1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NonTrivialTypeVisitor.h"
29#include "clang/AST/Randstruct.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/DiagnosticComment.h"
34#include "clang/Basic/HLSLRuntime.h"
35#include "clang/Basic/PartialDiagnostic.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
40#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
41#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42#include "clang/Sema/CXXFieldCollector.h"
43#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/DelayedDiagnostic.h"
45#include "clang/Sema/Initialization.h"
46#include "clang/Sema/Lookup.h"
47#include "clang/Sema/ParsedTemplate.h"
48#include "clang/Sema/Scope.h"
49#include "clang/Sema/ScopeInfo.h"
50#include "clang/Sema/SemaAMDGPU.h"
51#include "clang/Sema/SemaARM.h"
52#include "clang/Sema/SemaCUDA.h"
53#include "clang/Sema/SemaHLSL.h"
54#include "clang/Sema/SemaInternal.h"
55#include "clang/Sema/SemaObjC.h"
56#include "clang/Sema/SemaOpenACC.h"
57#include "clang/Sema/SemaOpenMP.h"
58#include "clang/Sema/SemaPPC.h"
59#include "clang/Sema/SemaRISCV.h"
60#include "clang/Sema/SemaSYCL.h"
61#include "clang/Sema/SemaSwift.h"
62#include "clang/Sema/SemaWasm.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/STLForwardCompat.h"
66#include "llvm/ADT/ScopeExit.h"
67#include "llvm/ADT/SmallPtrSet.h"
68#include "llvm/ADT/SmallString.h"
69#include "llvm/ADT/StringExtras.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/Support/SaveAndRestore.h"
72#include "llvm/TargetParser/Triple.h"
73#include <algorithm>
74#include <cstring>
75#include <optional>
76#include <unordered_map>
77
78using namespace clang;
79using namespace sema;
80
81Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
82 if (OwnedType) {
83 Decl *Group[2] = { OwnedType, Ptr };
84 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
85 }
86
87 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
88}
89
90namespace {
91
92class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
93 public:
94 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
95 bool AllowTemplates = false,
96 bool AllowNonTemplates = true)
97 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
98 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
99 WantExpressionKeywords = false;
100 WantCXXNamedCasts = false;
101 WantRemainingKeywords = false;
102 }
103
104 bool ValidateCandidate(const TypoCorrection &candidate) override {
105 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
106 if (!AllowInvalidDecl && ND->isInvalidDecl())
107 return false;
108
109 if (getAsTypeTemplateDecl(D: ND))
110 return AllowTemplates;
111
112 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
113 if (!IsType)
114 return false;
115
116 if (AllowNonTemplates)
117 return true;
118
119 // An injected-class-name of a class template (specialization) is valid
120 // as a template or as a non-template.
121 if (AllowTemplates) {
122 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
123 if (!RD || !RD->isInjectedClassName())
124 return false;
125 RD = cast<CXXRecordDecl>(Val: RD->getDeclContext());
126 return RD->getDescribedClassTemplate() ||
127 isa<ClassTemplateSpecializationDecl>(Val: RD);
128 }
129
130 return false;
131 }
132
133 return !WantClassName && candidate.isKeyword();
134 }
135
136 std::unique_ptr<CorrectionCandidateCallback> clone() override {
137 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
138 }
139
140 private:
141 bool AllowInvalidDecl;
142 bool WantClassName;
143 bool AllowTemplates;
144 bool AllowNonTemplates;
145};
146
147} // end anonymous namespace
148
149void Sema::checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
150 TypeDecl *TD, SourceLocation NameLoc) {
151 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
152 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
153 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
154 FoundRD->isInjectedClassName() &&
155 declaresSameEntity(D1: LookupRD, D2: cast<Decl>(Val: FoundRD->getParent()))) {
156 Diag(Loc: NameLoc,
157 DiagID: DCK == DiagCtorKind::Typename
158 ? diag::ext_out_of_line_qualified_id_type_names_constructor
159 : diag::err_out_of_line_qualified_id_type_names_constructor)
160 << TD->getIdentifier() << /*Type=*/1
161 << 0 /*if any keyword was present, it was 'typename'*/;
162 }
163
164 DiagnoseUseOfDecl(D: TD, Locs: NameLoc);
165 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
181lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
191 if (BaseRD) {
192 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
193 Val: Base.getType().getCanonicalType())) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
206 if (const ClassTemplatePartialSpecializationDecl *PS =
207 CTD->findPartialSpecialization(T: Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(Name: &II)) {
215 if (!isa<TypeDecl>(Val: ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
236static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(Val: DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
257 // allowed. We'll fully resolve the lookup during template instantiation.
258 S.Diag(Loc: NameLoc, DiagID: diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD).getTypePtr());
262 QualType T =
263 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
271 DepTL.setElaboratedKeywordLoc(SourceLocation());
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
274}
275
276ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
277 Scope *S, CXXScopeSpec *SS, bool isClassName,
278 bool HasTrailingDot, ParsedType ObjectTypePtr,
279 bool IsCtorOrDtorName,
280 bool WantNontrivialTypeSourceInfo,
281 bool IsClassTemplateDeductionContext,
282 ImplicitTypenameContext AllowImplicitTypename,
283 IdentifierInfo **CorrectedII) {
284 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
285 // FIXME: Consider allowing this outside C++1z mode as an extension.
286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
288 !HasTrailingDot;
289
290 // Determine where we will perform name lookup.
291 DeclContext *LookupCtx = nullptr;
292 if (ObjectTypePtr) {
293 QualType ObjectType = ObjectTypePtr.get();
294 if (ObjectType->isRecordType())
295 LookupCtx = computeDeclContext(T: ObjectType);
296 } else if (SS && SS->isNotEmpty()) {
297 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
298
299 if (!LookupCtx) {
300 if (isDependentScopeSpecifier(SS: *SS)) {
301 // C++ [temp.res]p3:
302 // A qualified-id that refers to a type and in which the
303 // nested-name-specifier depends on a template-parameter (14.6.2)
304 // shall be prefixed by the keyword typename to indicate that the
305 // qualified-id denotes a type, forming an
306 // elaborated-type-specifier (7.1.5.3).
307 //
308 // We therefore do not perform any name lookup if the result would
309 // refer to a member of an unknown specialization.
310 // In C++2a, in several contexts a 'typename' is not required. Also
311 // allow this as an extension.
312 if (IsImplicitTypename) {
313 if (AllowImplicitTypename == ImplicitTypenameContext::No)
314 return nullptr;
315 SourceLocation QualifiedLoc = SS->getRange().getBegin();
316 // FIXME: Defer the diagnostic after we build the type and use it.
317 auto DB = DiagCompat(Loc: QualifiedLoc, CompatDiagId: diag_compat::implicit_typename)
318 << Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
319 NNS: SS->getScopeRep(), Name: &II);
320 if (!getLangOpts().CPlusPlus20)
321 DB << FixItHint::CreateInsertion(InsertionLoc: QualifiedLoc, Code: "typename ");
322 }
323
324 // We know from the grammar that this name refers to a type,
325 // so build a dependent node to describe the type.
326 if (WantNontrivialTypeSourceInfo)
327 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
328 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
329 .get();
330
331 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
332 QualType T = CheckTypenameType(
333 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
334 : ElaboratedTypeKeyword::None,
335 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
336 return ParsedType::make(P: T);
337 }
338
339 return nullptr;
340 }
341
342 if (!LookupCtx->isDependentContext() &&
343 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
344 return nullptr;
345 }
346
347 // In the case where we know that the identifier is a class name, we know that
348 // it is a type declaration (struct, class, union or enum) so we can use tag
349 // name lookup.
350 //
351 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
352 // the component name of the type-name or simple-template-id is type-only.
353 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
354 LookupResult Result(*this, &II, NameLoc, Kind);
355 if (LookupCtx) {
356 // Perform "qualified" name lookup into the declaration context we
357 // computed, which is either the type of the base of a member access
358 // expression or the declaration context associated with a prior
359 // nested-name-specifier.
360 LookupQualifiedName(R&: Result, LookupCtx);
361
362 if (ObjectTypePtr && Result.empty()) {
363 // C++ [basic.lookup.classref]p3:
364 // If the unqualified-id is ~type-name, the type-name is looked up
365 // in the context of the entire postfix-expression. If the type T of
366 // the object expression is of a class type C, the type-name is also
367 // looked up in the scope of class C. At least one of the lookups shall
368 // find a name that refers to (possibly cv-qualified) T.
369 LookupName(R&: Result, S);
370 }
371 } else {
372 // Perform unqualified name lookup.
373 LookupName(R&: Result, S);
374
375 // For unqualified lookup in a class template in MSVC mode, look into
376 // dependent base classes where the primary class template is known.
377 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
378 if (ParsedType TypeInBase =
379 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
380 return TypeInBase;
381 }
382 }
383
384 NamedDecl *IIDecl = nullptr;
385 UsingShadowDecl *FoundUsingShadow = nullptr;
386 switch (Result.getResultKind()) {
387 case LookupResultKind::NotFound:
388 if (CorrectedII) {
389 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
390 AllowDeducedTemplate);
391 TypoCorrection Correction =
392 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind, S, SS, CCC,
393 Mode: CorrectTypoKind::ErrorRecovery);
394 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
395 TemplateTy Template;
396 bool MemberOfUnknownSpecialization;
397 UnqualifiedId TemplateName;
398 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
399 NestedNameSpecifier NNS = Correction.getCorrectionSpecifier();
400 CXXScopeSpec NewSS, *NewSSPtr = SS;
401 if (SS && NNS) {
402 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
403 NewSSPtr = &NewSS;
404 }
405 if (Correction && (NNS || NewII != &II) &&
406 // Ignore a correction to a template type as the to-be-corrected
407 // identifier is not a template (typo correction for template names
408 // is handled elsewhere).
409 !(getLangOpts().CPlusPlus && NewSSPtr &&
410 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
411 Template, MemberOfUnknownSpecialization))) {
412 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
413 isClassName, HasTrailingDot, ObjectTypePtr,
414 IsCtorOrDtorName,
415 WantNontrivialTypeSourceInfo,
416 IsClassTemplateDeductionContext);
417 if (Ty) {
418 diagnoseTypo(Correction,
419 TypoDiag: PDiag(DiagID: diag::err_unknown_type_or_class_name_suggest)
420 << Result.getLookupName() << isClassName);
421 if (SS && NNS)
422 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
423 *CorrectedII = NewII;
424 return Ty;
425 }
426 }
427 }
428 Result.suppressDiagnostics();
429 return nullptr;
430 case LookupResultKind::NotFoundInCurrentInstantiation:
431 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
432 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
433 NNS: SS->getScopeRep(), Name: &II);
434 TypeLocBuilder TLB;
435 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
436 TL.setElaboratedKeywordLoc(SourceLocation());
437 TL.setQualifierLoc(SS->getWithLocInContext(Context));
438 TL.setNameLoc(NameLoc);
439 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
440 }
441 [[fallthrough]];
442 case LookupResultKind::FoundOverloaded:
443 case LookupResultKind::FoundUnresolvedValue:
444 Result.suppressDiagnostics();
445 return nullptr;
446
447 case LookupResultKind::Ambiguous:
448 // Recover from type-hiding ambiguities by hiding the type. We'll
449 // do the lookup again when looking for an object, and we can
450 // diagnose the error then. If we don't do this, then the error
451 // about hiding the type will be immediately followed by an error
452 // that only makes sense if the identifier was treated like a type.
453 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
454 Result.suppressDiagnostics();
455 return nullptr;
456 }
457
458 // Look to see if we have a type anywhere in the list of results.
459 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
460 Res != ResEnd; ++Res) {
461 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
462 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
463 Val: RealRes) ||
464 (AllowDeducedTemplate && getAsTypeTemplateDecl(D: RealRes))) {
465 if (!IIDecl ||
466 // Make the selection of the recovery decl deterministic.
467 RealRes->getLocation() < IIDecl->getLocation()) {
468 IIDecl = RealRes;
469 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
470 }
471 }
472 }
473
474 if (!IIDecl) {
475 // None of the entities we found is a type, so there is no way
476 // to even assume that the result is a type. In this case, don't
477 // complain about the ambiguity. The parser will either try to
478 // perform this lookup again (e.g., as an object name), which
479 // will produce the ambiguity, or will complain that it expected
480 // a type name.
481 Result.suppressDiagnostics();
482 return nullptr;
483 }
484
485 // We found a type within the ambiguous lookup; diagnose the
486 // ambiguity and then return that type. This might be the right
487 // answer, or it might not be, but it suppresses any attempt to
488 // perform the name lookup again.
489 break;
490
491 case LookupResultKind::Found:
492 IIDecl = Result.getFoundDecl();
493 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
494 break;
495 }
496
497 assert(IIDecl && "Didn't find decl");
498
499 TypeLocBuilder TLB;
500 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
501 checkTypeDeclType(LookupCtx,
502 DCK: IsImplicitTypename ? DiagCtorKind::Implicit
503 : DiagCtorKind::None,
504 TD, NameLoc);
505 QualType T;
506 if (FoundUsingShadow) {
507 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None,
508 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
509 D: FoundUsingShadow);
510 if (!WantNontrivialTypeSourceInfo)
511 return ParsedType::make(P: T);
512 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
513 QualifierLoc: SS ? SS->getWithLocInContext(Context)
514 : NestedNameSpecifierLoc(),
515 NameLoc);
516 } else if (auto *Tag = dyn_cast<TagDecl>(Val: TD)) {
517 T = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
518 Qualifier: SS ? SS->getScopeRep() : std::nullopt, TD: Tag,
519 /*OwnsTag=*/false);
520 if (!WantNontrivialTypeSourceInfo)
521 return ParsedType::make(P: T);
522 auto TL = TLB.push<TagTypeLoc>(T);
523 TL.setElaboratedKeywordLoc(SourceLocation());
524 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
525 : NestedNameSpecifierLoc());
526 TL.setNameLoc(NameLoc);
527 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD);
528 TN && !isa<ObjCTypeParamDecl>(Val: TN)) {
529 T = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
530 Qualifier: SS ? SS->getScopeRep() : std::nullopt, Decl: TN);
531 if (!WantNontrivialTypeSourceInfo)
532 return ParsedType::make(P: T);
533 TLB.push<TypedefTypeLoc>(T).set(
534 /*ElaboratedKeywordLoc=*/SourceLocation(),
535 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
536 NameLoc);
537 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD)) {
538 T = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
539 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
540 D: UD);
541 if (!WantNontrivialTypeSourceInfo)
542 return ParsedType::make(P: T);
543 TLB.push<UnresolvedUsingTypeLoc>(T).set(
544 /*ElaboratedKeywordLoc=*/SourceLocation(),
545 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
546 NameLoc);
547 } else {
548 T = Context.getTypeDeclType(Decl: TD);
549 if (!WantNontrivialTypeSourceInfo)
550 return ParsedType::make(P: T);
551 if (isa<ObjCTypeParamType>(Val: T))
552 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
553 else
554 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
555 }
556 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
557 }
558
559 if (getLangOpts().HLSL) {
560 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
561 Val: getAsTemplateNameDecl(D: IIDecl, /*AllowFunctionTemplates=*/false,
562 /*AllowDependent=*/false))) {
563 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(Template: TD, NameLoc);
564 if (!ShorthandTy.isNull())
565 return ParsedType::make(P: ShorthandTy);
566 }
567 }
568
569 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
570 (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc);
571 if (!HasTrailingDot) {
572 // FIXME: Support UsingType for this case.
573 QualType T = Context.getObjCInterfaceType(Decl: IDecl);
574 if (!WantNontrivialTypeSourceInfo)
575 return ParsedType::make(P: T);
576 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
577 TL.setNameLoc(NameLoc);
578 // FIXME: Pass in this source location.
579 TL.setNameEndLoc(NameLoc);
580 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
581 }
582 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
583 (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc);
584 // Recover with 'int'
585 return ParsedType::make(P: Context.IntTy);
586 } else if (AllowDeducedTemplate) {
587 if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) {
588 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
589 // FIXME: Support UsingType here.
590 TemplateName Template = Context.getQualifiedTemplateName(
591 Qualifier: SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
592 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
593 QualType T = Context.getDeducedTemplateSpecializationType(
594 DK: DeducedKind::Undeduced, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None,
595 Template);
596 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
597 TL.setElaboratedKeywordLoc(SourceLocation());
598 TL.setNameLoc(NameLoc);
599 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
600 : NestedNameSpecifierLoc());
601 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
602 }
603 }
604
605 // As it's not plausibly a type, suppress diagnostics.
606 Result.suppressDiagnostics();
607 return nullptr;
608}
609
610// Builds a fake NNS for the given decl context.
611static NestedNameSpecifier
612synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
613 for (;; DC = DC->getLookupParent()) {
614 DC = DC->getPrimaryContext();
615 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
616 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
617 return NestedNameSpecifier(Context, ND, std::nullopt);
618 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
619 return NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
620 if (isa<TranslationUnitDecl>(Val: DC))
621 return NestedNameSpecifier::getGlobal();
622 }
623 llvm_unreachable("something isn't in TU scope?");
624}
625
626/// Find the parent class with dependent bases of the innermost enclosing method
627/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
628/// up allowing unqualified dependent type names at class-level, which MSVC
629/// correctly rejects.
630static const CXXRecordDecl *
631findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
632 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
633 DC = DC->getPrimaryContext();
634 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
635 if (MD->getParent()->hasAnyDependentBases())
636 return MD->getParent();
637 }
638 return nullptr;
639}
640
641ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
642 SourceLocation NameLoc,
643 bool IsTemplateTypeArg) {
644 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
645
646 NestedNameSpecifier NNS = std::nullopt;
647 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
648 // If we weren't able to parse a default template argument, delay lookup
649 // until instantiation time by making a non-dependent DependentTypeName. We
650 // pretend we saw a NestedNameSpecifier referring to the current scope, and
651 // lookup is retried.
652 // FIXME: This hurts our diagnostic quality, since we get errors like "no
653 // type named 'Foo' in 'current_namespace'" when the user didn't write any
654 // name specifiers.
655 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
656 Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II;
657 } else if (const CXXRecordDecl *RD =
658 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
659 // Build a DependentNameType that will perform lookup into RD at
660 // instantiation time.
661 NNS = NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
662
663 // Diagnose that this identifier was undeclared, and retry the lookup during
664 // template instantiation.
665 Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II
666 << RD;
667 } else {
668 // This is not a situation that we should recover from.
669 return ParsedType();
670 }
671
672 QualType T =
673 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
674
675 // Build type location information. We synthesized the qualifier, so we have
676 // to build a fake NestedNameSpecifierLoc.
677 NestedNameSpecifierLocBuilder NNSLocBuilder;
678 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
679 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
680
681 TypeLocBuilder Builder;
682 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
683 DepTL.setNameLoc(NameLoc);
684 DepTL.setElaboratedKeywordLoc(SourceLocation());
685 DepTL.setQualifierLoc(QualifierLoc);
686 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
687}
688
689DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
690 // Do a tag name lookup in this scope.
691 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
692 LookupName(R, S, AllowBuiltinCreation: false);
693 R.suppressDiagnostics();
694 if (R.getResultKind() == LookupResultKind::Found)
695 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
696 switch (TD->getTagKind()) {
697 case TagTypeKind::Struct:
698 return DeclSpec::TST_struct;
699 case TagTypeKind::Interface:
700 return DeclSpec::TST_interface;
701 case TagTypeKind::Union:
702 return DeclSpec::TST_union;
703 case TagTypeKind::Class:
704 return DeclSpec::TST_class;
705 case TagTypeKind::Enum:
706 return DeclSpec::TST_enum;
707 }
708 }
709
710 return DeclSpec::TST_unspecified;
711}
712
713bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
714 if (!CurContext->isRecord())
715 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
716
717 switch (SS->getScopeRep().getKind()) {
718 case NestedNameSpecifier::Kind::MicrosoftSuper:
719 return true;
720 case NestedNameSpecifier::Kind::Type: {
721 QualType T(SS->getScopeRep().getAsType(), 0);
722 for (const auto &Base : cast<CXXRecordDecl>(Val: CurContext)->bases())
723 if (Context.hasSameUnqualifiedType(T1: T, T2: Base.getType()))
724 return true;
725 [[fallthrough]];
726 }
727 default:
728 return S->isFunctionPrototypeScope();
729 }
730}
731
732void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
733 SourceLocation IILoc,
734 Scope *S,
735 CXXScopeSpec *SS,
736 ParsedType &SuggestedType,
737 bool IsTemplateName) {
738 // Don't report typename errors for editor placeholders.
739 if (II->isEditorPlaceholder())
740 return;
741 // We don't have anything to suggest (yet).
742 SuggestedType = nullptr;
743
744 // There may have been a typo in the name of the type. Look up typo
745 // results, in case we have something that we can suggest.
746 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
747 /*AllowTemplates=*/IsTemplateName,
748 /*AllowNonTemplates=*/!IsTemplateName);
749 if (TypoCorrection Corrected =
750 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
751 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
752 // FIXME: Support error recovery for the template-name case.
753 bool CanRecover = !IsTemplateName;
754 if (Corrected.isKeyword()) {
755 // We corrected to a keyword.
756 diagnoseTypo(Correction: Corrected,
757 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
758 : diag::err_unknown_typename_suggest)
759 << II);
760 II = Corrected.getCorrectionAsIdentifierInfo();
761 } else {
762 // We found a similarly-named type or interface; suggest that.
763 if (!SS || !SS->isSet()) {
764 diagnoseTypo(Correction: Corrected,
765 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
766 : diag::err_unknown_typename_suggest)
767 << II, ErrorRecovery: CanRecover);
768 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
769 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
770 bool DroppedSpecifier =
771 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
772 diagnoseTypo(Correction: Corrected,
773 TypoDiag: PDiag(DiagID: IsTemplateName
774 ? diag::err_no_member_template_suggest
775 : diag::err_unknown_nested_typename_suggest)
776 << II << DC << DroppedSpecifier << SS->getRange(),
777 ErrorRecovery: CanRecover);
778 } else {
779 llvm_unreachable("could not have corrected a typo here");
780 }
781
782 if (!CanRecover)
783 return;
784
785 CXXScopeSpec tmpSS;
786 if (Corrected.getCorrectionSpecifier())
787 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
788 R: SourceRange(IILoc));
789 // FIXME: Support class template argument deduction here.
790 SuggestedType =
791 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
792 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
793 /*IsCtorOrDtorName=*/false,
794 /*WantNontrivialTypeSourceInfo=*/true);
795 }
796 return;
797 }
798
799 if (getLangOpts().CPlusPlus && !IsTemplateName) {
800 // See if II is a class template that the user forgot to pass arguments to.
801 UnqualifiedId Name;
802 Name.setIdentifier(Id: II, IdLoc: IILoc);
803 CXXScopeSpec EmptySS;
804 TemplateTy TemplateResult;
805 bool MemberOfUnknownSpecialization;
806 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
807 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
808 MemberOfUnknownSpecialization) == TNK_Type_template) {
809 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
810 return;
811 }
812 }
813
814 // FIXME: Should we move the logic that tries to recover from a missing tag
815 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
816
817 if (!SS || (!SS->isSet() && !SS->isInvalid()))
818 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template
819 : diag::err_unknown_typename)
820 << II;
821 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
822 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template
823 : diag::err_typename_nested_not_found)
824 << II << DC << SS->getRange();
825 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
826 SuggestedType =
827 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
828 } else if (isDependentScopeSpecifier(SS: *SS)) {
829 unsigned DiagID = diag::err_typename_missing;
830 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
831 DiagID = diag::ext_typename_missing;
832
833 SuggestedType =
834 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
835
836 Diag(Loc: SS->getRange().getBegin(), DiagID)
837 << GetTypeFromParser(Ty: SuggestedType)
838 << SourceRange(SS->getRange().getBegin(), IILoc)
839 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
840 } else {
841 assert(SS && SS->isInvalid() &&
842 "Invalid scope specifier has already been diagnosed");
843 }
844}
845
846/// Determine whether the given result set contains either a type name
847/// or
848static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
849 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
850 NextToken.is(K: tok::less);
851
852 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
853 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
854 return true;
855
856 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
857 return true;
858 }
859
860 return false;
861}
862
863static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
864 Scope *S, CXXScopeSpec &SS,
865 IdentifierInfo *&Name,
866 SourceLocation NameLoc) {
867 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
868 SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
869 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
870 StringRef FixItTagName;
871 switch (Tag->getTagKind()) {
872 case TagTypeKind::Class:
873 FixItTagName = "class ";
874 break;
875
876 case TagTypeKind::Enum:
877 FixItTagName = "enum ";
878 break;
879
880 case TagTypeKind::Struct:
881 FixItTagName = "struct ";
882 break;
883
884 case TagTypeKind::Interface:
885 FixItTagName = "__interface ";
886 break;
887
888 case TagTypeKind::Union:
889 FixItTagName = "union ";
890 break;
891 }
892
893 StringRef TagName = FixItTagName.drop_back();
894 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag)
895 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
896 << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName);
897
898 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
899 I != IEnd; ++I)
900 SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type)
901 << Name << TagName;
902
903 // Replace lookup results with just the tag decl.
904 Result.clear(Kind: Sema::LookupTagName);
905 SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType());
906 return true;
907 }
908
909 return false;
910}
911
912Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
913 IdentifierInfo *&Name,
914 SourceLocation NameLoc,
915 const Token &NextToken,
916 CorrectionCandidateCallback *CCC) {
917 DeclarationNameInfo NameInfo(Name, NameLoc);
918 ObjCMethodDecl *CurMethod = getCurMethodDecl();
919
920 assert(NextToken.isNot(tok::coloncolon) &&
921 "parse nested name specifiers before calling ClassifyName");
922 if (getLangOpts().CPlusPlus && SS.isSet() &&
923 isCurrentClassName(II: *Name, S, SS: &SS)) {
924 // Per [class.qual]p2, this names the constructors of SS, not the
925 // injected-class-name. We don't have a classification for that.
926 // There's not much point caching this result, since the parser
927 // will reject it later.
928 return NameClassification::Unknown();
929 }
930
931 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
932 LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(),
933 /*AllowBuiltinCreation=*/!CurMethod);
934
935 if (SS.isInvalid())
936 return NameClassification::Error();
937
938 // For unqualified lookup in a class template in MSVC mode, look into
939 // dependent base classes where the primary class template is known.
940 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
941 if (ParsedType TypeInBase =
942 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
943 return TypeInBase;
944 }
945
946 // Perform lookup for Objective-C instance variables (including automatically
947 // synthesized instance variables), if we're in an Objective-C method.
948 // FIXME: This lookup really, really needs to be folded in to the normal
949 // unqualified lookup mechanism.
950 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
951 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
952 if (Ivar.isInvalid())
953 return NameClassification::Error();
954 if (Ivar.isUsable())
955 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
956
957 // We defer builtin creation until after ivar lookup inside ObjC methods.
958 if (Result.empty())
959 LookupBuiltin(R&: Result);
960 }
961
962 bool SecondTry = false;
963 bool IsFilteredTemplateName = false;
964
965Corrected:
966 switch (Result.getResultKind()) {
967 case LookupResultKind::NotFound:
968 // If an unqualified-id is followed by a '(', then we have a function
969 // call.
970 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
971 // In C++, this is an ADL-only call.
972 // FIXME: Reference?
973 if (getLangOpts().CPlusPlus)
974 return NameClassification::UndeclaredNonType();
975
976 // C90 6.3.2.2:
977 // If the expression that precedes the parenthesized argument list in a
978 // function call consists solely of an identifier, and if no
979 // declaration is visible for this identifier, the identifier is
980 // implicitly declared exactly as if, in the innermost block containing
981 // the function call, the declaration
982 //
983 // extern int identifier ();
984 //
985 // appeared.
986 //
987 // We also allow this in C99 as an extension. However, this is not
988 // allowed in all language modes as functions without prototypes may not
989 // be supported.
990 if (getLangOpts().implicitFunctionsAllowed()) {
991 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
992 return NameClassification::NonType(D);
993 }
994 }
995
996 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
997 // In C++20 onwards, this could be an ADL-only call to a function
998 // template, and we're required to assume that this is a template name.
999 //
1000 // FIXME: Find a way to still do typo correction in this case.
1001 TemplateName Template =
1002 Context.getAssumedTemplateName(Name: NameInfo.getName());
1003 return NameClassification::UndeclaredTemplate(Name: Template);
1004 }
1005
1006 // In C, we first see whether there is a tag type by the same name, in
1007 // which case it's likely that the user just forgot to write "enum",
1008 // "struct", or "union".
1009 if (!getLangOpts().CPlusPlus && !SecondTry &&
1010 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1011 break;
1012 }
1013
1014 // Perform typo correction to determine if there is another name that is
1015 // close to this name.
1016 if (!SecondTry && CCC) {
1017 SecondTry = true;
1018 if (TypoCorrection Corrected =
1019 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
1020 SS: &SS, CCC&: *CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
1021 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1022 unsigned QualifiedDiag = diag::err_no_member_suggest;
1023
1024 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1025 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1026 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1027 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
1028 UnqualifiedDiag = diag::err_no_template_suggest;
1029 QualifiedDiag = diag::err_no_member_template_suggest;
1030 } else if (UnderlyingFirstDecl &&
1031 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
1032 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
1033 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
1034 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1035 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1036 }
1037
1038 if (SS.isEmpty()) {
1039 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1040 } else {// FIXME: is this even reachable? Test it.
1041 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1042 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1043 Name->getName() == CorrectedStr;
1044 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1045 << Name << computeDeclContext(SS, EnteringContext: false)
1046 << DroppedSpecifier << SS.getRange());
1047 }
1048
1049 // Update the name, so that the caller has the new name.
1050 Name = Corrected.getCorrectionAsIdentifierInfo();
1051
1052 // Typo correction corrected to a keyword.
1053 if (Corrected.isKeyword())
1054 return Name;
1055
1056 // Also update the LookupResult...
1057 // FIXME: This should probably go away at some point
1058 Result.clear();
1059 Result.setLookupName(Corrected.getCorrection());
1060 if (FirstDecl)
1061 Result.addDecl(D: FirstDecl);
1062
1063 // If we found an Objective-C instance variable, let
1064 // LookupInObjCMethod build the appropriate expression to
1065 // reference the ivar.
1066 // FIXME: This is a gross hack.
1067 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1068 DeclResult R =
1069 ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1070 if (R.isInvalid())
1071 return NameClassification::Error();
1072 if (R.isUsable())
1073 return NameClassification::NonType(D: Ivar);
1074 }
1075
1076 goto Corrected;
1077 }
1078 }
1079
1080 // We failed to correct; just fall through and let the parser deal with it.
1081 Result.suppressDiagnostics();
1082 return NameClassification::Unknown();
1083
1084 case LookupResultKind::NotFoundInCurrentInstantiation: {
1085 // We performed name lookup into the current instantiation, and there were
1086 // dependent bases, so we treat this result the same way as any other
1087 // dependent nested-name-specifier.
1088
1089 // C++ [temp.res]p2:
1090 // A name used in a template declaration or definition and that is
1091 // dependent on a template-parameter is assumed not to name a type
1092 // unless the applicable name lookup finds a type name or the name is
1093 // qualified by the keyword typename.
1094 //
1095 // FIXME: If the next token is '<', we might want to ask the parser to
1096 // perform some heroics to see if we actually have a
1097 // template-argument-list, which would indicate a missing 'template'
1098 // keyword here.
1099 return NameClassification::DependentNonType();
1100 }
1101
1102 case LookupResultKind::Found:
1103 case LookupResultKind::FoundOverloaded:
1104 case LookupResultKind::FoundUnresolvedValue:
1105 break;
1106
1107 case LookupResultKind::Ambiguous:
1108 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1109 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false)) {
1111 // C++ [temp.local]p3:
1112 // A lookup that finds an injected-class-name (10.2) can result in an
1113 // ambiguity in certain cases (for example, if it is found in more than
1114 // one base class). If all of the injected-class-names that are found
1115 // refer to specializations of the same class template, and if the name
1116 // is followed by a template-argument-list, the reference refers to the
1117 // class template itself and not a specialization thereof, and is not
1118 // ambiguous.
1119 //
1120 // This filtering can make an ambiguous result into an unambiguous one,
1121 // so try again after filtering out template names.
1122 FilterAcceptableTemplateNames(R&: Result);
1123 if (!Result.isAmbiguous()) {
1124 IsFilteredTemplateName = true;
1125 break;
1126 }
1127 }
1128
1129 // Diagnose the ambiguity and return an error.
1130 return NameClassification::Error();
1131 }
1132
1133 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1134 (IsFilteredTemplateName ||
1135 hasAnyAcceptableTemplateNames(
1136 R&: Result, /*AllowFunctionTemplates=*/true,
1137 /*AllowDependent=*/false,
1138 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1139 getLangOpts().CPlusPlus20))) {
1140 // C++ [temp.names]p3:
1141 // After name lookup (3.4) finds that a name is a template-name or that
1142 // an operator-function-id or a literal- operator-id refers to a set of
1143 // overloaded functions any member of which is a function template if
1144 // this is followed by a <, the < is always taken as the delimiter of a
1145 // template-argument-list and never as the less-than operator.
1146 // C++2a [temp.names]p2:
1147 // A name is also considered to refer to a template if it is an
1148 // unqualified-id followed by a < and name lookup finds either one
1149 // or more functions or finds nothing.
1150 if (!IsFilteredTemplateName)
1151 FilterAcceptableTemplateNames(R&: Result);
1152
1153 bool IsFunctionTemplate;
1154 bool IsVarTemplate;
1155 TemplateName Template;
1156 if (Result.end() - Result.begin() > 1) {
1157 IsFunctionTemplate = true;
1158 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1159 End: Result.end());
1160 } else if (!Result.empty()) {
1161 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1162 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1163 /*AllowDependent=*/false));
1164 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1165 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1166
1167 UsingShadowDecl *FoundUsingShadow =
1168 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1169 assert(!FoundUsingShadow ||
1170 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1171 Template = Context.getQualifiedTemplateName(
1172 Qualifier: SS.getScopeRep(),
1173 /*TemplateKeyword=*/false,
1174 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1175 } else {
1176 // All results were non-template functions. This is a function template
1177 // name.
1178 IsFunctionTemplate = true;
1179 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1180 }
1181
1182 if (IsFunctionTemplate) {
1183 // Function templates always go through overload resolution, at which
1184 // point we'll perform the various checks (e.g., accessibility) we need
1185 // to based on which function we selected.
1186 Result.suppressDiagnostics();
1187
1188 return NameClassification::FunctionTemplate(Name: Template);
1189 }
1190
1191 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1192 : NameClassification::TypeTemplate(Name: Template);
1193 }
1194
1195 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1196 QualType T;
1197 TypeLocBuilder TLB;
1198 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found)) {
1199 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1200 D: USD);
1201 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1202 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1203 } else {
1204 T = Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1205 Decl: Type);
1206 if (isa<TagType>(Val: T)) {
1207 auto TTL = TLB.push<TagTypeLoc>(T);
1208 TTL.setElaboratedKeywordLoc(SourceLocation());
1209 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1210 TTL.setNameLoc(NameLoc);
1211 } else if (isa<TypedefType>(Val: T)) {
1212 TLB.push<TypedefTypeLoc>(T).set(
1213 /*ElaboratedKeywordLoc=*/SourceLocation(),
1214 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1215 } else if (isa<UnresolvedUsingType>(Val: T)) {
1216 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1217 /*ElaboratedKeywordLoc=*/SourceLocation(),
1218 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1219 } else {
1220 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1221 }
1222 }
1223 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
1224 };
1225
1226 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1227 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1228 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1229 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1230 return BuildTypeFor(Type, *Result.begin());
1231 }
1232
1233 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1234 if (!Class) {
1235 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1236 if (ObjCCompatibleAliasDecl *Alias =
1237 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1238 Class = Alias->getClassInterface();
1239 }
1240
1241 if (Class) {
1242 DiagnoseUseOfDecl(D: Class, Locs: NameLoc);
1243
1244 if (NextToken.is(K: tok::period)) {
1245 // Interface. <something> is parsed as a property reference expression.
1246 // Just return "unknown" as a fall-through for now.
1247 Result.suppressDiagnostics();
1248 return NameClassification::Unknown();
1249 }
1250
1251 QualType T = Context.getObjCInterfaceType(Decl: Class);
1252 return ParsedType::make(P: T);
1253 }
1254
1255 if (isa<ConceptDecl>(Val: FirstDecl)) {
1256 // We want to preserve the UsingShadowDecl for concepts.
1257 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1258 return NameClassification::Concept(Name: TemplateName(USD));
1259 return NameClassification::Concept(
1260 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1261 }
1262
1263 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1264 (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc);
1265 return NameClassification::Error();
1266 }
1267
1268 // We can have a type template here if we're classifying a template argument.
1269 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1270 !isa<VarTemplateDecl>(Val: FirstDecl))
1271 return NameClassification::TypeTemplate(
1272 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1273
1274 // Check for a tag type hidden by a non-type decl in a few cases where it
1275 // seems likely a type is wanted instead of the non-type that was found.
1276 bool NextIsOp = NextToken.isOneOf(Ks: tok::amp, Ks: tok::star);
1277 if ((NextToken.is(K: tok::identifier) ||
1278 (NextIsOp &&
1279 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1280 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1281 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1282 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1283 return BuildTypeFor(Type, *Result.begin());
1284 }
1285
1286 // If we already know which single declaration is referenced, just annotate
1287 // that declaration directly. Defer resolving even non-overloaded class
1288 // member accesses, as we need to defer certain access checks until we know
1289 // the context.
1290 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1291 if (Result.isSingleResult() && !ADL &&
1292 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1293 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1294
1295 // Otherwise, this is an overload set that we will need to resolve later.
1296 Result.suppressDiagnostics();
1297 return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create(
1298 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1299 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1300 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1301}
1302
1303ExprResult
1304Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1305 SourceLocation NameLoc) {
1306 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1307 CXXScopeSpec SS;
1308 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1309 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1310}
1311
1312ExprResult
1313Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1314 IdentifierInfo *Name,
1315 SourceLocation NameLoc,
1316 bool IsAddressOfOperand) {
1317 DeclarationNameInfo NameInfo(Name, NameLoc);
1318 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1319 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1320 /*TemplateArgs=*/nullptr);
1321}
1322
1323ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1324 NamedDecl *Found,
1325 SourceLocation NameLoc,
1326 const Token &NextToken) {
1327 if (getCurMethodDecl() && SS.isEmpty())
1328 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1329 return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1330
1331 // Reconstruct the lookup result.
1332 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1333 Result.addDecl(D: Found);
1334 Result.resolveKind();
1335
1336 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1337 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1338}
1339
1340ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1341 // For an implicit class member access, transform the result into a member
1342 // access expression if necessary.
1343 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1344 if ((*ULE->decls_begin())->isCXXClassMember()) {
1345 CXXScopeSpec SS;
1346 SS.Adopt(Other: ULE->getQualifierLoc());
1347
1348 // Reconstruct the lookup result.
1349 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1350 LookupOrdinaryName);
1351 Result.setNamingClass(ULE->getNamingClass());
1352 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1353 Result.addDecl(D: *I, AS: I.getAccess());
1354 Result.resolveKind();
1355 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1356 TemplateArgs: nullptr, S);
1357 }
1358
1359 // Otherwise, this is already in the form we needed, and no further checks
1360 // are necessary.
1361 return ULE;
1362}
1363
1364Sema::TemplateNameKindForDiagnostics
1365Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1366 auto *TD = Name.getAsTemplateDecl();
1367 if (!TD)
1368 return TemplateNameKindForDiagnostics::DependentTemplate;
1369 if (isa<ClassTemplateDecl>(Val: TD))
1370 return TemplateNameKindForDiagnostics::ClassTemplate;
1371 if (isa<FunctionTemplateDecl>(Val: TD))
1372 return TemplateNameKindForDiagnostics::FunctionTemplate;
1373 if (isa<VarTemplateDecl>(Val: TD))
1374 return TemplateNameKindForDiagnostics::VarTemplate;
1375 if (isa<TypeAliasTemplateDecl>(Val: TD))
1376 return TemplateNameKindForDiagnostics::AliasTemplate;
1377 if (isa<TemplateTemplateParmDecl>(Val: TD))
1378 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1379 if (isa<ConceptDecl>(Val: TD))
1380 return TemplateNameKindForDiagnostics::Concept;
1381 return TemplateNameKindForDiagnostics::DependentTemplate;
1382}
1383
1384void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1385 assert(DC->getLexicalParent() == CurContext &&
1386 "The next DeclContext should be lexically contained in the current one.");
1387 CurContext = DC;
1388 S->setEntity(DC);
1389}
1390
1391void Sema::PopDeclContext() {
1392 assert(CurContext && "DeclContext imbalance!");
1393
1394 CurContext = CurContext->getLexicalParent();
1395 assert(CurContext && "Popped translation unit!");
1396}
1397
1398Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1399 Decl *D) {
1400 // Unlike PushDeclContext, the context to which we return is not necessarily
1401 // the containing DC of TD, because the new context will be some pre-existing
1402 // TagDecl definition instead of a fresh one.
1403 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1404 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1405 assert(CurContext && "skipping definition of undefined tag");
1406 // Start lookups from the parent of the current context; we don't want to look
1407 // into the pre-existing complete definition.
1408 S->setEntity(CurContext->getLookupParent());
1409 return Result;
1410}
1411
1412void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1413 CurContext = static_cast<decltype(CurContext)>(Context);
1414}
1415
1416void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1417 // C++0x [basic.lookup.unqual]p13:
1418 // A name used in the definition of a static data member of class
1419 // X (after the qualified-id of the static member) is looked up as
1420 // if the name was used in a member function of X.
1421 // C++0x [basic.lookup.unqual]p14:
1422 // If a variable member of a namespace is defined outside of the
1423 // scope of its namespace then any name used in the definition of
1424 // the variable member (after the declarator-id) is looked up as
1425 // if the definition of the variable member occurred in its
1426 // namespace.
1427 // Both of these imply that we should push a scope whose context
1428 // is the semantic context of the declaration. We can't use
1429 // PushDeclContext here because that context is not necessarily
1430 // lexically contained in the current context. Fortunately,
1431 // the containing scope should have the appropriate information.
1432
1433 assert(!S->getEntity() && "scope already has entity");
1434
1435#ifndef NDEBUG
1436 Scope *Ancestor = S->getParent();
1437 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1438 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1439#endif
1440
1441 CurContext = DC;
1442 S->setEntity(DC);
1443
1444 if (S->getParent()->isTemplateParamScope()) {
1445 // Also set the corresponding entities for all immediately-enclosing
1446 // template parameter scopes.
1447 EnterTemplatedContext(S: S->getParent(), DC);
1448 }
1449}
1450
1451void Sema::ExitDeclaratorContext(Scope *S) {
1452 assert(S->getEntity() == CurContext && "Context imbalance!");
1453
1454 // Switch back to the lexical context. The safety of this is
1455 // enforced by an assert in EnterDeclaratorContext.
1456 Scope *Ancestor = S->getParent();
1457 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1458 CurContext = Ancestor->getEntity();
1459
1460 // We don't need to do anything with the scope, which is going to
1461 // disappear.
1462}
1463
1464void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1465 assert(S->isTemplateParamScope() &&
1466 "expected to be initializing a template parameter scope");
1467
1468 // C++20 [temp.local]p7:
1469 // In the definition of a member of a class template that appears outside
1470 // of the class template definition, the name of a member of the class
1471 // template hides the name of a template-parameter of any enclosing class
1472 // templates (but not a template-parameter of the member if the member is a
1473 // class or function template).
1474 // C++20 [temp.local]p9:
1475 // In the definition of a class template or in the definition of a member
1476 // of such a template that appears outside of the template definition, for
1477 // each non-dependent base class (13.8.2.1), if the name of the base class
1478 // or the name of a member of the base class is the same as the name of a
1479 // template-parameter, the base class name or member name hides the
1480 // template-parameter name (6.4.10).
1481 //
1482 // This means that a template parameter scope should be searched immediately
1483 // after searching the DeclContext for which it is a template parameter
1484 // scope. For example, for
1485 // template<typename T> template<typename U> template<typename V>
1486 // void N::A<T>::B<U>::f(...)
1487 // we search V then B<U> (and base classes) then U then A<T> (and base
1488 // classes) then T then N then ::.
1489 unsigned ScopeDepth = getTemplateDepth(S);
1490 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1491 DeclContext *SearchDCAfterScope = DC;
1492 for (; DC; DC = DC->getLookupParent()) {
1493 if (const TemplateParameterList *TPL =
1494 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1495 unsigned DCDepth = TPL->getDepth() + 1;
1496 if (DCDepth > ScopeDepth)
1497 continue;
1498 if (ScopeDepth == DCDepth)
1499 SearchDCAfterScope = DC = DC->getLookupParent();
1500 break;
1501 }
1502 }
1503 S->setLookupEntity(SearchDCAfterScope);
1504 }
1505}
1506
1507void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1508 // We assume that the caller has already called
1509 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1510 FunctionDecl *FD = D->getAsFunction();
1511 if (!FD)
1512 return;
1513
1514 // Same implementation as PushDeclContext, but enters the context
1515 // from the lexical parent, rather than the top-level class.
1516 assert(CurContext == FD->getLexicalParent() &&
1517 "The next DeclContext should be lexically contained in the current one.");
1518 CurContext = FD;
1519 S->setEntity(CurContext);
1520
1521 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1522 ParmVarDecl *Param = FD->getParamDecl(i: P);
1523 // If the parameter has an identifier, then add it to the scope
1524 if (Param->getIdentifier()) {
1525 S->AddDecl(D: Param);
1526 IdResolver.AddDecl(D: Param);
1527 }
1528 }
1529}
1530
1531void Sema::ActOnExitFunctionContext() {
1532 // Same implementation as PopDeclContext, but returns to the lexical parent,
1533 // rather than the top-level class.
1534 assert(CurContext && "DeclContext imbalance!");
1535 CurContext = CurContext->getLexicalParent();
1536 assert(CurContext && "Popped translation unit!");
1537}
1538
1539/// Determine whether overloading is allowed for a new function
1540/// declaration considering prior declarations of the same name.
1541///
1542/// This routine determines whether overloading is possible, not
1543/// whether a new declaration actually overloads a previous one.
1544/// It will return true in C++ (where overloads are always permitted)
1545/// or, as a C extension, when either the new declaration or a
1546/// previous one is declared with the 'overloadable' attribute.
1547static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1548 ASTContext &Context,
1549 const FunctionDecl *New) {
1550 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1551 return true;
1552
1553 // Multiversion function declarations are not overloads in the
1554 // usual sense of that term, but lookup will report that an
1555 // overload set was found if more than one multiversion function
1556 // declaration is present for the same name. It is therefore
1557 // inadequate to assume that some prior declaration(s) had
1558 // the overloadable attribute; checking is required. Since one
1559 // declaration is permitted to omit the attribute, it is necessary
1560 // to check at least two; hence the 'any_of' check below. Note that
1561 // the overloadable attribute is implicitly added to declarations
1562 // that were required to have it but did not.
1563 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1564 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1565 return ND->hasAttr<OverloadableAttr>();
1566 });
1567 } else if (Previous.getResultKind() == LookupResultKind::Found)
1568 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1569
1570 return false;
1571}
1572
1573void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1574 // Move up the scope chain until we find the nearest enclosing
1575 // non-transparent context. The declaration will be introduced into this
1576 // scope.
1577 while (S->getEntity() && S->getEntity()->isTransparentContext())
1578 S = S->getParent();
1579
1580 // Add scoped declarations into their context, so that they can be
1581 // found later. Declarations without a context won't be inserted
1582 // into any context.
1583 if (AddToContext)
1584 CurContext->addDecl(D);
1585
1586 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1587 // are function-local declarations.
1588 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1589 return;
1590
1591 // Template instantiations should also not be pushed into scope.
1592 if (isa<FunctionDecl>(Val: D) &&
1593 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1594 return;
1595
1596 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1597 S->AddDecl(D);
1598 return;
1599 }
1600 // If this replaces anything in the current scope,
1601 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1602 IEnd = IdResolver.end();
1603 for (; I != IEnd; ++I) {
1604 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1605 S->RemoveDecl(D: *I);
1606 IdResolver.RemoveDecl(D: *I);
1607
1608 // Should only need to replace one decl.
1609 break;
1610 }
1611 }
1612
1613 S->AddDecl(D);
1614
1615 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1616 // Implicitly-generated labels may end up getting generated in an order that
1617 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1618 // the label at the appropriate place in the identifier chain.
1619 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1620 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1621 if (IDC == CurContext) {
1622 if (!S->isDeclScope(D: *I))
1623 continue;
1624 } else if (IDC->Encloses(DC: CurContext))
1625 break;
1626 }
1627
1628 IdResolver.InsertDeclAfter(Pos: I, D);
1629 } else {
1630 IdResolver.AddDecl(D);
1631 }
1632 warnOnReservedIdentifier(D);
1633}
1634
1635bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1636 bool AllowInlineNamespace) const {
1637 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1638}
1639
1640Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1641 DeclContext *TargetDC = DC->getPrimaryContext();
1642 do {
1643 if (DeclContext *ScopeDC = S->getEntity())
1644 if (ScopeDC->getPrimaryContext() == TargetDC)
1645 return S;
1646 } while ((S = S->getParent()));
1647
1648 return nullptr;
1649}
1650
1651static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1652 DeclContext*,
1653 ASTContext&);
1654
1655void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1656 bool ConsiderLinkage,
1657 bool AllowInlineNamespace) {
1658 LookupResult::Filter F = R.makeFilter();
1659 while (F.hasNext()) {
1660 NamedDecl *D = F.next();
1661
1662 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1663 continue;
1664
1665 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1666 continue;
1667
1668 F.erase();
1669 }
1670
1671 F.done();
1672}
1673
1674static bool isImplicitInstantiation(NamedDecl *D) {
1675 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1676 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1677 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1678 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1679 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1680 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1681
1682 return false;
1683}
1684
1685bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1686 // [module.interface]p7:
1687 // A declaration is attached to a module as follows:
1688 // - If the declaration is a non-dependent friend declaration that nominates a
1689 // function with a declarator-id that is a qualified-id or template-id or that
1690 // nominates a class other than with an elaborated-type-specifier with neither
1691 // a nested-name-specifier nor a simple-template-id, it is attached to the
1692 // module to which the friend is attached ([basic.link]).
1693 if (New->getFriendObjectKind() &&
1694 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1695 New->setLocalOwningModule(Old->getOwningModule());
1696 makeMergedDefinitionVisible(ND: New);
1697 return false;
1698 }
1699
1700 // Although we have questions for the module ownership of implicit
1701 // instantiations, it should be sure that we shouldn't diagnose the
1702 // redeclaration of incorrect module ownership for different implicit
1703 // instantiations in different modules. We will diagnose the redeclaration of
1704 // incorrect module ownership for the template itself.
1705 if (isImplicitInstantiation(D: New) || isImplicitInstantiation(D: Old))
1706 return false;
1707
1708 Module *NewM = New->getOwningModule();
1709 Module *OldM = Old->getOwningModule();
1710
1711 if (NewM && NewM->isPrivateModule())
1712 NewM = NewM->Parent;
1713 if (OldM && OldM->isPrivateModule())
1714 OldM = OldM->Parent;
1715
1716 if (NewM == OldM)
1717 return false;
1718
1719 if (NewM && OldM) {
1720 // A module implementation unit has visibility of the decls in its
1721 // implicitly imported interface.
1722 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1723 return false;
1724
1725 // Partitions are part of the module, but a partition could import another
1726 // module, so verify that the PMIs agree.
1727 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1728 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1729 return false;
1730 }
1731
1732 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1733 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1734 if (NewIsModuleInterface || OldIsModuleInterface) {
1735 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1736 // if a declaration of D [...] appears in the purview of a module, all
1737 // other such declarations shall appear in the purview of the same module
1738 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1739 << New
1740 << NewIsModuleInterface
1741 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1742 << OldIsModuleInterface
1743 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1744 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1745 New->setInvalidDecl();
1746 return true;
1747 }
1748
1749 return false;
1750}
1751
1752bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1753 // [module.interface]p1:
1754 // An export-declaration shall inhabit a namespace scope.
1755 //
1756 // So it is meaningless to talk about redeclaration which is not at namespace
1757 // scope.
1758 if (!New->getLexicalDeclContext()
1759 ->getNonTransparentContext()
1760 ->isFileContext() ||
1761 !Old->getLexicalDeclContext()
1762 ->getNonTransparentContext()
1763 ->isFileContext())
1764 return false;
1765
1766 bool IsNewExported = New->isInExportDeclContext();
1767 bool IsOldExported = Old->isInExportDeclContext();
1768
1769 // It should be irrevelant if both of them are not exported.
1770 if (!IsNewExported && !IsOldExported)
1771 return false;
1772
1773 if (IsOldExported)
1774 return false;
1775
1776 // If the Old declaration are not attached to named modules
1777 // and the New declaration are attached to global module.
1778 // It should be fine to allow the export since it doesn't change
1779 // the linkage of declarations. See
1780 // https://github.com/llvm/llvm-project/issues/98583 for details.
1781 if (!Old->isInNamedModule() && New->getOwningModule() &&
1782 New->getOwningModule()->isImplicitGlobalModule())
1783 return false;
1784
1785 assert(IsNewExported);
1786
1787 auto Lk = Old->getFormalLinkage();
1788 int S = 0;
1789 if (Lk == Linkage::Internal)
1790 S = 1;
1791 else if (Lk == Linkage::Module)
1792 S = 2;
1793 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1794 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1795 return true;
1796}
1797
1798bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1799 if (CheckRedeclarationModuleOwnership(New, Old))
1800 return true;
1801
1802 if (CheckRedeclarationExported(New, Old))
1803 return true;
1804
1805 return false;
1806}
1807
1808bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1809 const NamedDecl *Old) const {
1810 assert(getASTContext().isSameEntity(New, Old) &&
1811 "New and Old are not the same definition, we should diagnostic it "
1812 "immediately instead of checking it.");
1813 assert(const_cast<Sema *>(this)->isReachable(New) &&
1814 const_cast<Sema *>(this)->isReachable(Old) &&
1815 "We shouldn't see unreachable definitions here.");
1816
1817 Module *NewM = New->getOwningModule();
1818 Module *OldM = Old->getOwningModule();
1819
1820 // We only checks for named modules here. The header like modules is skipped.
1821 // FIXME: This is not right if we import the header like modules in the module
1822 // purview.
1823 //
1824 // For example, assuming "header.h" provides definition for `D`.
1825 // ```C++
1826 // //--- M.cppm
1827 // export module M;
1828 // import "header.h"; // or #include "header.h" but import it by clang modules
1829 // actually.
1830 //
1831 // //--- Use.cpp
1832 // import M;
1833 // import "header.h"; // or uses clang modules.
1834 // ```
1835 //
1836 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1837 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1838 // reject it. But the current implementation couldn't detect the case since we
1839 // don't record the information about the importee modules.
1840 //
1841 // But this might not be painful in practice. Since the design of C++20 Named
1842 // Modules suggests us to use headers in global module fragment instead of
1843 // module purview.
1844 if (NewM && NewM->isHeaderLikeModule())
1845 NewM = nullptr;
1846 if (OldM && OldM->isHeaderLikeModule())
1847 OldM = nullptr;
1848
1849 if (!NewM && !OldM)
1850 return true;
1851
1852 // [basic.def.odr]p14.3
1853 // Each such definition shall not be attached to a named module
1854 // ([module.unit]).
1855 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1856 return true;
1857
1858 // Then New and Old lives in the same TU if their share one same module unit.
1859 if (NewM)
1860 NewM = NewM->getTopLevelModule();
1861 if (OldM)
1862 OldM = OldM->getTopLevelModule();
1863 return OldM == NewM;
1864}
1865
1866static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1867 if (D->getDeclContext()->isFileContext())
1868 return false;
1869
1870 return isa<UsingShadowDecl>(Val: D) ||
1871 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1872 isa<UnresolvedUsingValueDecl>(Val: D);
1873}
1874
1875/// Removes using shadow declarations not at class scope from the lookup
1876/// results.
1877static void RemoveUsingDecls(LookupResult &R) {
1878 LookupResult::Filter F = R.makeFilter();
1879 while (F.hasNext())
1880 if (isUsingDeclNotAtClassScope(D: F.next()))
1881 F.erase();
1882
1883 F.done();
1884}
1885
1886/// Check for this common pattern:
1887/// @code
1888/// class S {
1889/// S(const S&); // DO NOT IMPLEMENT
1890/// void operator=(const S&); // DO NOT IMPLEMENT
1891/// };
1892/// @endcode
1893static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1894 // FIXME: Should check for private access too but access is set after we get
1895 // the decl here.
1896 if (D->doesThisDeclarationHaveABody())
1897 return false;
1898
1899 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1900 return CD->isCopyConstructor();
1901 return D->isCopyAssignmentOperator();
1902}
1903
1904bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1905 const DeclContext *DC = D->getDeclContext();
1906 while (!DC->isTranslationUnit()) {
1907 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1908 if (!RD->hasNameForLinkage())
1909 return true;
1910 }
1911 DC = DC->getParent();
1912 }
1913
1914 return !D->isExternallyVisible();
1915}
1916
1917bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1918 assert(D);
1919
1920 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1921 return false;
1922
1923 // Ignore all entities declared within templates, and out-of-line definitions
1924 // of members of class templates.
1925 if (D->getDeclContext()->isDependentContext() ||
1926 D->getLexicalDeclContext()->isDependentContext())
1927 return false;
1928
1929 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1930 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1931 return false;
1932 // A non-out-of-line declaration of a member specialization was implicitly
1933 // instantiated; it's the out-of-line declaration that we're interested in.
1934 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1935 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1936 return false;
1937
1938 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1939 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1940 return false;
1941 } else {
1942 // 'static inline' functions are defined in headers; don't warn.
1943 if (FD->isInlined() && !isMainFileLoc(Loc: FD->getLocation()))
1944 return false;
1945 }
1946
1947 if (FD->doesThisDeclarationHaveABody() &&
1948 Context.DeclMustBeEmitted(D: FD))
1949 return false;
1950 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1951 // Constants and utility variables are defined in headers with internal
1952 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1953 // like "inline".)
1954 if (!isMainFileLoc(Loc: VD->getLocation()))
1955 return false;
1956
1957 if (Context.DeclMustBeEmitted(D: VD))
1958 return false;
1959
1960 if (VD->isStaticDataMember() &&
1961 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1962 return false;
1963 if (VD->isStaticDataMember() &&
1964 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1965 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1966 return false;
1967
1968 if (VD->isInline() && !isMainFileLoc(Loc: VD->getLocation()))
1969 return false;
1970 } else {
1971 return false;
1972 }
1973
1974 // Only warn for unused decls internal to the translation unit.
1975 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1976 // for inline functions defined in the main source file, for instance.
1977 return mightHaveNonExternalLinkage(D);
1978}
1979
1980void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1981 if (!D)
1982 return;
1983
1984 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1985 const FunctionDecl *First = FD->getFirstDecl();
1986 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1987 return; // First should already be in the vector.
1988 }
1989
1990 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1991 const VarDecl *First = VD->getFirstDecl();
1992 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1993 return; // First should already be in the vector.
1994 }
1995
1996 if (ShouldWarnIfUnusedFileScopedDecl(D))
1997 UnusedFileScopedDecls.push_back(LocalValue: D);
1998}
1999
2000static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2001 const NamedDecl *D) {
2002 if (D->isInvalidDecl())
2003 return false;
2004
2005 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
2006 // For a decomposition declaration, warn if none of the bindings are
2007 // referenced, instead of if the variable itself is referenced (which
2008 // it is, by the bindings' expressions).
2009 bool IsAllIgnored = true;
2010 for (const auto *BD : DD->bindings()) {
2011 if (BD->isReferenced())
2012 return false;
2013 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2014 BD->hasAttr<UnusedAttr>());
2015 }
2016 if (IsAllIgnored)
2017 return false;
2018 } else if (!D->getDeclName()) {
2019 return false;
2020 } else if (D->isReferenced() || D->isUsed()) {
2021 return false;
2022 }
2023
2024 if (D->isPlaceholderVar(LangOpts))
2025 return false;
2026
2027 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2028 D->hasAttr<CleanupAttr>())
2029 return false;
2030
2031 if (isa<LabelDecl>(Val: D))
2032 return true;
2033
2034 // Except for labels, we only care about unused decls that are local to
2035 // functions.
2036 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2037 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
2038 // For dependent types, the diagnostic is deferred.
2039 WithinFunction =
2040 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2041 if (!WithinFunction)
2042 return false;
2043
2044 if (isa<TypedefNameDecl>(Val: D))
2045 return true;
2046
2047 // White-list anything that isn't a local variable.
2048 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2049 return false;
2050
2051 // Types of valid local variables should be complete, so this should succeed.
2052 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2053
2054 const Expr *Init = VD->getInit();
2055 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2056 Init = Cleanups->getSubExpr();
2057
2058 const auto *Ty = VD->getType().getTypePtr();
2059
2060 // Only look at the outermost level of typedef.
2061 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2062 // Allow anything marked with __attribute__((unused)).
2063 if (TT->getDecl()->hasAttr<UnusedAttr>())
2064 return false;
2065 }
2066
2067 // Warn for reference variables whose initializtion performs lifetime
2068 // extension.
2069 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2070 MTE && MTE->getExtendingDecl()) {
2071 Ty = VD->getType().getNonReferenceType().getTypePtr();
2072 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2073 }
2074
2075 // If we failed to complete the type for some reason, or if the type is
2076 // dependent, don't diagnose the variable.
2077 if (Ty->isIncompleteType() || Ty->isDependentType())
2078 return false;
2079
2080 // Look at the element type to ensure that the warning behaviour is
2081 // consistent for both scalars and arrays.
2082 Ty = Ty->getBaseElementTypeUnsafe();
2083
2084 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2085 if (Tag->hasAttr<UnusedAttr>())
2086 return false;
2087
2088 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2089 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2090 return false;
2091
2092 if (Init) {
2093 const auto *Construct =
2094 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2095 if (Construct && !Construct->isElidable()) {
2096 const CXXConstructorDecl *CD = Construct->getConstructor();
2097 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2098 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2099 return false;
2100 }
2101
2102 // Suppress the warning if we don't know how this is constructed, and
2103 // it could possibly be non-trivial constructor.
2104 if (Init->isTypeDependent()) {
2105 for (const CXXConstructorDecl *Ctor : RD->ctors())
2106 if (!Ctor->isTrivial())
2107 return false;
2108 }
2109
2110 // Suppress the warning if the constructor is unresolved because
2111 // its arguments are dependent.
2112 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2113 return false;
2114 }
2115 }
2116 }
2117
2118 // TODO: __attribute__((unused)) templates?
2119 }
2120
2121 return true;
2122}
2123
2124static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2125 FixItHint &Hint) {
2126 if (isa<LabelDecl>(Val: D)) {
2127 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2128 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2129 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2130 if (AfterColon.isInvalid())
2131 return;
2132 Hint = FixItHint::CreateRemoval(
2133 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2134 }
2135}
2136
2137void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2138 DiagnoseUnusedNestedTypedefs(
2139 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2140}
2141
2142void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2143 DiagReceiverTy DiagReceiver) {
2144 if (D->isDependentType())
2145 return;
2146
2147 for (auto *TmpD : D->decls()) {
2148 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2149 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2150 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2151 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2152 }
2153}
2154
2155void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2156 DiagnoseUnusedDecl(
2157 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2158}
2159
2160void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2161 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2162 return;
2163
2164 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2165 // typedefs can be referenced later on, so the diagnostics are emitted
2166 // at end-of-translation-unit.
2167 UnusedLocalTypedefNameCandidates.insert(X: TD);
2168 return;
2169 }
2170
2171 FixItHint Hint;
2172 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2173
2174 unsigned DiagID;
2175 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2176 DiagID = diag::warn_unused_exception_param;
2177 else if (isa<LabelDecl>(Val: D))
2178 DiagID = diag::warn_unused_label;
2179 else
2180 DiagID = diag::warn_unused_variable;
2181
2182 SourceLocation DiagLoc = D->getLocation();
2183 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2184}
2185
2186void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2187 DiagReceiverTy DiagReceiver) {
2188 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2189 // it's not really unused.
2190 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2191 return;
2192
2193 // In C++, `_` variables behave as if they were maybe_unused
2194 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2195 return;
2196
2197 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2198
2199 if (Ty->isReferenceType() || Ty->isDependentType())
2200 return;
2201
2202 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2203 if (Tag->hasAttr<UnusedAttr>())
2204 return;
2205 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2206 // mimic gcc's behavior.
2207 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2208 RD && !RD->hasAttr<WarnUnusedAttr>())
2209 return;
2210 }
2211
2212 // Don't warn on volatile file-scope variables. They are visible beyond their
2213 // declaring function and writes to them could be observable side effects.
2214 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2215 return;
2216
2217 // Don't warn about __block Objective-C pointer variables, as they might
2218 // be assigned in the block but not used elsewhere for the purpose of lifetime
2219 // extension.
2220 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2221 return;
2222
2223 // Don't warn about Objective-C pointer variables with precise lifetime
2224 // semantics; they can be used to ensure ARC releases the object at a known
2225 // time, which may mean assignment but no other references.
2226 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2227 return;
2228
2229 auto iter = RefsMinusAssignments.find(Val: VD->getCanonicalDecl());
2230 if (iter == RefsMinusAssignments.end())
2231 return;
2232
2233 assert(iter->getSecond() >= 0 &&
2234 "Found a negative number of references to a VarDecl");
2235 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2236 // Assume the given VarDecl is "used" if its ref count stored in
2237 // `RefMinusAssignments` is positive, with one exception.
2238 //
2239 // For a C++ variable whose decl (with initializer) entirely consist the
2240 // condition expression of a if/while/for construct,
2241 // Clang creates a DeclRefExpr for the condition expression rather than a
2242 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2243 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2244 // used in the body of the if/while/for construct.
2245 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2246 if (!UnusedCXXCondDecl)
2247 return;
2248 }
2249
2250 unsigned DiagID;
2251 if (isa<ParmVarDecl>(Val: VD))
2252 DiagID = diag::warn_unused_but_set_parameter;
2253 else if (VD->isFileVarDecl())
2254 DiagID = diag::warn_unused_but_set_global;
2255 else
2256 DiagID = diag::warn_unused_but_set_variable;
2257 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2258}
2259
2260static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2261 Sema::DiagReceiverTy DiagReceiver) {
2262 // Verify that we have no forward references left. If so, there was a goto
2263 // or address of a label taken, but no definition of it. Label fwd
2264 // definitions are indicated with a null substmt which is also not a resolved
2265 // MS inline assembly label name.
2266 bool Diagnose = false;
2267 if (L->isMSAsmLabel())
2268 Diagnose = !L->isResolvedMSAsmLabel();
2269 else
2270 Diagnose = L->getStmt() == nullptr;
2271 if (Diagnose)
2272 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2273 << L);
2274}
2275
2276void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2277 S->applyNRVO();
2278
2279 if (S->decl_empty()) return;
2280 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2281 "Scope shouldn't contain decls!");
2282
2283 /// We visit the decls in non-deterministic order, but we want diagnostics
2284 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2285 /// and sort the diagnostics before emitting them, after we visited all decls.
2286 struct LocAndDiag {
2287 SourceLocation Loc;
2288 std::optional<SourceLocation> PreviousDeclLoc;
2289 PartialDiagnostic PD;
2290 };
2291 SmallVector<LocAndDiag, 16> DeclDiags;
2292 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2293 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2294 };
2295 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2296 SourceLocation PreviousDeclLoc,
2297 PartialDiagnostic PD) {
2298 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2299 };
2300
2301 for (auto *TmpD : S->decls()) {
2302 assert(TmpD && "This decl didn't get pushed??");
2303
2304 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2305 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2306
2307 // Diagnose unused variables in this scope.
2308 if (!S->hasUnrecoverableErrorOccurred()) {
2309 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2310 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2311 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2312 // Wait until end of TU to diagnose internal linkage file vars.
2313 if (auto *VD = dyn_cast<VarDecl>(Val: D);
2314 VD && !VD->isInternalLinkageFileVar()) {
2315 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2316 RefsMinusAssignments.erase(Val: VD->getCanonicalDecl());
2317 }
2318 }
2319
2320 if (!D->getDeclName()) continue;
2321
2322 // If this was a forward reference to a label, verify it was defined.
2323 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2324 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2325
2326 // Partial translation units that are created in incremental processing must
2327 // not clean up the IdResolver because PTUs should take into account the
2328 // declarations that came from previous PTUs.
2329 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2330 getLangOpts().CPlusPlus)
2331 IdResolver.RemoveDecl(D);
2332
2333 // Warn on it if we are shadowing a declaration.
2334 auto ShadowI = ShadowingDecls.find(Val: D);
2335 if (ShadowI != ShadowingDecls.end()) {
2336 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2337 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2338 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2339 << D << FD << FD->getParent());
2340 }
2341 ShadowingDecls.erase(I: ShadowI);
2342 }
2343 }
2344
2345 llvm::sort(C&: DeclDiags,
2346 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2347 // The particular order for diagnostics is not important, as long
2348 // as the order is deterministic. Using the raw location is going
2349 // to generally be in source order unless there are macro
2350 // expansions involved.
2351 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2352 });
2353 for (const LocAndDiag &D : DeclDiags) {
2354 Diag(Loc: D.Loc, PD: D.PD);
2355 if (D.PreviousDeclLoc)
2356 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2357 }
2358}
2359
2360Scope *Sema::getNonFieldDeclScope(Scope *S) {
2361 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2362 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2363 (S->isClassScope() && !getLangOpts().CPlusPlus))
2364 S = S->getParent();
2365 return S;
2366}
2367
2368static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2369 ASTContext::GetBuiltinTypeError Error) {
2370 switch (Error) {
2371 case ASTContext::GE_None:
2372 return "";
2373 case ASTContext::GE_Missing_type:
2374 return BuiltinInfo.getHeaderName(ID);
2375 case ASTContext::GE_Missing_stdio:
2376 return "stdio.h";
2377 case ASTContext::GE_Missing_setjmp:
2378 return "setjmp.h";
2379 case ASTContext::GE_Missing_ucontext:
2380 return "ucontext.h";
2381 }
2382 llvm_unreachable("unhandled error kind");
2383}
2384
2385FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2386 unsigned ID, SourceLocation Loc) {
2387 DeclContext *Parent = Context.getTranslationUnitDecl();
2388
2389 if (getLangOpts().CPlusPlus) {
2390 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2391 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2392 CLinkageDecl->setImplicit();
2393 Parent->addDecl(D: CLinkageDecl);
2394 Parent = CLinkageDecl;
2395 }
2396
2397 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2398 if (Context.BuiltinInfo.isImmediate(ID)) {
2399 assert(getLangOpts().CPlusPlus20 &&
2400 "consteval builtins should only be available in C++20 mode");
2401 ConstexprKind = ConstexprSpecKind::Consteval;
2402 }
2403
2404 FunctionDecl *New = FunctionDecl::Create(
2405 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2406 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2407 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2408 New->setImplicit();
2409 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2410
2411 // Create Decl objects for each parameter, adding them to the
2412 // FunctionDecl.
2413 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2414 SmallVector<ParmVarDecl *, 16> Params;
2415 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2416 ParmVarDecl *parm = ParmVarDecl::Create(
2417 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2418 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2419 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2420 Params.push_back(Elt: parm);
2421 }
2422 New->setParams(Params);
2423 }
2424
2425 AddKnownFunctionAttributes(FD: New);
2426 return New;
2427}
2428
2429NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2430 Scope *S, bool ForRedeclaration,
2431 SourceLocation Loc) {
2432 LookupNecessaryTypesForBuiltin(S, ID);
2433
2434 ASTContext::GetBuiltinTypeError Error;
2435 QualType R = Context.GetBuiltinType(ID, Error);
2436 if (Error) {
2437 if (!ForRedeclaration)
2438 return nullptr;
2439
2440 // If we have a builtin without an associated type we should not emit a
2441 // warning when we were not able to find a type for it.
2442 if (Error == ASTContext::GE_Missing_type ||
2443 Context.BuiltinInfo.allowTypeMismatch(ID))
2444 return nullptr;
2445
2446 // If we could not find a type for setjmp it is because the jmp_buf type was
2447 // not defined prior to the setjmp declaration.
2448 if (Error == ASTContext::GE_Missing_setjmp) {
2449 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2450 << Context.BuiltinInfo.getName(ID);
2451 return nullptr;
2452 }
2453
2454 // Generally, we emit a warning that the declaration requires the
2455 // appropriate header.
2456 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2457 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2458 << Context.BuiltinInfo.getName(ID);
2459 return nullptr;
2460 }
2461
2462 if (!ForRedeclaration &&
2463 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2464 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2465 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2466 : diag::ext_implicit_lib_function_decl)
2467 << Context.BuiltinInfo.getName(ID) << R;
2468 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2469 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2470 << Header << Context.BuiltinInfo.getName(ID);
2471 }
2472
2473 if (R.isNull())
2474 return nullptr;
2475
2476 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2477 RegisterLocallyScopedExternCDecl(ND: New, S);
2478
2479 // TUScope is the translation-unit scope to insert this function into.
2480 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2481 // relate Scopes to DeclContexts, and probably eliminate CurContext
2482 // entirely, but we're not there yet.
2483 DeclContext *SavedContext = CurContext;
2484 CurContext = New->getDeclContext();
2485 PushOnScopeChains(D: New, S: TUScope);
2486 CurContext = SavedContext;
2487 return New;
2488}
2489
2490/// Typedef declarations don't have linkage, but they still denote the same
2491/// entity if their types are the same.
2492/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2493/// isSameEntity.
2494static void
2495filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2496 LookupResult &Previous) {
2497 // This is only interesting when modules are enabled.
2498 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2499 return;
2500
2501 // Empty sets are uninteresting.
2502 if (Previous.empty())
2503 return;
2504
2505 LookupResult::Filter Filter = Previous.makeFilter();
2506 while (Filter.hasNext()) {
2507 NamedDecl *Old = Filter.next();
2508
2509 // Non-hidden declarations are never ignored.
2510 if (S.isVisible(D: Old))
2511 continue;
2512
2513 // Declarations of the same entity are not ignored, even if they have
2514 // different linkages.
2515 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2516 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2517 T2: Decl->getUnderlyingType()))
2518 continue;
2519
2520 // If both declarations give a tag declaration a typedef name for linkage
2521 // purposes, then they declare the same entity.
2522 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2523 Decl->getAnonDeclWithTypedefName())
2524 continue;
2525 }
2526
2527 Filter.erase();
2528 }
2529
2530 Filter.done();
2531}
2532
2533bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2534 QualType OldType;
2535 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2536 OldType = OldTypedef->getUnderlyingType();
2537 else
2538 OldType = Context.getTypeDeclType(Decl: Old);
2539 QualType NewType = New->getUnderlyingType();
2540
2541 if (NewType->isVariablyModifiedType()) {
2542 // Must not redefine a typedef with a variably-modified type.
2543 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2544 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2545 << Kind << NewType;
2546 if (Old->getLocation().isValid())
2547 notePreviousDefinition(Old, New: New->getLocation());
2548 New->setInvalidDecl();
2549 return true;
2550 }
2551
2552 if (OldType != NewType &&
2553 !OldType->isDependentType() &&
2554 !NewType->isDependentType() &&
2555 !Context.hasSameType(T1: OldType, T2: NewType)) {
2556 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2557 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2558 << Kind << NewType << OldType;
2559 if (Old->getLocation().isValid())
2560 notePreviousDefinition(Old, New: New->getLocation());
2561 New->setInvalidDecl();
2562 return true;
2563 }
2564 return false;
2565}
2566
2567void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2568 LookupResult &OldDecls) {
2569 // If the new decl is known invalid already, don't bother doing any
2570 // merging checks.
2571 if (New->isInvalidDecl()) return;
2572
2573 // Allow multiple definitions for ObjC built-in typedefs.
2574 // FIXME: Verify the underlying types are equivalent!
2575 if (getLangOpts().ObjC) {
2576 const IdentifierInfo *TypeID = New->getIdentifier();
2577 switch (TypeID->getLength()) {
2578 default: break;
2579 case 2:
2580 {
2581 if (!TypeID->isStr(Str: "id"))
2582 break;
2583 QualType T = New->getUnderlyingType();
2584 if (!T->isPointerType())
2585 break;
2586 if (!T->isVoidPointerType()) {
2587 QualType PT = T->castAs<PointerType>()->getPointeeType();
2588 if (!PT->isStructureType())
2589 break;
2590 }
2591 Context.setObjCIdRedefinitionType(T);
2592 // Install the built-in type for 'id', ignoring the current definition.
2593 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2594 modedTy: Context.getObjCIdType());
2595 return;
2596 }
2597 case 5:
2598 if (!TypeID->isStr(Str: "Class"))
2599 break;
2600 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2601 // Install the built-in type for 'Class', ignoring the current definition.
2602 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2603 modedTy: Context.getObjCClassType());
2604 return;
2605 case 3:
2606 if (!TypeID->isStr(Str: "SEL"))
2607 break;
2608 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2609 // Install the built-in type for 'SEL', ignoring the current definition.
2610 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2611 modedTy: Context.getObjCSelType());
2612 return;
2613 }
2614 // Fall through - the typedef name was not a builtin type.
2615 }
2616
2617 // Verify the old decl was also a type.
2618 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2619 if (!Old) {
2620 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2621 << New->getDeclName();
2622
2623 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2624 if (OldD->getLocation().isValid())
2625 notePreviousDefinition(Old: OldD, New: New->getLocation());
2626
2627 return New->setInvalidDecl();
2628 }
2629
2630 // If the old declaration is invalid, just give up here.
2631 if (Old->isInvalidDecl())
2632 return New->setInvalidDecl();
2633
2634 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2635 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2636 auto *NewTag = New->getAnonDeclWithTypedefName();
2637 NamedDecl *Hidden = nullptr;
2638 if (OldTag && NewTag &&
2639 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2640 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2641 // There is a definition of this tag, but it is not visible. Use it
2642 // instead of our tag.
2643 if (OldTD->isModed())
2644 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2645 modedTy: OldTD->getUnderlyingType());
2646 else
2647 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2648
2649 // Make the old tag definition visible.
2650 makeMergedDefinitionVisible(ND: Hidden);
2651
2652 CleanupMergedEnum(S, New: NewTag);
2653 }
2654 }
2655
2656 // If the typedef types are not identical, reject them in all languages and
2657 // with any extensions enabled.
2658 if (isIncompatibleTypedef(Old, New))
2659 return;
2660
2661 // The types match. Link up the redeclaration chain and merge attributes if
2662 // the old declaration was a typedef.
2663 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2664 New->setPreviousDecl(Typedef);
2665 mergeDeclAttributes(New, Old);
2666 }
2667
2668 if (getLangOpts().MicrosoftExt)
2669 return;
2670
2671 if (getLangOpts().CPlusPlus) {
2672 // C++ [dcl.typedef]p2:
2673 // In a given non-class scope, a typedef specifier can be used to
2674 // redefine the name of any type declared in that scope to refer
2675 // to the type to which it already refers.
2676 if (!isa<CXXRecordDecl>(Val: CurContext))
2677 return;
2678
2679 // C++0x [dcl.typedef]p4:
2680 // In a given class scope, a typedef specifier can be used to redefine
2681 // any class-name declared in that scope that is not also a typedef-name
2682 // to refer to the type to which it already refers.
2683 //
2684 // This wording came in via DR424, which was a correction to the
2685 // wording in DR56, which accidentally banned code like:
2686 //
2687 // struct S {
2688 // typedef struct A { } A;
2689 // };
2690 //
2691 // in the C++03 standard. We implement the C++0x semantics, which
2692 // allow the above but disallow
2693 //
2694 // struct S {
2695 // typedef int I;
2696 // typedef int I;
2697 // };
2698 //
2699 // since that was the intent of DR56.
2700 if (!isa<TypedefNameDecl>(Val: Old))
2701 return;
2702
2703 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2704 << New->getDeclName();
2705 notePreviousDefinition(Old, New: New->getLocation());
2706 return New->setInvalidDecl();
2707 }
2708
2709 // Modules always permit redefinition of typedefs, as does C11.
2710 if (getLangOpts().Modules || getLangOpts().C11)
2711 return;
2712
2713 // If we have a redefinition of a typedef in C, emit a warning. This warning
2714 // is normally mapped to an error, but can be controlled with
2715 // -Wtypedef-redefinition. If either the original or the redefinition is
2716 // in a system header, don't emit this for compatibility with GCC.
2717 if (getDiagnostics().getSuppressSystemWarnings() &&
2718 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2719 (Old->isImplicit() ||
2720 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2721 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2722 return;
2723
2724 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2725 << New->getDeclName();
2726 notePreviousDefinition(Old, New: New->getLocation());
2727}
2728
2729void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2730 // If this was an unscoped enumeration, yank all of its enumerators
2731 // out of the scope.
2732 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2733 Scope *EnumScope = getNonFieldDeclScope(S);
2734 for (auto *ECD : ED->enumerators()) {
2735 assert(EnumScope->isDeclScope(ECD));
2736 EnumScope->RemoveDecl(D: ECD);
2737 IdResolver.RemoveDecl(D: ECD);
2738 }
2739 }
2740}
2741
2742/// DeclhasAttr - returns true if decl Declaration already has the target
2743/// attribute.
2744static bool DeclHasAttr(const Decl *D, const Attr *A) {
2745 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2746 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2747 for (const auto *i : D->attrs())
2748 if (i->getKind() == A->getKind()) {
2749 if (Ann) {
2750 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2751 return true;
2752 continue;
2753 }
2754 // FIXME: Don't hardcode this check
2755 if (OA && isa<OwnershipAttr>(Val: i))
2756 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2757 return true;
2758 }
2759
2760 return false;
2761}
2762
2763static bool isAttributeTargetADefinition(Decl *D) {
2764 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2765 return VD->isThisDeclarationADefinition();
2766 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2767 return TD->isCompleteDefinition() || TD->isBeingDefined();
2768 return true;
2769}
2770
2771/// Merge alignment attributes from \p Old to \p New, taking into account the
2772/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2773///
2774/// \return \c true if any attributes were added to \p New.
2775static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2776 // Look for alignas attributes on Old, and pick out whichever attribute
2777 // specifies the strictest alignment requirement.
2778 AlignedAttr *OldAlignasAttr = nullptr;
2779 AlignedAttr *OldStrictestAlignAttr = nullptr;
2780 unsigned OldAlign = 0;
2781 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2782 // FIXME: We have no way of representing inherited dependent alignments
2783 // in a case like:
2784 // template<int A, int B> struct alignas(A) X;
2785 // template<int A, int B> struct alignas(B) X {};
2786 // For now, we just ignore any alignas attributes which are not on the
2787 // definition in such a case.
2788 if (I->isAlignmentDependent())
2789 return false;
2790
2791 if (I->isAlignas())
2792 OldAlignasAttr = I;
2793
2794 unsigned Align = I->getAlignment(Ctx&: S.Context);
2795 if (Align > OldAlign) {
2796 OldAlign = Align;
2797 OldStrictestAlignAttr = I;
2798 }
2799 }
2800
2801 // Look for alignas attributes on New.
2802 AlignedAttr *NewAlignasAttr = nullptr;
2803 unsigned NewAlign = 0;
2804 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2805 if (I->isAlignmentDependent())
2806 return false;
2807
2808 if (I->isAlignas())
2809 NewAlignasAttr = I;
2810
2811 unsigned Align = I->getAlignment(Ctx&: S.Context);
2812 if (Align > NewAlign)
2813 NewAlign = Align;
2814 }
2815
2816 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2817 // Both declarations have 'alignas' attributes. We require them to match.
2818 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2819 // fall short. (If two declarations both have alignas, they must both match
2820 // every definition, and so must match each other if there is a definition.)
2821
2822 // If either declaration only contains 'alignas(0)' specifiers, then it
2823 // specifies the natural alignment for the type.
2824 if (OldAlign == 0 || NewAlign == 0) {
2825 QualType Ty;
2826 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2827 Ty = VD->getType();
2828 else
2829 Ty = S.Context.getCanonicalTagType(TD: cast<TagDecl>(Val: New));
2830
2831 if (OldAlign == 0)
2832 OldAlign = S.Context.getTypeAlign(T: Ty);
2833 if (NewAlign == 0)
2834 NewAlign = S.Context.getTypeAlign(T: Ty);
2835 }
2836
2837 if (OldAlign != NewAlign) {
2838 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2839 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2840 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2841 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2842 }
2843 }
2844
2845 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2846 // C++11 [dcl.align]p6:
2847 // if any declaration of an entity has an alignment-specifier,
2848 // every defining declaration of that entity shall specify an
2849 // equivalent alignment.
2850 // C11 6.7.5/7:
2851 // If the definition of an object does not have an alignment
2852 // specifier, any other declaration of that object shall also
2853 // have no alignment specifier.
2854 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2855 << OldAlignasAttr;
2856 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2857 << OldAlignasAttr;
2858 }
2859
2860 bool AnyAdded = false;
2861
2862 // Ensure we have an attribute representing the strictest alignment.
2863 if (OldAlign > NewAlign) {
2864 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2865 Clone->setInherited(true);
2866 New->addAttr(A: Clone);
2867 AnyAdded = true;
2868 }
2869
2870 // Ensure we have an alignas attribute if the old declaration had one.
2871 if (OldAlignasAttr && !NewAlignasAttr &&
2872 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2873 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2874 Clone->setInherited(true);
2875 New->addAttr(A: Clone);
2876 AnyAdded = true;
2877 }
2878
2879 return AnyAdded;
2880}
2881
2882#define WANT_DECL_MERGE_LOGIC
2883#include "clang/Sema/AttrParsedAttrImpl.inc"
2884#undef WANT_DECL_MERGE_LOGIC
2885
2886static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2887 const InheritableAttr *Attr,
2888 AvailabilityMergeKind AMK) {
2889 // Diagnose any mutual exclusions between the attribute that we want to add
2890 // and attributes that already exist on the declaration.
2891 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2892 return false;
2893
2894 // This function copies an attribute Attr from a previous declaration to the
2895 // new declaration D if the new declaration doesn't itself have that attribute
2896 // yet or if that attribute allows duplicates.
2897 // If you're adding a new attribute that requires logic different from
2898 // "use explicit attribute on decl if present, else use attribute from
2899 // previous decl", for example if the attribute needs to be consistent
2900 // between redeclarations, you need to call a custom merge function here.
2901 InheritableAttr *NewAttr = nullptr;
2902 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr))
2903 NewAttr = S.mergeAvailabilityAttr(
2904 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2905 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2906 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2907 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment(),
2908 OrigAnyAppleOSVersion: AA->getOrigAnyAppleOSVersion());
2909 else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2910 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2911 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2912 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2913 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2914 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2915 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2916 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2917 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2918 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2919 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2920 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2921 FirstArg: FA->getFirstArg());
2922 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2923 NewAttr = S.mergeFormatMatchesAttr(
2924 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2925 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Val: Attr))
2926 NewAttr = S.mergeModularFormatAttr(
2927 D, CI: *MFA, ModularImplFn: MFA->getModularImplFn(), ImplName: MFA->getImplName(),
2928 Aspects: MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2929 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2930 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2931 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2932 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2933 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
2934 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
2935 Model: IA->getInheritanceModel());
2936 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
2937 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
2938 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
2939 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
2940 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
2941 isa<CUDAGlobalAttr>(Val: Attr))) {
2942 // CUDA target attributes are part of function signature for
2943 // overloading purposes and must not be merged.
2944 return false;
2945 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
2946 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
2947 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
2948 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
2949 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
2950 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
2951 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
2952 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
2953 else if (isa<AlignedAttr>(Val: Attr))
2954 // AlignedAttrs are handled separately, because we need to handle all
2955 // such attributes on a declaration at the same time.
2956 NewAttr = nullptr;
2957 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
2958 (AMK == AvailabilityMergeKind::Override ||
2959 AMK == AvailabilityMergeKind::ProtocolImplementation ||
2960 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
2961 NewAttr = nullptr;
2962 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
2963 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
2964 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
2965 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
2966 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
2967 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
2968 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
2969 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
2970 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
2971 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
2972 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
2973 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
2974 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
2975 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
2976 Z: NT->getZ());
2977 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
2978 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
2979 Preferred: WS->getPreferred(),
2980 SpelledArgsCount: WS->getSpelledArgsCount());
2981 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
2982 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
2983 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
2984 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
2985 else if (isa<SuppressAttr>(Val: Attr))
2986 // Do nothing. Each redeclaration should be suppressed separately.
2987 NewAttr = nullptr;
2988 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
2989 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
2990 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
2991 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
2992 else if (const auto *PA = dyn_cast<PersonalityAttr>(Val: Attr))
2993 NewAttr = S.mergePersonalityAttr(D, Routine: PA->getRoutine(), CI: *PA);
2994
2995 if (NewAttr) {
2996 NewAttr->setInherited(true);
2997 D->addAttr(A: NewAttr);
2998 if (isa<MSInheritanceAttr>(Val: NewAttr))
2999 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
3000 return true;
3001 }
3002
3003 return false;
3004}
3005
3006static const NamedDecl *getDefinition(const Decl *D) {
3007 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
3008 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3009 return Def;
3010 return nullptr;
3011 }
3012 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
3013 const VarDecl *Def = VD->getDefinition();
3014 if (Def)
3015 return Def;
3016 return VD->getActingDefinition();
3017 }
3018 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3019 const FunctionDecl *Def = nullptr;
3020 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3021 return Def;
3022 }
3023 return nullptr;
3024}
3025
3026static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3027 for (const auto *Attribute : D->attrs())
3028 if (Attribute->getKind() == Kind)
3029 return true;
3030 return false;
3031}
3032
3033/// checkNewAttributesAfterDef - If we already have a definition, check that
3034/// there are no new attributes in this declaration.
3035static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3036 if (!New->hasAttrs())
3037 return;
3038
3039 const NamedDecl *Def = getDefinition(D: Old);
3040 if (!Def || Def == New)
3041 return;
3042
3043 AttrVec &NewAttributes = New->getAttrs();
3044 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3045 Attr *NewAttribute = NewAttributes[I];
3046
3047 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
3048 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3049 SkipBodyInfo SkipBody;
3050 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3051
3052 // If we're skipping this definition, drop the "alias" attribute.
3053 if (SkipBody.ShouldSkip) {
3054 NewAttributes.erase(CI: NewAttributes.begin() + I);
3055 --E;
3056 continue;
3057 }
3058 } else {
3059 VarDecl *VD = cast<VarDecl>(Val: New);
3060 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
3061 VarDecl::TentativeDefinition
3062 ? diag::err_alias_after_tentative
3063 : diag::err_redefinition;
3064 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
3065 if (Diag == diag::err_redefinition)
3066 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3067 else
3068 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3069 VD->setInvalidDecl();
3070 }
3071 ++I;
3072 continue;
3073 }
3074
3075 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3076 // Tentative definitions are only interesting for the alias check above.
3077 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3078 ++I;
3079 continue;
3080 }
3081 }
3082
3083 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
3084 ++I;
3085 continue; // regular attr merging will take care of validating this.
3086 }
3087
3088 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
3089 // C's _Noreturn is allowed to be added to a function after it is defined.
3090 ++I;
3091 continue;
3092 } else if (isa<UuidAttr>(Val: NewAttribute)) {
3093 // msvc will allow a subsequent definition to add an uuid to a class
3094 ++I;
3095 continue;
3096 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3097 Val: NewAttribute) &&
3098 NewAttribute->isStandardAttributeSyntax()) {
3099 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3100 // deprecated attribute can later be re-declared with the attribute and
3101 // vice-versa.
3102 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3103 // maybe_unused attribute can later be redeclared with the attribute and
3104 // vice versa.
3105 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3106 // nodiscard attribute can later be redeclared with the attribute and
3107 // vice-versa.
3108 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3109 ++I;
3110 continue;
3111 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3112 if (AA->isAlignas()) {
3113 // C++11 [dcl.align]p6:
3114 // if any declaration of an entity has an alignment-specifier,
3115 // every defining declaration of that entity shall specify an
3116 // equivalent alignment.
3117 // C11 6.7.5/7:
3118 // If the definition of an object does not have an alignment
3119 // specifier, any other declaration of that object shall also
3120 // have no alignment specifier.
3121 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3122 << AA;
3123 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3124 << AA;
3125 NewAttributes.erase(CI: NewAttributes.begin() + I);
3126 --E;
3127 continue;
3128 }
3129 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3130 // If there is a C definition followed by a redeclaration with this
3131 // attribute then there are two different definitions. In C++, prefer the
3132 // standard diagnostics.
3133 if (!S.getLangOpts().CPlusPlus) {
3134 S.Diag(Loc: NewAttribute->getLocation(),
3135 DiagID: diag::err_loader_uninitialized_redeclaration);
3136 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3137 NewAttributes.erase(CI: NewAttributes.begin() + I);
3138 --E;
3139 continue;
3140 }
3141 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3142 cast<VarDecl>(Val: New)->isInline() &&
3143 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3144 // Don't warn about applying selectany to implicitly inline variables.
3145 // Older compilers and language modes would require the use of selectany
3146 // to make such variables inline, and it would have no effect if we
3147 // honored it.
3148 ++I;
3149 continue;
3150 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3151 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3152 // declarations after definitions.
3153 ++I;
3154 continue;
3155 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3156 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3157 // error since the definition will have already been created without
3158 // the semantic effects of the attribute having been applied.
3159 S.Diag(Loc: NewAttribute->getLocation(),
3160 DiagID: diag::err_sycl_entry_point_after_definition)
3161 << NewAttribute;
3162 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3163 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3164 ++I;
3165 continue;
3166 } else if (isa<SYCLExternalAttr>(Val: NewAttribute)) {
3167 // SYCLExternalAttr may be added after a definition.
3168 ++I;
3169 continue;
3170 }
3171
3172 S.Diag(Loc: NewAttribute->getLocation(),
3173 DiagID: diag::warn_attribute_precede_definition);
3174 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3175 NewAttributes.erase(CI: NewAttributes.begin() + I);
3176 --E;
3177 }
3178}
3179
3180static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3181 const ConstInitAttr *CIAttr,
3182 bool AttrBeforeInit) {
3183 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3184
3185 // Figure out a good way to write this specifier on the old declaration.
3186 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3187 // enough of the attribute list spelling information to extract that without
3188 // heroics.
3189 std::string SuitableSpelling;
3190 if (S.getLangOpts().CPlusPlus20)
3191 SuitableSpelling = std::string(
3192 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3193 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3194 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3195 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3196 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3197 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3198 tok::r_square, tok::r_square}));
3199 if (SuitableSpelling.empty())
3200 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3201 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3202 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3203 tok::r_paren, tok::r_paren}));
3204 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3205 SuitableSpelling = "constinit";
3206 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3207 SuitableSpelling = "[[clang::require_constant_initialization]]";
3208 if (SuitableSpelling.empty())
3209 SuitableSpelling = "__attribute__((require_constant_initialization))";
3210 SuitableSpelling += " ";
3211
3212 if (AttrBeforeInit) {
3213 // extern constinit int a;
3214 // int a = 0; // error (missing 'constinit'), accepted as extension
3215 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3216 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3217 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3218 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3219 } else {
3220 // int a = 0;
3221 // constinit extern int a; // error (missing 'constinit')
3222 S.Diag(Loc: CIAttr->getLocation(),
3223 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3224 : diag::warn_require_const_init_added_too_late)
3225 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3226 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3227 << CIAttr->isConstinit()
3228 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3229 }
3230}
3231
3232void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3233 AvailabilityMergeKind AMK) {
3234 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3235 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3236 NewAttr->setInherited(true);
3237 New->addAttr(A: NewAttr);
3238 }
3239 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3240 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3241 NewAttr->setInherited(true);
3242 New->addAttr(A: NewAttr);
3243 }
3244
3245 if (!Old->hasAttrs() && !New->hasAttrs())
3246 return;
3247
3248 // [dcl.constinit]p1:
3249 // If the [constinit] specifier is applied to any declaration of a
3250 // variable, it shall be applied to the initializing declaration.
3251 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3252 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3253 if (bool(OldConstInit) != bool(NewConstInit)) {
3254 const auto *OldVD = cast<VarDecl>(Val: Old);
3255 auto *NewVD = cast<VarDecl>(Val: New);
3256
3257 // Find the initializing declaration. Note that we might not have linked
3258 // the new declaration into the redeclaration chain yet.
3259 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3260 if (!InitDecl &&
3261 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3262 InitDecl = NewVD;
3263
3264 if (InitDecl == NewVD) {
3265 // This is the initializing declaration. If it would inherit 'constinit',
3266 // that's ill-formed. (Note that we do not apply this to the attribute
3267 // form).
3268 if (OldConstInit && OldConstInit->isConstinit())
3269 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3270 /*AttrBeforeInit=*/true);
3271 } else if (NewConstInit) {
3272 // This is the first time we've been told that this declaration should
3273 // have a constant initializer. If we already saw the initializing
3274 // declaration, this is too late.
3275 if (InitDecl && InitDecl != NewVD) {
3276 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3277 /*AttrBeforeInit=*/false);
3278 NewVD->dropAttr<ConstInitAttr>();
3279 }
3280 }
3281 }
3282
3283 // Attributes declared post-definition are currently ignored.
3284 checkNewAttributesAfterDef(S&: *this, New, Old);
3285
3286 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3287 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3288 if (!OldA->isEquivalent(Other: NewA)) {
3289 // This redeclaration changes __asm__ label.
3290 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3291 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3292 }
3293 } else if (Old->isUsed()) {
3294 // This redeclaration adds an __asm__ label to a declaration that has
3295 // already been ODR-used.
3296 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3297 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3298 }
3299 }
3300
3301 // Re-declaration cannot add abi_tag's.
3302 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3303 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3304 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3305 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3306 Diag(Loc: NewAbiTagAttr->getLocation(),
3307 DiagID: diag::err_new_abi_tag_on_redeclaration)
3308 << NewTag;
3309 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3310 }
3311 }
3312 } else {
3313 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3314 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3315 }
3316 }
3317
3318 // This redeclaration adds a section attribute.
3319 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3320 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3321 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3322 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3323 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3324 }
3325 }
3326 }
3327
3328 // Redeclaration adds code-seg attribute.
3329 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3330 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3331 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3332 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3333 << 0 /*codeseg*/;
3334 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3335 }
3336
3337 if (!Old->hasAttrs())
3338 return;
3339
3340 bool foundAny = New->hasAttrs();
3341
3342 // Ensure that any moving of objects within the allocated map is done before
3343 // we process them.
3344 if (!foundAny) New->setAttrs(AttrVec());
3345
3346 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3347 // Ignore deprecated/unavailable/availability attributes if requested.
3348 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3349 if (isa<DeprecatedAttr>(Val: I) ||
3350 isa<UnavailableAttr>(Val: I) ||
3351 isa<AvailabilityAttr>(Val: I)) {
3352 switch (AMK) {
3353 case AvailabilityMergeKind::None:
3354 continue;
3355
3356 case AvailabilityMergeKind::Redeclaration:
3357 case AvailabilityMergeKind::Override:
3358 case AvailabilityMergeKind::ProtocolImplementation:
3359 case AvailabilityMergeKind::OptionalProtocolImplementation:
3360 LocalAMK = AMK;
3361 break;
3362 }
3363 }
3364
3365 // Already handled.
3366 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3367 continue;
3368
3369 if (isa<InferredNoReturnAttr>(Val: I)) {
3370 if (auto *FD = dyn_cast<FunctionDecl>(Val: New);
3371 FD &&
3372 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3373 continue; // Don't propagate inferred noreturn attributes to explicit
3374 }
3375
3376 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3377 foundAny = true;
3378 }
3379
3380 if (mergeAlignedAttrs(S&: *this, New, Old))
3381 foundAny = true;
3382
3383 if (!foundAny) New->dropAttrs();
3384}
3385
3386void Sema::CheckAttributesOnDeducedType(Decl *D) {
3387 for (const Attr *A : D->attrs())
3388 checkAttrIsTypeDependent(D, A);
3389}
3390
3391// Returns the number of added attributes.
3392template <class T>
3393static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3394 Sema &S) {
3395 unsigned found = 0;
3396 for (const auto *I : From->specific_attrs<T>()) {
3397 if (!DeclHasAttr(To, I)) {
3398 T *newAttr = cast<T>(I->clone(S.Context));
3399 newAttr->setInherited(true);
3400 To->addAttr(A: newAttr);
3401 ++found;
3402 }
3403 }
3404 return found;
3405}
3406
3407template <class F>
3408static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3409 F &&propagator) {
3410 if (!From->hasAttrs()) {
3411 return;
3412 }
3413
3414 bool foundAny = To->hasAttrs();
3415
3416 // Ensure that any moving of objects within the allocated map is
3417 // done before we process them.
3418 if (!foundAny)
3419 To->setAttrs(AttrVec());
3420
3421 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3422
3423 if (!foundAny)
3424 To->dropAttrs();
3425}
3426
3427/// mergeParamDeclAttributes - Copy attributes from the old parameter
3428/// to the new one.
3429static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3430 const ParmVarDecl *oldDecl,
3431 Sema &S) {
3432 // C++11 [dcl.attr.depend]p2:
3433 // The first declaration of a function shall specify the
3434 // carries_dependency attribute for its declarator-id if any declaration
3435 // of the function specifies the carries_dependency attribute.
3436 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3437 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3438 S.Diag(Loc: CDA->getLocation(),
3439 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3440 // Find the first declaration of the parameter.
3441 // FIXME: Should we build redeclaration chains for function parameters?
3442 const FunctionDecl *FirstFD =
3443 cast<FunctionDecl>(Val: oldDecl->getDeclContext())->getFirstDecl();
3444 const ParmVarDecl *FirstVD =
3445 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3446 S.Diag(Loc: FirstVD->getLocation(),
3447 DiagID: diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3448 }
3449
3450 propagateAttributes(
3451 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3452 unsigned found = 0;
3453 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3454 // Propagate the lifetimebound attribute from parameters to the
3455 // most recent declaration. Note that this doesn't include the implicit
3456 // 'this' parameter, as the attribute is applied to the function type in
3457 // that case.
3458 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3459 return found;
3460 });
3461}
3462
3463static bool EquivalentArrayTypes(QualType Old, QualType New,
3464 const ASTContext &Ctx) {
3465
3466 auto NoSizeInfo = [&Ctx](QualType Ty) {
3467 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3468 return true;
3469 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3470 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3471 return false;
3472 };
3473
3474 // `type[]` is equivalent to `type *` and `type[*]`.
3475 if (NoSizeInfo(Old) && NoSizeInfo(New))
3476 return true;
3477
3478 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3479 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3480 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3481 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3482 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3483 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3484 return false;
3485 return true;
3486 }
3487
3488 // Only compare size, ignore Size modifiers and CVR.
3489 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3490 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3491 Ctx.getAsConstantArrayType(T: New)->getSize();
3492 }
3493
3494 // Don't try to compare dependent sized array
3495 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3496 return true;
3497 }
3498
3499 return Old == New;
3500}
3501
3502static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3503 const ParmVarDecl *OldParam,
3504 Sema &S) {
3505 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3506 if (auto Newnullability = NewParam->getType()->getNullability()) {
3507 if (*Oldnullability != *Newnullability) {
3508 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3509 << DiagNullabilityKind(
3510 *Newnullability,
3511 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3512 != 0))
3513 << DiagNullabilityKind(
3514 *Oldnullability,
3515 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3516 != 0));
3517 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3518 }
3519 } else {
3520 QualType NewT = NewParam->getType();
3521 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3522 NewParam->setType(NewT);
3523 }
3524 }
3525 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3526 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3527 if (OldParamDT && NewParamDT &&
3528 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3529 QualType OldParamOT = OldParamDT->getOriginalType();
3530 QualType NewParamOT = NewParamDT->getOriginalType();
3531 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3532 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3533 << NewParam << NewParamOT;
3534 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3535 << OldParamOT;
3536 }
3537 }
3538}
3539
3540namespace {
3541
3542/// Used in MergeFunctionDecl to keep track of function parameters in
3543/// C.
3544struct GNUCompatibleParamWarning {
3545 ParmVarDecl *OldParm;
3546 ParmVarDecl *NewParm;
3547 QualType PromotedType;
3548};
3549
3550} // end anonymous namespace
3551
3552// Determine whether the previous declaration was a definition, implicit
3553// declaration, or a declaration.
3554template <typename T>
3555static std::pair<diag::kind, SourceLocation>
3556getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3557 diag::kind PrevDiag;
3558 SourceLocation OldLocation = Old->getLocation();
3559 if (Old->isThisDeclarationADefinition())
3560 PrevDiag = diag::note_previous_definition;
3561 else if (Old->isImplicit()) {
3562 PrevDiag = diag::note_previous_implicit_declaration;
3563 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3564 if (FD->getBuiltinID())
3565 PrevDiag = diag::note_previous_builtin_declaration;
3566 }
3567 if (OldLocation.isInvalid())
3568 OldLocation = New->getLocation();
3569 } else
3570 PrevDiag = diag::note_previous_declaration;
3571 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3572}
3573
3574/// canRedefineFunction - checks if a function can be redefined. Currently,
3575/// only extern inline functions can be redefined, and even then only in
3576/// GNU89 mode.
3577static bool canRedefineFunction(const FunctionDecl *FD,
3578 const LangOptions& LangOpts) {
3579 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3580 !LangOpts.CPlusPlus &&
3581 FD->isInlineSpecified() &&
3582 FD->getStorageClass() == SC_Extern);
3583}
3584
3585const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3586 const AttributedType *AT = T->getAs<AttributedType>();
3587 while (AT && !AT->isCallingConv())
3588 AT = AT->getModifiedType()->getAs<AttributedType>();
3589 return AT;
3590}
3591
3592template <typename T>
3593static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3594 const DeclContext *DC = Old->getDeclContext();
3595 if (DC->isRecord())
3596 return false;
3597
3598 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3599 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3600 return true;
3601 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3602 return true;
3603 return false;
3604}
3605
3606template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3607static bool isExternC(VarTemplateDecl *) { return false; }
3608static bool isExternC(FunctionTemplateDecl *) { return false; }
3609
3610/// Check whether a redeclaration of an entity introduced by a
3611/// using-declaration is valid, given that we know it's not an overload
3612/// (nor a hidden tag declaration).
3613template<typename ExpectedDecl>
3614static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3615 ExpectedDecl *New) {
3616 // C++11 [basic.scope.declarative]p4:
3617 // Given a set of declarations in a single declarative region, each of
3618 // which specifies the same unqualified name,
3619 // -- they shall all refer to the same entity, or all refer to functions
3620 // and function templates; or
3621 // -- exactly one declaration shall declare a class name or enumeration
3622 // name that is not a typedef name and the other declarations shall all
3623 // refer to the same variable or enumerator, or all refer to functions
3624 // and function templates; in this case the class name or enumeration
3625 // name is hidden (3.3.10).
3626
3627 // C++11 [namespace.udecl]p14:
3628 // If a function declaration in namespace scope or block scope has the
3629 // same name and the same parameter-type-list as a function introduced
3630 // by a using-declaration, and the declarations do not declare the same
3631 // function, the program is ill-formed.
3632
3633 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3634 if (Old &&
3635 !Old->getDeclContext()->getRedeclContext()->Equals(
3636 New->getDeclContext()->getRedeclContext()) &&
3637 !(isExternC(Old) && isExternC(New)))
3638 Old = nullptr;
3639
3640 if (!Old) {
3641 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3642 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3643 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3644 return true;
3645 }
3646 return false;
3647}
3648
3649static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3650 const FunctionDecl *B) {
3651 assert(A->getNumParams() == B->getNumParams());
3652
3653 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3654 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3655 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3656 if (AttrA == AttrB)
3657 return true;
3658 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3659 AttrA->isDynamic() == AttrB->isDynamic();
3660 };
3661
3662 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3663}
3664
3665/// If necessary, adjust the semantic declaration context for a qualified
3666/// declaration to name the correct inline namespace within the qualifier.
3667static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3668 DeclaratorDecl *OldD) {
3669 // The only case where we need to update the DeclContext is when
3670 // redeclaration lookup for a qualified name finds a declaration
3671 // in an inline namespace within the context named by the qualifier:
3672 //
3673 // inline namespace N { int f(); }
3674 // int ::f(); // Sema DC needs adjusting from :: to N::.
3675 //
3676 // For unqualified declarations, the semantic context *can* change
3677 // along the redeclaration chain (for local extern declarations,
3678 // extern "C" declarations, and friend declarations in particular).
3679 if (!NewD->getQualifier())
3680 return;
3681
3682 // NewD is probably already in the right context.
3683 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3684 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3685 if (NamedDC->Equals(DC: SemaDC))
3686 return;
3687
3688 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3689 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3690 "unexpected context for redeclaration");
3691
3692 auto *LexDC = NewD->getLexicalDeclContext();
3693 auto FixSemaDC = [=](NamedDecl *D) {
3694 if (!D)
3695 return;
3696 D->setDeclContext(SemaDC);
3697 D->setLexicalDeclContext(LexDC);
3698 };
3699
3700 FixSemaDC(NewD);
3701 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3702 FixSemaDC(FD->getDescribedFunctionTemplate());
3703 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3704 FixSemaDC(VD->getDescribedVarTemplate());
3705}
3706
3707bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3708 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3709 // Verify the old decl was also a function.
3710 FunctionDecl *Old = OldD->getAsFunction();
3711 if (!Old) {
3712 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3713 // We don't need to check the using friend pattern from other module unit
3714 // since we should have diagnosed such cases in its unit already.
3715 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3716 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3717 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3718 DiagID: diag::note_using_decl_target);
3719 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3720 << 0;
3721 return true;
3722 }
3723
3724 // Check whether the two declarations might declare the same function or
3725 // function template.
3726 if (FunctionTemplateDecl *NewTemplate =
3727 New->getDescribedFunctionTemplate()) {
3728 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3729 New: NewTemplate))
3730 return true;
3731 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3732 ->getAsFunction();
3733 } else {
3734 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3735 return true;
3736 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3737 }
3738 } else {
3739 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3740 << New->getDeclName();
3741 notePreviousDefinition(Old: OldD, New: New->getLocation());
3742 return true;
3743 }
3744 }
3745
3746 // If the old declaration was found in an inline namespace and the new
3747 // declaration was qualified, update the DeclContext to match.
3748 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3749
3750 // If the old declaration is invalid, just give up here.
3751 if (Old->isInvalidDecl())
3752 return true;
3753
3754 // Disallow redeclaration of some builtins.
3755 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3756 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3757 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3758 << Old << Old->getType();
3759 return true;
3760 }
3761
3762 diag::kind PrevDiag;
3763 SourceLocation OldLocation;
3764 std::tie(args&: PrevDiag, args&: OldLocation) =
3765 getNoteDiagForInvalidRedeclaration(Old, New);
3766
3767 // Don't complain about this if we're in GNU89 mode and the old function
3768 // is an extern inline function.
3769 // Don't complain about specializations. They are not supposed to have
3770 // storage classes.
3771 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3772 New->getStorageClass() == SC_Static &&
3773 Old->hasExternalFormalLinkage() &&
3774 !New->getTemplateSpecializationInfo() &&
3775 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3776 if (getLangOpts().MicrosoftExt) {
3777 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3778 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3779 } else {
3780 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static) << New;
3781 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3782 return true;
3783 }
3784 }
3785
3786 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3787 if (!Old->hasAttr<InternalLinkageAttr>()) {
3788 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3789 << ILA;
3790 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3791 New->dropAttr<InternalLinkageAttr>();
3792 }
3793
3794 if (auto *EA = New->getAttr<ErrorAttr>()) {
3795 if (!Old->hasAttr<ErrorAttr>()) {
3796 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3797 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3798 New->dropAttr<ErrorAttr>();
3799 }
3800 }
3801
3802 if (CheckRedeclarationInModule(New, Old))
3803 return true;
3804
3805 if (!getLangOpts().CPlusPlus) {
3806 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3807 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3808 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3809 << New << OldOvl;
3810
3811 // Try our best to find a decl that actually has the overloadable
3812 // attribute for the note. In most cases (e.g. programs with only one
3813 // broken declaration/definition), this won't matter.
3814 //
3815 // FIXME: We could do this if we juggled some extra state in
3816 // OverloadableAttr, rather than just removing it.
3817 const Decl *DiagOld = Old;
3818 if (OldOvl) {
3819 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3820 const auto *A = D->getAttr<OverloadableAttr>();
3821 return A && !A->isImplicit();
3822 });
3823 // If we've implicitly added *all* of the overloadable attrs to this
3824 // chain, emitting a "previous redecl" note is pointless.
3825 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3826 }
3827
3828 if (DiagOld)
3829 Diag(Loc: DiagOld->getLocation(),
3830 DiagID: diag::note_attribute_overloadable_prev_overload)
3831 << OldOvl;
3832
3833 if (OldOvl)
3834 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3835 else
3836 New->dropAttr<OverloadableAttr>();
3837 }
3838 }
3839
3840 // It is not permitted to redeclare an SME function with different SME
3841 // attributes.
3842 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3843 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3844 << New->getType() << Old->getType();
3845 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3846 return true;
3847 }
3848
3849 // If a function is first declared with a calling convention, but is later
3850 // declared or defined without one, all following decls assume the calling
3851 // convention of the first.
3852 //
3853 // It's OK if a function is first declared without a calling convention,
3854 // but is later declared or defined with the default calling convention.
3855 //
3856 // To test if either decl has an explicit calling convention, we look for
3857 // AttributedType sugar nodes on the type as written. If they are missing or
3858 // were canonicalized away, we assume the calling convention was implicit.
3859 //
3860 // Note also that we DO NOT return at this point, because we still have
3861 // other tests to run.
3862 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3863 QualType NewQType = Context.getCanonicalType(T: New->getType());
3864 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3865 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3866 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3867 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3868 bool RequiresAdjustment = false;
3869
3870 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3871 FunctionDecl *First = Old->getFirstDecl();
3872 const FunctionType *FT =
3873 First->getType().getCanonicalType()->castAs<FunctionType>();
3874 FunctionType::ExtInfo FI = FT->getExtInfo();
3875 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3876 if (!NewCCExplicit) {
3877 // Inherit the CC from the previous declaration if it was specified
3878 // there but not here.
3879 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3880 RequiresAdjustment = true;
3881 } else if (Old->getBuiltinID()) {
3882 // Builtin attribute isn't propagated to the new one yet at this point,
3883 // so we check if the old one is a builtin.
3884
3885 // Calling Conventions on a Builtin aren't really useful and setting a
3886 // default calling convention and cdecl'ing some builtin redeclarations is
3887 // common, so warn and ignore the calling convention on the redeclaration.
3888 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3889 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3890 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3891 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3892 RequiresAdjustment = true;
3893 } else {
3894 // Calling conventions aren't compatible, so complain.
3895 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3896 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3897 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3898 << !FirstCCExplicit
3899 << (!FirstCCExplicit ? "" :
3900 FunctionType::getNameForCallConv(CC: FI.getCC()));
3901
3902 // Put the note on the first decl, since it is the one that matters.
3903 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3904 return true;
3905 }
3906 }
3907
3908 // FIXME: diagnose the other way around?
3909 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3910 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3911 RequiresAdjustment = true;
3912 }
3913
3914 // If the declaration is marked with cfi_unchecked_callee but the definition
3915 // isn't, the definition is also cfi_unchecked_callee.
3916 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3917 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3918 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3919 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3920
3921 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3922 EPI2.CFIUncheckedCallee = true;
3923 NewQType = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
3924 Args: FPT2->getParamTypes(), EPI: EPI2);
3925 NewType = cast<FunctionType>(Val&: NewQType);
3926 New->setType(NewQType);
3927 }
3928 }
3929 }
3930
3931 // Merge regparm attribute.
3932 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3933 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3934 if (NewTypeInfo.getHasRegParm()) {
3935 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
3936 << NewType->getRegParmType()
3937 << OldType->getRegParmType();
3938 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3939 return true;
3940 }
3941
3942 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3943 RequiresAdjustment = true;
3944 }
3945
3946 // Merge ns_returns_retained attribute.
3947 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3948 if (NewTypeInfo.getProducesResult()) {
3949 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
3950 << "'ns_returns_retained'";
3951 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3952 return true;
3953 }
3954
3955 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3956 RequiresAdjustment = true;
3957 }
3958
3959 if (OldTypeInfo.getNoCallerSavedRegs() !=
3960 NewTypeInfo.getNoCallerSavedRegs()) {
3961 if (NewTypeInfo.getNoCallerSavedRegs()) {
3962 AnyX86NoCallerSavedRegistersAttr *Attr =
3963 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3964 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
3965 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3966 return true;
3967 }
3968
3969 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3970 RequiresAdjustment = true;
3971 }
3972
3973 if (RequiresAdjustment) {
3974 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3975 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
3976 New->setType(QualType(AdjustedType, 0));
3977 NewQType = Context.getCanonicalType(T: New->getType());
3978 }
3979
3980 // If this redeclaration makes the function inline, we may need to add it to
3981 // UndefinedButUsed.
3982 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3983 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
3984 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3985 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
3986 y: SourceLocation()));
3987
3988 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3989 // about it.
3990 if (New->hasAttr<GNUInlineAttr>() &&
3991 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3992 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
3993 }
3994
3995 // If pass_object_size params don't match up perfectly, this isn't a valid
3996 // redeclaration.
3997 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3998 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
3999 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
4000 << New->getDeclName();
4001 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4002 return true;
4003 }
4004
4005 QualType OldQTypeForComparison = OldQType;
4006 if (Context.hasAnyFunctionEffects()) {
4007 const auto OldFX = Old->getFunctionEffects();
4008 const auto NewFX = New->getFunctionEffects();
4009 if (OldFX != NewFX) {
4010 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4011 for (const auto &Diff : Diffs) {
4012 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
4013 Diag(Loc: New->getLocation(),
4014 DiagID: diag::warn_mismatched_func_effect_redeclaration)
4015 << Diff.effectName();
4016 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4017 }
4018 }
4019 // Following a warning, we could skip merging effects from the previous
4020 // declaration, but that would trigger an additional "conflicting types"
4021 // error.
4022 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4023 FunctionEffectSet::Conflicts MergeErrs;
4024 FunctionEffectSet MergedFX =
4025 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
4026 if (!MergeErrs.empty())
4027 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
4028 OldLoc: Old->getLocation());
4029
4030 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4031 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4032 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
4033 Args: NewFPT->getParamTypes(), EPI);
4034
4035 New->setType(ModQT);
4036 NewQType = New->getType();
4037
4038 // Revise OldQTForComparison to include the merged effects,
4039 // so as not to fail due to differences later.
4040 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4041 EPI = OldFPT->getExtProtoInfo();
4042 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4043 OldQTypeForComparison = Context.getFunctionType(
4044 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
4045 }
4046 if (OldFX.empty()) {
4047 // A redeclaration may add the attribute to a previously seen function
4048 // body which needs to be verified.
4049 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
4050 }
4051 }
4052 }
4053 }
4054
4055 if (getLangOpts().CPlusPlus) {
4056 OldQType = Context.getCanonicalType(T: Old->getType());
4057 NewQType = Context.getCanonicalType(T: New->getType());
4058
4059 // Go back to the type source info to compare the declared return types,
4060 // per C++1y [dcl.type.auto]p13:
4061 // Redeclarations or specializations of a function or function template
4062 // with a declared return type that uses a placeholder type shall also
4063 // use that placeholder, not a deduced type.
4064 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4065 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4066 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
4067 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
4068 OldT: OldDeclaredReturnType)) {
4069 QualType ResQT;
4070 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4071 OldDeclaredReturnType->isObjCObjectPointerType())
4072 // FIXME: This does the wrong thing for a deduced return type.
4073 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4074 if (ResQT.isNull()) {
4075 if (New->isCXXClassMember() && New->isOutOfLine())
4076 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
4077 << New << New->getReturnTypeSourceRange();
4078 else if (Old->isExternC() && New->isExternC() &&
4079 !Old->hasAttr<OverloadableAttr>() &&
4080 !New->hasAttr<OverloadableAttr>())
4081 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4082 else
4083 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
4084 << New->getReturnTypeSourceRange();
4085 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
4086 << Old->getReturnTypeSourceRange();
4087 return true;
4088 }
4089 else
4090 NewQType = ResQT;
4091 }
4092
4093 QualType OldReturnType = OldType->getReturnType();
4094 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
4095 if (OldReturnType != NewReturnType) {
4096 // If this function has a deduced return type and has already been
4097 // defined, copy the deduced value from the old declaration.
4098 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4099 if (OldAT && OldAT->isDeduced()) {
4100 QualType DT = OldAT->getDeducedType();
4101 if (DT.isNull()) {
4102 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
4103 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
4104 } else {
4105 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
4106 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
4107 }
4108 }
4109 }
4110
4111 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
4112 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
4113 if (OldMethod && NewMethod) {
4114 // Preserve triviality.
4115 NewMethod->setTrivial(OldMethod->isTrivial());
4116
4117 // MSVC allows explicit template specialization at class scope:
4118 // 2 CXXMethodDecls referring to the same function will be injected.
4119 // We don't want a redeclaration error.
4120 bool IsClassScopeExplicitSpecialization =
4121 OldMethod->isFunctionTemplateSpecialization() &&
4122 NewMethod->isFunctionTemplateSpecialization();
4123 bool isFriend = NewMethod->getFriendObjectKind();
4124
4125 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4126 !IsClassScopeExplicitSpecialization) {
4127 // -- Member function declarations with the same name and the
4128 // same parameter types cannot be overloaded if any of them
4129 // is a static member function declaration.
4130 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4131 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4132 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4133 return true;
4134 }
4135
4136 // C++ [class.mem]p1:
4137 // [...] A member shall not be declared twice in the
4138 // member-specification, except that a nested class or member
4139 // class template can be declared and then later defined.
4140 if (!inTemplateInstantiation()) {
4141 unsigned NewDiag;
4142 if (isa<CXXConstructorDecl>(Val: OldMethod))
4143 NewDiag = diag::err_constructor_redeclared;
4144 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4145 NewDiag = diag::err_destructor_redeclared;
4146 else if (isa<CXXConversionDecl>(Val: NewMethod))
4147 NewDiag = diag::err_conv_function_redeclared;
4148 else
4149 NewDiag = diag::err_member_redeclared;
4150
4151 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4152 } else {
4153 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4154 << New << New->getType();
4155 }
4156 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4157 return true;
4158
4159 // Complain if this is an explicit declaration of a special
4160 // member that was initially declared implicitly.
4161 //
4162 // As an exception, it's okay to befriend such methods in order
4163 // to permit the implicit constructor/destructor/operator calls.
4164 } else if (OldMethod->isImplicit()) {
4165 if (isFriend) {
4166 NewMethod->setImplicit();
4167 } else {
4168 Diag(Loc: NewMethod->getLocation(),
4169 DiagID: diag::err_definition_of_implicitly_declared_member)
4170 << New << getSpecialMember(MD: OldMethod);
4171 return true;
4172 }
4173 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4174 Diag(Loc: NewMethod->getLocation(),
4175 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4176 << getSpecialMember(MD: OldMethod);
4177 return true;
4178 }
4179 }
4180
4181 // C++1z [over.load]p2
4182 // Certain function declarations cannot be overloaded:
4183 // -- Function declarations that differ only in the return type,
4184 // the exception specification, or both cannot be overloaded.
4185
4186 // Check the exception specifications match. This may recompute the type of
4187 // both Old and New if it resolved exception specifications, so grab the
4188 // types again after this. Because this updates the type, we do this before
4189 // any of the other checks below, which may update the "de facto" NewQType
4190 // but do not necessarily update the type of New.
4191 if (CheckEquivalentExceptionSpec(Old, New))
4192 return true;
4193
4194 // C++11 [dcl.attr.noreturn]p1:
4195 // The first declaration of a function shall specify the noreturn
4196 // attribute if any declaration of that function specifies the noreturn
4197 // attribute.
4198 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4199 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4200 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4201 << NRA;
4202 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4203 }
4204
4205 // C++11 [dcl.attr.depend]p2:
4206 // The first declaration of a function shall specify the
4207 // carries_dependency attribute for its declarator-id if any declaration
4208 // of the function specifies the carries_dependency attribute.
4209 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4210 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4211 Diag(Loc: CDA->getLocation(),
4212 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4213 Diag(Loc: Old->getFirstDecl()->getLocation(),
4214 DiagID: diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4215 }
4216
4217 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4218 // When a function is declared with SYCL_EXTERNAL, that macro must be
4219 // used on the first declaration of that function in the translation unit.
4220 // Redeclarations of the function in the same translation unit may
4221 // optionally use SYCL_EXTERNAL, but this is not required.
4222 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4223 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4224 Diag(Loc: SEA->getLocation(), DiagID: diag::warn_sycl_external_missing_on_first_decl)
4225 << SEA;
4226 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4227 }
4228
4229 // (C++98 8.3.5p3):
4230 // All declarations for a function shall agree exactly in both the
4231 // return type and the parameter-type-list.
4232 // We also want to respect all the extended bits except noreturn.
4233
4234 // noreturn should now match unless the old type info didn't have it.
4235 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4236 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4237 const FunctionType *OldTypeForComparison
4238 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4239 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4240 assert(OldQTypeForComparison.isCanonical());
4241 }
4242
4243 if (haveIncompatibleLanguageLinkages(Old, New)) {
4244 // As a special case, retain the language linkage from previous
4245 // declarations of a friend function as an extension.
4246 //
4247 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4248 // and is useful because there's otherwise no way to specify language
4249 // linkage within class scope.
4250 //
4251 // Check cautiously as the friend object kind isn't yet complete.
4252 if (New->getFriendObjectKind() != Decl::FOK_None) {
4253 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4254 Diag(Loc: OldLocation, DiagID: PrevDiag);
4255 } else {
4256 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4257 Diag(Loc: OldLocation, DiagID: PrevDiag);
4258 return true;
4259 }
4260 }
4261
4262 // HLSL check parameters for matching ABI specifications.
4263 if (getLangOpts().HLSL) {
4264 if (HLSL().CheckCompatibleParameterABI(New, Old))
4265 return true;
4266
4267 // If no errors are generated when checking parameter ABIs we can check if
4268 // the two declarations have the same type ignoring the ABIs and if so,
4269 // the declarations can be merged. This case for merging is only valid in
4270 // HLSL because there are no valid cases of merging mismatched parameter
4271 // ABIs except the HLSL implicit in and explicit in.
4272 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4273 U: NewQType))
4274 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4275 // Fall through for conflicting redeclarations and redefinitions.
4276 }
4277
4278 // If the function types are compatible, merge the declarations. Ignore the
4279 // exception specifier because it was already checked above in
4280 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4281 // about incompatible types under -fms-compatibility.
4282 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4283 U: NewQType))
4284 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4285
4286 // If the types are imprecise (due to dependent constructs in friends or
4287 // local extern declarations), it's OK if they differ. We'll check again
4288 // during instantiation.
4289 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4290 return false;
4291
4292 // Fall through for conflicting redeclarations and redefinitions.
4293 }
4294
4295 // C: Function types need to be compatible, not identical. This handles
4296 // duplicate function decls like "void f(int); void f(enum X);" properly.
4297 if (!getLangOpts().CPlusPlus) {
4298 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4299 // type is specified by a function definition that contains a (possibly
4300 // empty) identifier list, both shall agree in the number of parameters
4301 // and the type of each parameter shall be compatible with the type that
4302 // results from the application of default argument promotions to the
4303 // type of the corresponding identifier. ...
4304 // This cannot be handled by ASTContext::typesAreCompatible() because that
4305 // doesn't know whether the function type is for a definition or not when
4306 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4307 // we need to cover here is that the number of arguments agree as the
4308 // default argument promotion rules were already checked by
4309 // ASTContext::typesAreCompatible().
4310 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4311 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4312 if (Old->hasInheritedPrototype())
4313 Old = Old->getCanonicalDecl();
4314 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4315 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4316 return true;
4317 }
4318
4319 // If we are merging two functions where only one of them has a prototype,
4320 // we may have enough information to decide to issue a diagnostic that the
4321 // function without a prototype will change behavior in C23. This handles
4322 // cases like:
4323 // void i(); void i(int j);
4324 // void i(int j); void i();
4325 // void i(); void i(int j) {}
4326 // See ActOnFinishFunctionBody() for other cases of the behavior change
4327 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4328 // type without a prototype.
4329 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4330 !New->isImplicit() && !Old->isImplicit()) {
4331 const FunctionDecl *WithProto, *WithoutProto;
4332 if (New->hasWrittenPrototype()) {
4333 WithProto = New;
4334 WithoutProto = Old;
4335 } else {
4336 WithProto = Old;
4337 WithoutProto = New;
4338 }
4339
4340 if (WithProto->getNumParams() != 0) {
4341 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4342 // The one without the prototype will be changing behavior in C23, so
4343 // warn about that one so long as it's a user-visible declaration.
4344 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4345 if (WithoutProto == New)
4346 IsWithoutProtoADef = NewDeclIsDefn;
4347 else
4348 IsWithProtoADef = NewDeclIsDefn;
4349 Diag(Loc: WithoutProto->getLocation(),
4350 DiagID: diag::warn_non_prototype_changes_behavior)
4351 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4352 << (WithoutProto == Old) << IsWithProtoADef;
4353
4354 // The reason the one without the prototype will be changing behavior
4355 // is because of the one with the prototype, so note that so long as
4356 // it's a user-visible declaration. There is one exception to this:
4357 // when the new declaration is a definition without a prototype, the
4358 // old declaration with a prototype is not the cause of the issue,
4359 // and that does not need to be noted because the one with a
4360 // prototype will not change behavior in C23.
4361 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4362 !IsWithoutProtoADef)
4363 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4364 }
4365 }
4366 }
4367
4368 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4369 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4370 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4371 const FunctionProtoType *OldProto = nullptr;
4372 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4373 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4374 // The old declaration provided a function prototype, but the
4375 // new declaration does not. Merge in the prototype.
4376 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4377 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4378 Args: OldProto->getParamTypes(),
4379 EPI: OldProto->getExtProtoInfo());
4380 New->setType(NewQType);
4381 New->setHasInheritedPrototype();
4382
4383 // Synthesize parameters with the same types.
4384 SmallVector<ParmVarDecl *, 16> Params;
4385 for (const auto &ParamType : OldProto->param_types()) {
4386 ParmVarDecl *Param = ParmVarDecl::Create(
4387 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4388 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4389 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4390 Param->setImplicit();
4391 Params.push_back(Elt: Param);
4392 }
4393
4394 New->setParams(Params);
4395 }
4396
4397 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4398 }
4399 }
4400
4401 // Check if the function types are compatible when pointer size address
4402 // spaces are ignored.
4403 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4404 return false;
4405
4406 // GNU C permits a K&R definition to follow a prototype declaration
4407 // if the declared types of the parameters in the K&R definition
4408 // match the types in the prototype declaration, even when the
4409 // promoted types of the parameters from the K&R definition differ
4410 // from the types in the prototype. GCC then keeps the types from
4411 // the prototype.
4412 //
4413 // If a variadic prototype is followed by a non-variadic K&R definition,
4414 // the K&R definition becomes variadic. This is sort of an edge case, but
4415 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4416 // C99 6.9.1p8.
4417 if (!getLangOpts().CPlusPlus &&
4418 Old->hasPrototype() && !New->hasPrototype() &&
4419 New->getType()->getAs<FunctionProtoType>() &&
4420 Old->getNumParams() == New->getNumParams()) {
4421 SmallVector<QualType, 16> ArgTypes;
4422 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4423 const FunctionProtoType *OldProto
4424 = Old->getType()->getAs<FunctionProtoType>();
4425 const FunctionProtoType *NewProto
4426 = New->getType()->getAs<FunctionProtoType>();
4427
4428 // Determine whether this is the GNU C extension.
4429 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4430 NewProto->getReturnType());
4431 bool LooseCompatible = !MergedReturn.isNull();
4432 for (unsigned Idx = 0, End = Old->getNumParams();
4433 LooseCompatible && Idx != End; ++Idx) {
4434 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4435 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4436 if (Context.typesAreCompatible(T1: OldParm->getType(),
4437 T2: NewProto->getParamType(i: Idx))) {
4438 ArgTypes.push_back(Elt: NewParm->getType());
4439 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4440 T2: NewParm->getType(),
4441 /*CompareUnqualified=*/true)) {
4442 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4443 .PromotedType: NewProto->getParamType(i: Idx) };
4444 Warnings.push_back(Elt: Warn);
4445 ArgTypes.push_back(Elt: NewParm->getType());
4446 } else
4447 LooseCompatible = false;
4448 }
4449
4450 if (LooseCompatible) {
4451 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4452 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4453 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4454 << Warnings[Warn].PromotedType
4455 << Warnings[Warn].OldParm->getType();
4456 if (Warnings[Warn].OldParm->getLocation().isValid())
4457 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4458 DiagID: diag::note_previous_declaration);
4459 }
4460
4461 if (MergeTypeWithOld)
4462 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4463 EPI: OldProto->getExtProtoInfo()));
4464 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4465 }
4466
4467 // Fall through to diagnose conflicting types.
4468 }
4469
4470 // A function that has already been declared has been redeclared or
4471 // defined with a different type; show an appropriate diagnostic.
4472
4473 // If the previous declaration was an implicitly-generated builtin
4474 // declaration, then at the very least we should use a specialized note.
4475 unsigned BuiltinID;
4476 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4477 // If it's actually a library-defined builtin function like 'malloc'
4478 // or 'printf', just warn about the incompatible redeclaration.
4479 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4480 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4481 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4482 << Old << Old->getType();
4483 return false;
4484 }
4485
4486 PrevDiag = diag::note_previous_builtin_declaration;
4487 }
4488
4489 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4490 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4491 return true;
4492}
4493
4494bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4495 Scope *S, bool MergeTypeWithOld) {
4496 // Merge the attributes
4497 mergeDeclAttributes(New, Old);
4498
4499 // Merge "pure" flag.
4500 if (Old->isPureVirtual())
4501 New->setIsPureVirtual();
4502
4503 // Merge "used" flag.
4504 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4505 New->setIsUsed();
4506
4507 // Merge attributes from the parameters. These can mismatch with K&R
4508 // declarations.
4509 if (New->getNumParams() == Old->getNumParams())
4510 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4511 ParmVarDecl *NewParam = New->getParamDecl(i);
4512 ParmVarDecl *OldParam = Old->getParamDecl(i);
4513 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4514 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4515 }
4516
4517 if (getLangOpts().CPlusPlus)
4518 return MergeCXXFunctionDecl(New, Old, S);
4519
4520 // Merge the function types so the we get the composite types for the return
4521 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4522 // was visible.
4523 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4524 if (!Merged.isNull() && MergeTypeWithOld)
4525 New->setType(Merged);
4526
4527 return false;
4528}
4529
4530void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4531 ObjCMethodDecl *oldMethod) {
4532 // Merge the attributes, including deprecated/unavailable
4533 AvailabilityMergeKind MergeKind =
4534 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4535 ? (oldMethod->isOptional()
4536 ? AvailabilityMergeKind::OptionalProtocolImplementation
4537 : AvailabilityMergeKind::ProtocolImplementation)
4538 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4539 ? AvailabilityMergeKind::Redeclaration
4540 : AvailabilityMergeKind::Override;
4541
4542 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4543
4544 // Merge attributes from the parameters.
4545 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4546 oe = oldMethod->param_end();
4547 for (ObjCMethodDecl::param_iterator
4548 ni = newMethod->param_begin(), ne = newMethod->param_end();
4549 ni != ne && oi != oe; ++ni, ++oi)
4550 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4551
4552 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4553}
4554
4555static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4556 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4557
4558 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4559 ? diag::err_redefinition_different_type
4560 : diag::err_redeclaration_different_type)
4561 << New->getDeclName() << New->getType() << Old->getType();
4562
4563 diag::kind PrevDiag;
4564 SourceLocation OldLocation;
4565 std::tie(args&: PrevDiag, args&: OldLocation)
4566 = getNoteDiagForInvalidRedeclaration(Old, New);
4567 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4568 New->setInvalidDecl();
4569}
4570
4571void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4572 bool MergeTypeWithOld) {
4573 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4574 return;
4575
4576 QualType MergedT;
4577 if (getLangOpts().CPlusPlus) {
4578 if (New->getType()->isUndeducedType()) {
4579 // We don't know what the new type is until the initializer is attached.
4580 return;
4581 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4582 // These could still be something that needs exception specs checked.
4583 return MergeVarDeclExceptionSpecs(New, Old);
4584 }
4585 // C++ [basic.link]p10:
4586 // [...] the types specified by all declarations referring to a given
4587 // object or function shall be identical, except that declarations for an
4588 // array object can specify array types that differ by the presence or
4589 // absence of a major array bound (8.3.4).
4590 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4591 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4592 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4593
4594 // We are merging a variable declaration New into Old. If it has an array
4595 // bound, and that bound differs from Old's bound, we should diagnose the
4596 // mismatch.
4597 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4598 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4599 PrevVD = PrevVD->getPreviousDecl()) {
4600 QualType PrevVDTy = PrevVD->getType();
4601 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4602 continue;
4603
4604 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4605 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4606 }
4607 }
4608
4609 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4610 if (Context.hasSameType(T1: OldArray->getElementType(),
4611 T2: NewArray->getElementType()))
4612 MergedT = New->getType();
4613 }
4614 // FIXME: Check visibility. New is hidden but has a complete type. If New
4615 // has no array bound, it should not inherit one from Old, if Old is not
4616 // visible.
4617 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4618 if (Context.hasSameType(T1: OldArray->getElementType(),
4619 T2: NewArray->getElementType()))
4620 MergedT = Old->getType();
4621 }
4622 }
4623 else if (New->getType()->isObjCObjectPointerType() &&
4624 Old->getType()->isObjCObjectPointerType()) {
4625 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4626 Old->getType());
4627 }
4628 } else {
4629 // C 6.2.7p2:
4630 // All declarations that refer to the same object or function shall have
4631 // compatible type.
4632 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4633 }
4634 if (MergedT.isNull()) {
4635 // It's OK if we couldn't merge types if either type is dependent, for a
4636 // block-scope variable. In other cases (static data members of class
4637 // templates, variable templates, ...), we require the types to be
4638 // equivalent.
4639 // FIXME: The C++ standard doesn't say anything about this.
4640 if ((New->getType()->isDependentType() ||
4641 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4642 // If the old type was dependent, we can't merge with it, so the new type
4643 // becomes dependent for now. We'll reproduce the original type when we
4644 // instantiate the TypeSourceInfo for the variable.
4645 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4646 New->setType(Context.DependentTy);
4647 return;
4648 }
4649 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4650 }
4651
4652 // Don't actually update the type on the new declaration if the old
4653 // declaration was an extern declaration in a different scope.
4654 if (MergeTypeWithOld)
4655 New->setType(MergedT);
4656}
4657
4658static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4659 LookupResult &Previous) {
4660 // C11 6.2.7p4:
4661 // For an identifier with internal or external linkage declared
4662 // in a scope in which a prior declaration of that identifier is
4663 // visible, if the prior declaration specifies internal or
4664 // external linkage, the type of the identifier at the later
4665 // declaration becomes the composite type.
4666 //
4667 // If the variable isn't visible, we do not merge with its type.
4668 if (Previous.isShadowed())
4669 return false;
4670
4671 if (S.getLangOpts().CPlusPlus) {
4672 // C++11 [dcl.array]p3:
4673 // If there is a preceding declaration of the entity in the same
4674 // scope in which the bound was specified, an omitted array bound
4675 // is taken to be the same as in that earlier declaration.
4676 return NewVD->isPreviousDeclInSameBlockScope() ||
4677 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4678 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4679 } else {
4680 // If the old declaration was function-local, don't merge with its
4681 // type unless we're in the same function.
4682 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4683 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4684 }
4685}
4686
4687void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4688 // If the new decl is already invalid, don't do any other checking.
4689 if (New->isInvalidDecl())
4690 return;
4691
4692 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4693 return;
4694
4695 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4696
4697 // Verify the old decl was also a variable or variable template.
4698 VarDecl *Old = nullptr;
4699 VarTemplateDecl *OldTemplate = nullptr;
4700 if (Previous.isSingleResult()) {
4701 if (NewTemplate) {
4702 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4703 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4704
4705 if (auto *Shadow =
4706 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4707 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4708 return New->setInvalidDecl();
4709 } else {
4710 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4711
4712 if (auto *Shadow =
4713 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4714 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4715 return New->setInvalidDecl();
4716 }
4717 }
4718 if (!Old) {
4719 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4720 << New->getDeclName();
4721 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4722 New: New->getLocation());
4723 return New->setInvalidDecl();
4724 }
4725
4726 // If the old declaration was found in an inline namespace and the new
4727 // declaration was qualified, update the DeclContext to match.
4728 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4729
4730 // Ensure the template parameters are compatible.
4731 if (NewTemplate &&
4732 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4733 Old: OldTemplate->getTemplateParameters(),
4734 /*Complain=*/true, Kind: TPL_TemplateMatch))
4735 return New->setInvalidDecl();
4736
4737 // C++ [class.mem]p1:
4738 // A member shall not be declared twice in the member-specification [...]
4739 //
4740 // Here, we need only consider static data members.
4741 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4742 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4743 << New->getIdentifier();
4744 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4745 New->setInvalidDecl();
4746 }
4747
4748 mergeDeclAttributes(New, Old);
4749 // Warn if an already-defined variable is made a weak_import in a subsequent
4750 // declaration
4751 if (New->hasAttr<WeakImportAttr>())
4752 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4753 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4754 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4755 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4756 // Remove weak_import attribute on new declaration.
4757 New->dropAttr<WeakImportAttr>();
4758 break;
4759 }
4760 }
4761
4762 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4763 if (!Old->hasAttr<InternalLinkageAttr>()) {
4764 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4765 << ILA;
4766 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4767 New->dropAttr<InternalLinkageAttr>();
4768 }
4769
4770 // Merge the types.
4771 VarDecl *MostRecent = Old->getMostRecentDecl();
4772 if (MostRecent != Old) {
4773 MergeVarDeclTypes(New, Old: MostRecent,
4774 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4775 if (New->isInvalidDecl())
4776 return;
4777 }
4778
4779 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4780 if (New->isInvalidDecl())
4781 return;
4782
4783 diag::kind PrevDiag;
4784 SourceLocation OldLocation;
4785 std::tie(args&: PrevDiag, args&: OldLocation) =
4786 getNoteDiagForInvalidRedeclaration(Old, New);
4787
4788 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4789 if (New->getStorageClass() == SC_Static &&
4790 !New->isStaticDataMember() &&
4791 Old->hasExternalFormalLinkage()) {
4792 if (getLangOpts().MicrosoftExt) {
4793 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4794 << New->getDeclName();
4795 Diag(Loc: OldLocation, DiagID: PrevDiag);
4796 } else {
4797 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4798 << New->getDeclName();
4799 Diag(Loc: OldLocation, DiagID: PrevDiag);
4800 return New->setInvalidDecl();
4801 }
4802 }
4803 // C99 6.2.2p4:
4804 // For an identifier declared with the storage-class specifier
4805 // extern in a scope in which a prior declaration of that
4806 // identifier is visible,23) if the prior declaration specifies
4807 // internal or external linkage, the linkage of the identifier at
4808 // the later declaration is the same as the linkage specified at
4809 // the prior declaration. If no prior declaration is visible, or
4810 // if the prior declaration specifies no linkage, then the
4811 // identifier has external linkage.
4812 if (New->hasExternalStorage() && Old->hasLinkage())
4813 /* Okay */;
4814 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4815 !New->isStaticDataMember() &&
4816 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4817 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4818 Diag(Loc: OldLocation, DiagID: PrevDiag);
4819 return New->setInvalidDecl();
4820 }
4821
4822 // Check if extern is followed by non-extern and vice-versa.
4823 if (New->hasExternalStorage() &&
4824 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4825 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4826 Diag(Loc: OldLocation, DiagID: PrevDiag);
4827 return New->setInvalidDecl();
4828 }
4829 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4830 !New->hasExternalStorage()) {
4831 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4832 Diag(Loc: OldLocation, DiagID: PrevDiag);
4833 return New->setInvalidDecl();
4834 }
4835
4836 if (CheckRedeclarationInModule(New, Old))
4837 return;
4838
4839 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4840
4841 // FIXME: The test for external storage here seems wrong? We still
4842 // need to check for mismatches.
4843 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4844 // Don't complain about out-of-line definitions of static members.
4845 !(Old->getLexicalDeclContext()->isRecord() &&
4846 !New->getLexicalDeclContext()->isRecord())) {
4847 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4848 Diag(Loc: OldLocation, DiagID: PrevDiag);
4849 return New->setInvalidDecl();
4850 }
4851
4852 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4853 if (VarDecl *Def = Old->getDefinition()) {
4854 // C++1z [dcl.fcn.spec]p4:
4855 // If the definition of a variable appears in a translation unit before
4856 // its first declaration as inline, the program is ill-formed.
4857 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4858 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4859 }
4860 }
4861
4862 // If this redeclaration makes the variable inline, we may need to add it to
4863 // UndefinedButUsed.
4864 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4865 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4866 !Old->isInAnotherModuleUnit())
4867 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4868 y: SourceLocation()));
4869
4870 if (New->getTLSKind() != Old->getTLSKind()) {
4871 if (!Old->getTLSKind()) {
4872 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4873 Diag(Loc: OldLocation, DiagID: PrevDiag);
4874 } else if (!New->getTLSKind()) {
4875 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4876 Diag(Loc: OldLocation, DiagID: PrevDiag);
4877 } else {
4878 // Do not allow redeclaration to change the variable between requiring
4879 // static and dynamic initialization.
4880 // FIXME: GCC allows this, but uses the TLS keyword on the first
4881 // declaration to determine the kind. Do we need to be compatible here?
4882 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4883 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4884 Diag(Loc: OldLocation, DiagID: PrevDiag);
4885 }
4886 }
4887
4888 // C++ doesn't have tentative definitions, so go right ahead and check here.
4889 if (getLangOpts().CPlusPlus) {
4890 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4891 Old->getCanonicalDecl()->isConstexpr()) {
4892 // This definition won't be a definition any more once it's been merged.
4893 Diag(Loc: New->getLocation(),
4894 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4895 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4896 VarDecl *Def = Old->getDefinition();
4897 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4898 return;
4899 }
4900 } else {
4901 // C++ may not have a tentative definition rule, but it has a different
4902 // rule about what constitutes a definition in the first place. See
4903 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4904 // contains the extern specifier and doesn't have an initializer, it's fine
4905 // in C++.
4906 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4907 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4908 << New;
4909 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4910 }
4911 }
4912
4913 if (haveIncompatibleLanguageLinkages(Old, New)) {
4914 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4915 Diag(Loc: OldLocation, DiagID: PrevDiag);
4916 New->setInvalidDecl();
4917 return;
4918 }
4919
4920 // Merge "used" flag.
4921 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4922 New->setIsUsed();
4923
4924 // Keep a chain of previous declarations.
4925 New->setPreviousDecl(Old);
4926 if (NewTemplate)
4927 NewTemplate->setPreviousDecl(OldTemplate);
4928
4929 // Inherit access appropriately.
4930 New->setAccess(Old->getAccess());
4931 if (NewTemplate)
4932 NewTemplate->setAccess(New->getAccess());
4933
4934 if (Old->isInline())
4935 New->setImplicitlyInline();
4936}
4937
4938void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4939 SourceManager &SrcMgr = getSourceManager();
4940 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
4941 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
4942 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
4943 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
4944 auto &HSI = PP.getHeaderSearchInfo();
4945 StringRef HdrFilename =
4946 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
4947
4948 auto noteFromModuleOrInclude = [&](Module *Mod,
4949 SourceLocation IncLoc) -> bool {
4950 // Redefinition errors with modules are common with non modular mapped
4951 // headers, example: a non-modular header H in module A that also gets
4952 // included directly in a TU. Pointing twice to the same header/definition
4953 // is confusing, try to get better diagnostics when modules is on.
4954 if (IncLoc.isValid()) {
4955 if (Mod) {
4956 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
4957 << HdrFilename.str() << Mod->getFullModuleName();
4958 if (!Mod->DefinitionLoc.isInvalid())
4959 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
4960 << Mod->getFullModuleName();
4961 } else {
4962 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
4963 << HdrFilename.str();
4964 }
4965 return true;
4966 }
4967
4968 return false;
4969 };
4970
4971 // Is it the same file and same offset? Provide more information on why
4972 // this leads to a redefinition error.
4973 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4974 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
4975 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
4976 bool EmittedDiag =
4977 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4978 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4979
4980 // If the header has no guards, emit a note suggesting one.
4981 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
4982 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
4983
4984 if (EmittedDiag)
4985 return;
4986 }
4987
4988 // Redefinition coming from different files or couldn't do better above.
4989 if (Old->getLocation().isValid())
4990 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
4991}
4992
4993bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4994 if (!hasVisibleDefinition(D: Old) &&
4995 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4996 isa<VarTemplateSpecializationDecl>(Val: New) ||
4997 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4998 New->getDeclContext()->isDependentContext() ||
4999 New->hasAttr<SelectAnyAttr>())) {
5000 // The previous definition is hidden, and multiple definitions are
5001 // permitted (in separate TUs). Demote this to a declaration.
5002 New->demoteThisDefinitionToDeclaration();
5003
5004 // Make the canonical definition visible.
5005 if (auto *OldTD = Old->getDescribedVarTemplate())
5006 makeMergedDefinitionVisible(ND: OldTD);
5007 makeMergedDefinitionVisible(ND: Old);
5008 return false;
5009 } else {
5010 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
5011 notePreviousDefinition(Old, New: New->getLocation());
5012 New->setInvalidDecl();
5013 return true;
5014 }
5015}
5016
5017Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5018 DeclSpec &DS,
5019 const ParsedAttributesView &DeclAttrs,
5020 RecordDecl *&AnonRecord) {
5021 return ParsedFreeStandingDeclSpec(
5022 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
5023}
5024
5025// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5026// disambiguate entities defined in different scopes.
5027// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5028// compatibility.
5029// We will pick our mangling number depending on which version of MSVC is being
5030// targeted.
5031static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5032 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
5033 ? S->getMSCurManglingNumber()
5034 : S->getMSLastManglingNumber();
5035}
5036
5037void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5038 if (!Context.getLangOpts().CPlusPlus)
5039 return;
5040
5041 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
5042 // If this tag is the direct child of a class, number it if
5043 // it is anonymous.
5044 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5045 return;
5046 MangleNumberingContext &MCtx =
5047 Context.getManglingNumberContext(DC: Tag->getParent());
5048 Context.setManglingNumber(
5049 ND: Tag, Number: MCtx.getManglingNumber(
5050 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5051 return;
5052 }
5053
5054 // If this tag isn't a direct child of a class, number it if it is local.
5055 MangleNumberingContext *MCtx;
5056 Decl *ManglingContextDecl;
5057 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5058 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
5059 if (MCtx) {
5060 Context.setManglingNumber(
5061 ND: Tag, Number: MCtx->getManglingNumber(
5062 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5063 }
5064}
5065
5066namespace {
5067struct NonCLikeKind {
5068 enum {
5069 None,
5070 BaseClass,
5071 DefaultMemberInit,
5072 Lambda,
5073 Friend,
5074 OtherMember,
5075 Invalid,
5076 } Kind = None;
5077 SourceRange Range;
5078
5079 explicit operator bool() { return Kind != None; }
5080};
5081}
5082
5083/// Determine whether a class is C-like, according to the rules of C++
5084/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5085static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5086 if (RD->isInvalidDecl())
5087 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
5088
5089 // C++ [dcl.typedef]p9: [P1766R1]
5090 // An unnamed class with a typedef name for linkage purposes shall not
5091 //
5092 // -- have any base classes
5093 if (RD->getNumBases())
5094 return {.Kind: NonCLikeKind::BaseClass,
5095 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
5096 RD->bases_end()[-1].getEndLoc())};
5097 bool Invalid = false;
5098 for (Decl *D : RD->decls()) {
5099 // Don't complain about things we already diagnosed.
5100 if (D->isInvalidDecl()) {
5101 Invalid = true;
5102 continue;
5103 }
5104
5105 // -- have any [...] default member initializers
5106 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
5107 if (FD->hasInClassInitializer()) {
5108 auto *Init = FD->getInClassInitializer();
5109 return {.Kind: NonCLikeKind::DefaultMemberInit,
5110 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
5111 }
5112 continue;
5113 }
5114
5115 // FIXME: We don't allow friend declarations. This violates the wording of
5116 // P1766, but not the intent.
5117 if (isa<FriendDecl>(Val: D))
5118 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
5119
5120 // -- declare any members other than non-static data members, member
5121 // enumerations, or member classes,
5122 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
5123 isa<EnumDecl>(Val: D))
5124 continue;
5125 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
5126 if (!MemberRD) {
5127 if (D->isImplicit())
5128 continue;
5129 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
5130 }
5131
5132 // -- contain a lambda-expression,
5133 if (MemberRD->isLambda())
5134 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5135
5136 // and all member classes shall also satisfy these requirements
5137 // (recursively).
5138 if (MemberRD->isThisDeclarationADefinition()) {
5139 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5140 return Kind;
5141 }
5142 }
5143
5144 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5145}
5146
5147void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5148 TypedefNameDecl *NewTD) {
5149 if (TagFromDeclSpec->isInvalidDecl())
5150 return;
5151
5152 // Do nothing if the tag already has a name for linkage purposes.
5153 if (TagFromDeclSpec->hasNameForLinkage())
5154 return;
5155
5156 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5157 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5158
5159 // The type must match the tag exactly; no qualifiers allowed.
5160 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5161 T2: Context.getCanonicalTagType(TD: TagFromDeclSpec))) {
5162 if (getLangOpts().CPlusPlus)
5163 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5164 return;
5165 }
5166
5167 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5168 // An unnamed class with a typedef name for linkage purposes shall [be
5169 // C-like].
5170 //
5171 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5172 // shouldn't happen, but there are constructs that the language rule doesn't
5173 // disallow for which we can't reasonably avoid computing linkage early.
5174 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5175 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5176 : NonCLikeKind();
5177 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5178 if (NonCLike || ChangesLinkage) {
5179 if (NonCLike.Kind == NonCLikeKind::Invalid)
5180 return;
5181
5182 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5183 if (ChangesLinkage) {
5184 // If the linkage changes, we can't accept this as an extension.
5185 if (NonCLike.Kind == NonCLikeKind::None)
5186 DiagID = diag::err_typedef_changes_linkage;
5187 else
5188 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5189 }
5190
5191 SourceLocation FixitLoc =
5192 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5193 llvm::SmallString<40> TextToInsert;
5194 TextToInsert += ' ';
5195 TextToInsert += NewTD->getIdentifier()->getName();
5196
5197 Diag(Loc: FixitLoc, DiagID)
5198 << isa<TypeAliasDecl>(Val: NewTD)
5199 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5200 if (NonCLike.Kind != NonCLikeKind::None) {
5201 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5202 << NonCLike.Kind - 1 << NonCLike.Range;
5203 }
5204 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5205 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5206
5207 if (ChangesLinkage)
5208 return;
5209 }
5210
5211 // Otherwise, set this as the anon-decl typedef for the tag.
5212 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5213
5214 // Now that we have a name for the tag, process API notes again.
5215 ProcessAPINotes(D: TagFromDeclSpec);
5216}
5217
5218static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5219 DeclSpec::TST T = DS.getTypeSpecType();
5220 switch (T) {
5221 case DeclSpec::TST_class:
5222 return 0;
5223 case DeclSpec::TST_struct:
5224 return 1;
5225 case DeclSpec::TST_interface:
5226 return 2;
5227 case DeclSpec::TST_union:
5228 return 3;
5229 case DeclSpec::TST_enum:
5230 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5231 if (ED->isScopedUsingClassTag())
5232 return 5;
5233 if (ED->isScoped())
5234 return 6;
5235 }
5236 return 4;
5237 default:
5238 llvm_unreachable("unexpected type specifier");
5239 }
5240}
5241
5242Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5243 DeclSpec &DS,
5244 const ParsedAttributesView &DeclAttrs,
5245 MultiTemplateParamsArg TemplateParams,
5246 bool IsExplicitInstantiation,
5247 RecordDecl *&AnonRecord,
5248 SourceLocation EllipsisLoc) {
5249 Decl *TagD = nullptr;
5250 TagDecl *Tag = nullptr;
5251 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5252 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5253 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5254 DS.getTypeSpecType() == DeclSpec::TST_union ||
5255 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5256 TagD = DS.getRepAsDecl();
5257
5258 if (!TagD) // We probably had an error
5259 return nullptr;
5260
5261 // Note that the above type specs guarantee that the
5262 // type rep is a Decl, whereas in many of the others
5263 // it's a Type.
5264 if (isa<TagDecl>(Val: TagD))
5265 Tag = cast<TagDecl>(Val: TagD);
5266 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5267 Tag = CTD->getTemplatedDecl();
5268 }
5269
5270 if (Tag) {
5271 handleTagNumbering(Tag, TagScope: S);
5272 Tag->setFreeStanding();
5273 if (Tag->isInvalidDecl())
5274 return Tag;
5275 }
5276
5277 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5278 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5279 // or incomplete types shall not be restrict-qualified."
5280 if (TypeQuals & DeclSpec::TQ_restrict)
5281 Diag(Loc: DS.getRestrictSpecLoc(),
5282 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5283 << DS.getSourceRange();
5284 }
5285
5286 if (DS.isInlineSpecified())
5287 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5288 << getLangOpts().CPlusPlus17;
5289
5290 if (DS.hasConstexprSpecifier()) {
5291 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5292 // and definitions of functions and variables.
5293 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5294 // the declaration of a function or function template
5295 if (Tag)
5296 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5297 << GetDiagnosticTypeSpecifierID(DS)
5298 << static_cast<int>(DS.getConstexprSpecifier());
5299 else if (getLangOpts().C23)
5300 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5301 else
5302 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5303 << static_cast<int>(DS.getConstexprSpecifier());
5304 // Don't emit warnings after this error.
5305 return TagD;
5306 }
5307
5308 DiagnoseFunctionSpecifiers(DS);
5309
5310 if (DS.isFriendSpecified()) {
5311 // If we're dealing with a decl but not a TagDecl, assume that
5312 // whatever routines created it handled the friendship aspect.
5313 if (TagD && !Tag)
5314 return nullptr;
5315 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5316 }
5317
5318 assert(EllipsisLoc.isInvalid() &&
5319 "Friend ellipsis but not friend-specified?");
5320
5321 // Track whether this decl-specifier declares anything.
5322 bool DeclaresAnything = true;
5323
5324 // Handle anonymous struct definitions.
5325 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5326 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5327 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5328 if (getLangOpts().CPlusPlus ||
5329 Record->getDeclContext()->isRecord()) {
5330 // If CurContext is a DeclContext that can contain statements,
5331 // RecursiveASTVisitor won't visit the decls that
5332 // BuildAnonymousStructOrUnion() will put into CurContext.
5333 // Also store them here so that they can be part of the
5334 // DeclStmt that gets created in this case.
5335 // FIXME: Also return the IndirectFieldDecls created by
5336 // BuildAnonymousStructOr union, for the same reason?
5337 if (CurContext->isFunctionOrMethod())
5338 AnonRecord = Record;
5339 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5340 Policy: Context.getPrintingPolicy());
5341 }
5342
5343 DeclaresAnything = false;
5344 }
5345 }
5346
5347 // C11 6.7.2.1p2:
5348 // A struct-declaration that does not declare an anonymous structure or
5349 // anonymous union shall contain a struct-declarator-list.
5350 //
5351 // This rule also existed in C89 and C99; the grammar for struct-declaration
5352 // did not permit a struct-declaration without a struct-declarator-list.
5353 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5354 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5355 // Check for Microsoft C extension: anonymous struct/union member.
5356 // Handle 2 kinds of anonymous struct/union:
5357 // struct STRUCT;
5358 // union UNION;
5359 // and
5360 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5361 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5362 if ((Tag && Tag->getDeclName()) ||
5363 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5364 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Val: Tag)
5365 : DS.getRepAsType().get()->getAsRecordDecl();
5366 if (Record && getLangOpts().MSAnonymousStructs) {
5367 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5368 << Record->isUnion() << DS.getSourceRange();
5369 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5370 }
5371
5372 DeclaresAnything = false;
5373 }
5374 }
5375
5376 // Skip all the checks below if we have a type error.
5377 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5378 (TagD && TagD->isInvalidDecl()))
5379 return TagD;
5380
5381 if (getLangOpts().CPlusPlus &&
5382 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5383 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5384 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5385 !Enum->isInvalidDecl())
5386 DeclaresAnything = false;
5387
5388 if (!DS.isMissingDeclaratorOk()) {
5389 // Customize diagnostic for a typedef missing a name.
5390 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5391 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5392 << DS.getSourceRange();
5393 else
5394 DeclaresAnything = false;
5395 }
5396
5397 if (DS.isModulePrivateSpecified() &&
5398 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5399 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5400 << Tag->getTagKind()
5401 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5402
5403 ActOnDocumentableDecl(D: TagD);
5404
5405 // C 6.7/2:
5406 // A declaration [...] shall declare at least a declarator [...], a tag,
5407 // or the members of an enumeration.
5408 // C++ [dcl.dcl]p3:
5409 // [If there are no declarators], and except for the declaration of an
5410 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5411 // names into the program, or shall redeclare a name introduced by a
5412 // previous declaration.
5413 if (!DeclaresAnything) {
5414 // In C, we allow this as a (popular) extension / bug. Don't bother
5415 // producing further diagnostics for redundant qualifiers after this.
5416 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5417 ? diag::err_no_declarators
5418 : diag::ext_no_declarators)
5419 << DS.getSourceRange();
5420 return TagD;
5421 }
5422
5423 // C++ [dcl.stc]p1:
5424 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5425 // init-declarator-list of the declaration shall not be empty.
5426 // C++ [dcl.fct.spec]p1:
5427 // If a cv-qualifier appears in a decl-specifier-seq, the
5428 // init-declarator-list of the declaration shall not be empty.
5429 //
5430 // Spurious qualifiers here appear to be valid in C.
5431 unsigned DiagID = diag::warn_standalone_specifier;
5432 if (getLangOpts().CPlusPlus)
5433 DiagID = diag::ext_standalone_specifier;
5434
5435 // Note that a linkage-specification sets a storage class, but
5436 // 'extern "C" struct foo;' is actually valid and not theoretically
5437 // useless.
5438 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5439 if (SCS == DeclSpec::SCS_mutable)
5440 // Since mutable is not a viable storage class specifier in C, there is
5441 // no reason to treat it as an extension. Instead, diagnose as an error.
5442 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5443 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5444 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5445 << DeclSpec::getSpecifierName(S: SCS);
5446 }
5447
5448 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5449 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5450 << DeclSpec::getSpecifierName(S: TSCS);
5451 if (DS.getTypeQualifiers()) {
5452 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5453 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5454 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5455 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5456 // Restrict is covered above.
5457 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5458 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5459 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5460 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5461 }
5462
5463 // Warn about ignored type attributes, for example:
5464 // __attribute__((aligned)) struct A;
5465 // Attributes should be placed after tag to apply to type declaration.
5466 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5467 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5468 if (TypeSpecType == DeclSpec::TST_class ||
5469 TypeSpecType == DeclSpec::TST_struct ||
5470 TypeSpecType == DeclSpec::TST_interface ||
5471 TypeSpecType == DeclSpec::TST_union ||
5472 TypeSpecType == DeclSpec::TST_enum) {
5473
5474 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5475 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5476 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5477 DiagnosticId = diag::warn_attribute_ignored;
5478 else if (AL.isRegularKeywordAttribute())
5479 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5480 else
5481 DiagnosticId = diag::warn_declspec_attribute_ignored;
5482 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5483 << AL << GetDiagnosticTypeSpecifierID(DS);
5484 };
5485
5486 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5487 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5488 }
5489 }
5490
5491 return TagD;
5492}
5493
5494/// We are trying to inject an anonymous member into the given scope;
5495/// check if there's an existing declaration that can't be overloaded.
5496///
5497/// \return true if this is a forbidden redeclaration
5498static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5499 DeclContext *Owner,
5500 DeclarationName Name,
5501 SourceLocation NameLoc, bool IsUnion,
5502 StorageClass SC) {
5503 LookupResult R(SemaRef, Name, NameLoc,
5504 Owner->isRecord() ? Sema::LookupMemberName
5505 : Sema::LookupOrdinaryName,
5506 RedeclarationKind::ForVisibleRedeclaration);
5507 if (!SemaRef.LookupName(R, S)) return false;
5508
5509 // Pick a representative declaration.
5510 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5511 assert(PrevDecl && "Expected a non-null Decl");
5512
5513 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5514 return false;
5515
5516 if (SC == StorageClass::SC_None &&
5517 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5518 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5519 if (!Owner->isRecord())
5520 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5521 return false;
5522 }
5523
5524 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5525 << IsUnion << Name;
5526 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5527
5528 return true;
5529}
5530
5531void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5532 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5533 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5534}
5535
5536void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5537 if (!getLangOpts().CPlusPlus)
5538 return;
5539
5540 // This function can be parsed before we have validated the
5541 // structure as an anonymous struct
5542 if (Record->isAnonymousStructOrUnion())
5543 return;
5544
5545 const NamedDecl *First = 0;
5546 for (const Decl *D : Record->decls()) {
5547 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5548 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5549 continue;
5550 if (!First)
5551 First = ND;
5552 else
5553 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5554 }
5555}
5556
5557/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5558/// anonymous struct or union AnonRecord into the owning context Owner
5559/// and scope S. This routine will be invoked just after we realize
5560/// that an unnamed union or struct is actually an anonymous union or
5561/// struct, e.g.,
5562///
5563/// @code
5564/// union {
5565/// int i;
5566/// float f;
5567/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5568/// // f into the surrounding scope.x
5569/// @endcode
5570///
5571/// This routine is recursive, injecting the names of nested anonymous
5572/// structs/unions into the owning context and scope as well.
5573static bool
5574InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5575 RecordDecl *AnonRecord, AccessSpecifier AS,
5576 StorageClass SC,
5577 SmallVectorImpl<NamedDecl *> &Chaining) {
5578 bool Invalid = false;
5579
5580 // Look every FieldDecl and IndirectFieldDecl with a name.
5581 for (auto *D : AnonRecord->decls()) {
5582 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5583 cast<NamedDecl>(Val: D)->getDeclName()) {
5584 ValueDecl *VD = cast<ValueDecl>(Val: D);
5585 // C++ [class.union]p2:
5586 // The names of the members of an anonymous union shall be
5587 // distinct from the names of any other entity in the
5588 // scope in which the anonymous union is declared.
5589
5590 bool FieldInvalid = CheckAnonMemberRedeclaration(
5591 SemaRef, S, Owner, Name: VD->getDeclName(), NameLoc: VD->getLocation(),
5592 IsUnion: AnonRecord->isUnion(), SC);
5593 if (FieldInvalid)
5594 Invalid = true;
5595
5596 // Inject the IndirectFieldDecl even if invalid, because later
5597 // diagnostics may depend on it being present, see findDefaultInitializer.
5598
5599 // C++ [class.union]p2:
5600 // For the purpose of name lookup, after the anonymous union
5601 // definition, the members of the anonymous union are
5602 // considered to have been defined in the scope in which the
5603 // anonymous union is declared.
5604 unsigned OldChainingSize = Chaining.size();
5605 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5606 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5607 else
5608 Chaining.push_back(Elt: VD);
5609
5610 assert(Chaining.size() >= 2);
5611 NamedDecl **NamedChain =
5612 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5613 for (unsigned i = 0; i < Chaining.size(); i++)
5614 NamedChain[i] = Chaining[i];
5615
5616 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5617 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5618 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5619
5620 for (const auto *Attr : VD->attrs())
5621 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5622
5623 IndirectField->setAccess(AS);
5624 IndirectField->setImplicit();
5625 IndirectField->setInvalidDecl(FieldInvalid);
5626 SemaRef.PushOnScopeChains(D: IndirectField, S);
5627
5628 // That includes picking up the appropriate access specifier.
5629 if (AS != AS_none)
5630 IndirectField->setAccess(AS);
5631
5632 Chaining.resize(N: OldChainingSize);
5633 }
5634 }
5635
5636 return Invalid;
5637}
5638
5639/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5640/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5641/// illegal input values are mapped to SC_None.
5642static StorageClass
5643StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5644 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5645 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5646 "Parser allowed 'typedef' as storage class VarDecl.");
5647 switch (StorageClassSpec) {
5648 case DeclSpec::SCS_unspecified: return SC_None;
5649 case DeclSpec::SCS_extern:
5650 if (DS.isExternInLinkageSpec())
5651 return SC_None;
5652 return SC_Extern;
5653 case DeclSpec::SCS_static: return SC_Static;
5654 case DeclSpec::SCS_auto: return SC_Auto;
5655 case DeclSpec::SCS_register: return SC_Register;
5656 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5657 // Illegal SCSs map to None: error reporting is up to the caller.
5658 case DeclSpec::SCS_mutable: // Fall through.
5659 case DeclSpec::SCS_typedef: return SC_None;
5660 }
5661 llvm_unreachable("unknown storage class specifier");
5662}
5663
5664static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5665 assert(Record->hasInClassInitializer());
5666
5667 for (const auto *I : Record->decls()) {
5668 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5669 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5670 FD = IFD->getAnonField();
5671 if (FD && FD->hasInClassInitializer())
5672 return FD->getLocation();
5673 }
5674
5675 llvm_unreachable("couldn't find in-class initializer");
5676}
5677
5678static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5679 SourceLocation DefaultInitLoc) {
5680 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5681 return;
5682
5683 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5684 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5685}
5686
5687static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5688 CXXRecordDecl *AnonUnion) {
5689 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5690 return;
5691
5692 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5693}
5694
5695Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5696 AccessSpecifier AS,
5697 RecordDecl *Record,
5698 const PrintingPolicy &Policy) {
5699 DeclContext *Owner = Record->getDeclContext();
5700
5701 // Diagnose whether this anonymous struct/union is an extension.
5702 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5703 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5704 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5705 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5706 else if (!Record->isUnion() && !getLangOpts().C11)
5707 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5708
5709 // C and C++ require different kinds of checks for anonymous
5710 // structs/unions.
5711 bool Invalid = false;
5712 if (getLangOpts().CPlusPlus) {
5713 const char *PrevSpec = nullptr;
5714 if (Record->isUnion()) {
5715 // C++ [class.union]p6:
5716 // C++17 [class.union.anon]p2:
5717 // Anonymous unions declared in a named namespace or in the
5718 // global namespace shall be declared static.
5719 unsigned DiagID;
5720 DeclContext *OwnerScope = Owner->getRedeclContext();
5721 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5722 (OwnerScope->isTranslationUnit() ||
5723 (OwnerScope->isNamespace() &&
5724 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5725 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5726 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5727
5728 // Recover by adding 'static'.
5729 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5730 PrevSpec, DiagID, Policy);
5731 }
5732 // C++ [class.union]p6:
5733 // A storage class is not allowed in a declaration of an
5734 // anonymous union in a class scope.
5735 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5736 isa<RecordDecl>(Val: Owner)) {
5737 Diag(Loc: DS.getStorageClassSpecLoc(),
5738 DiagID: diag::err_anonymous_union_with_storage_spec)
5739 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5740
5741 // Recover by removing the storage specifier.
5742 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5743 Loc: SourceLocation(),
5744 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5745 }
5746 }
5747
5748 // Ignore const/volatile/restrict qualifiers.
5749 if (DS.getTypeQualifiers()) {
5750 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5751 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5752 << Record->isUnion() << "const"
5753 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5754 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5755 Diag(Loc: DS.getVolatileSpecLoc(),
5756 DiagID: diag::ext_anonymous_struct_union_qualified)
5757 << Record->isUnion() << "volatile"
5758 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5759 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5760 Diag(Loc: DS.getRestrictSpecLoc(),
5761 DiagID: diag::ext_anonymous_struct_union_qualified)
5762 << Record->isUnion() << "restrict"
5763 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5764 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5765 Diag(Loc: DS.getAtomicSpecLoc(),
5766 DiagID: diag::ext_anonymous_struct_union_qualified)
5767 << Record->isUnion() << "_Atomic"
5768 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5769 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5770 Diag(Loc: DS.getUnalignedSpecLoc(),
5771 DiagID: diag::ext_anonymous_struct_union_qualified)
5772 << Record->isUnion() << "__unaligned"
5773 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5774
5775 DS.ClearTypeQualifiers();
5776 }
5777
5778 // C++ [class.union]p2:
5779 // The member-specification of an anonymous union shall only
5780 // define non-static data members. [Note: nested types and
5781 // functions cannot be declared within an anonymous union. ]
5782 for (auto *Mem : Record->decls()) {
5783 // Ignore invalid declarations; we already diagnosed them.
5784 if (Mem->isInvalidDecl())
5785 continue;
5786
5787 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5788 // C++ [class.union]p3:
5789 // An anonymous union shall not have private or protected
5790 // members (clause 11).
5791 assert(FD->getAccess() != AS_none);
5792 if (FD->getAccess() != AS_public) {
5793 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5794 << Record->isUnion() << (FD->getAccess() == AS_protected);
5795 Invalid = true;
5796 }
5797
5798 // C++ [class.union]p1
5799 // An object of a class with a non-trivial constructor, a non-trivial
5800 // copy constructor, a non-trivial destructor, or a non-trivial copy
5801 // assignment operator cannot be a member of a union, nor can an
5802 // array of such objects.
5803 if (CheckNontrivialField(FD))
5804 Invalid = true;
5805 } else if (Mem->isImplicit()) {
5806 // Any implicit members are fine.
5807 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5808 // This is a type that showed up in an
5809 // elaborated-type-specifier inside the anonymous struct or
5810 // union, but which actually declares a type outside of the
5811 // anonymous struct or union. It's okay.
5812 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5813 if (!MemRecord->isAnonymousStructOrUnion() &&
5814 MemRecord->getDeclName()) {
5815 // Visual C++ allows type definition in anonymous struct or union.
5816 if (getLangOpts().MicrosoftExt)
5817 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5818 << Record->isUnion();
5819 else {
5820 // This is a nested type declaration.
5821 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5822 << Record->isUnion();
5823 Invalid = true;
5824 }
5825 } else {
5826 // This is an anonymous type definition within another anonymous type.
5827 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5828 // not part of standard C++.
5829 Diag(Loc: MemRecord->getLocation(),
5830 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5831 << Record->isUnion();
5832 }
5833 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5834 // Any access specifier is fine.
5835 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5836 // In C++1z, static_assert declarations are also fine.
5837 } else {
5838 // We have something that isn't a non-static data
5839 // member. Complain about it.
5840 unsigned DK = diag::err_anonymous_record_bad_member;
5841 if (isa<TypeDecl>(Val: Mem))
5842 DK = diag::err_anonymous_record_with_type;
5843 else if (isa<FunctionDecl>(Val: Mem))
5844 DK = diag::err_anonymous_record_with_function;
5845 else if (isa<VarDecl>(Val: Mem))
5846 DK = diag::err_anonymous_record_with_static;
5847
5848 // Visual C++ allows type definition in anonymous struct or union.
5849 if (getLangOpts().MicrosoftExt &&
5850 DK == diag::err_anonymous_record_with_type)
5851 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5852 << Record->isUnion();
5853 else {
5854 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5855 Invalid = true;
5856 }
5857 }
5858 }
5859
5860 // C++11 [class.union]p8 (DR1460):
5861 // At most one variant member of a union may have a
5862 // brace-or-equal-initializer.
5863 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5864 Owner->isRecord())
5865 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5866 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5867 }
5868
5869 if (!Record->isUnion() && !Owner->isRecord()) {
5870 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5871 << getLangOpts().CPlusPlus;
5872 Invalid = true;
5873 }
5874
5875 // C++ [dcl.dcl]p3:
5876 // [If there are no declarators], and except for the declaration of an
5877 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5878 // names into the program
5879 // C++ [class.mem]p2:
5880 // each such member-declaration shall either declare at least one member
5881 // name of the class or declare at least one unnamed bit-field
5882 //
5883 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5884 if (getLangOpts().CPlusPlus && Record->field_empty())
5885 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5886
5887 // Mock up a declarator.
5888 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5889 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5890 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5891 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5892
5893 // Create a declaration for this anonymous struct/union.
5894 NamedDecl *Anon = nullptr;
5895 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5896 Anon = FieldDecl::Create(
5897 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5898 /*IdentifierInfo=*/Id: nullptr, T: Context.getCanonicalTagType(TD: Record), TInfo,
5899 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5900 /*InitStyle=*/ICIS_NoInit);
5901 Anon->setAccess(AS);
5902 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5903
5904 if (getLangOpts().CPlusPlus)
5905 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5906 } else {
5907 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5908 if (SCSpec == DeclSpec::SCS_mutable) {
5909 // mutable can only appear on non-static class members, so it's always
5910 // an error here
5911 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
5912 Invalid = true;
5913 SC = SC_None;
5914 }
5915
5916 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5917 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5918 T: Context.getCanonicalTagType(TD: Record), TInfo, S: SC);
5919 if (Invalid)
5920 Anon->setInvalidDecl();
5921
5922 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5923
5924 // Default-initialize the implicit variable. This initialization will be
5925 // trivial in almost all cases, except if a union member has an in-class
5926 // initializer:
5927 // union { int n = 0; };
5928 ActOnUninitializedDecl(dcl: Anon);
5929 }
5930 Anon->setImplicit();
5931
5932 // Mark this as an anonymous struct/union type.
5933 Record->setAnonymousStructOrUnion(true);
5934
5935 // Add the anonymous struct/union object to the current
5936 // context. We'll be referencing this object when we refer to one of
5937 // its members.
5938 Owner->addDecl(D: Anon);
5939
5940 // Inject the members of the anonymous struct/union into the owning
5941 // context and into the identifier resolver chain for name lookup
5942 // purposes.
5943 SmallVector<NamedDecl*, 2> Chain;
5944 Chain.push_back(Elt: Anon);
5945
5946 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
5947 Chaining&: Chain))
5948 Invalid = true;
5949
5950 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
5951 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5952 MangleNumberingContext *MCtx;
5953 Decl *ManglingContextDecl;
5954 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5955 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
5956 if (MCtx) {
5957 Context.setManglingNumber(
5958 ND: NewVD, Number: MCtx->getManglingNumber(
5959 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
5960 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
5961 }
5962 }
5963 }
5964
5965 if (Invalid)
5966 Anon->setInvalidDecl();
5967
5968 return Anon;
5969}
5970
5971Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5972 RecordDecl *Record) {
5973 assert(Record && "expected a record!");
5974
5975 // Mock up a declarator.
5976 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5977 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5978 assert(TInfo && "couldn't build declarator info for anonymous struct");
5979
5980 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
5981 CanQualType RecTy = Context.getCanonicalTagType(TD: Record);
5982
5983 // Create a declaration for this anonymous struct.
5984 NamedDecl *Anon =
5985 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
5986 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
5987 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5988 /*InitStyle=*/ICIS_NoInit);
5989 Anon->setImplicit();
5990
5991 // Add the anonymous struct object to the current context.
5992 CurContext->addDecl(D: Anon);
5993
5994 // Inject the members of the anonymous struct into the current
5995 // context and into the identifier resolver chain for name lookup
5996 // purposes.
5997 SmallVector<NamedDecl*, 2> Chain;
5998 Chain.push_back(Elt: Anon);
5999
6000 RecordDecl *RecordDef = Record->getDefinition();
6001 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
6002 DiagID: diag::err_field_incomplete_or_sizeless) ||
6003 InjectAnonymousStructOrUnionMembers(
6004 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
6005 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
6006 Anon->setInvalidDecl();
6007 ParentDecl->setInvalidDecl();
6008 }
6009
6010 return Anon;
6011}
6012
6013DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
6014 return GetNameFromUnqualifiedId(Name: D.getName());
6015}
6016
6017DeclarationNameInfo
6018Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
6019 DeclarationNameInfo NameInfo;
6020 NameInfo.setLoc(Name.StartLocation);
6021
6022 switch (Name.getKind()) {
6023
6024 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6025 case UnqualifiedIdKind::IK_Identifier:
6026 NameInfo.setName(Name.Identifier);
6027 return NameInfo;
6028
6029 case UnqualifiedIdKind::IK_DeductionGuideName: {
6030 // C++ [temp.deduct.guide]p3:
6031 // The simple-template-id shall name a class template specialization.
6032 // The template-name shall be the same identifier as the template-name
6033 // of the simple-template-id.
6034 // These together intend to imply that the template-name shall name a
6035 // class template.
6036 // FIXME: template<typename T> struct X {};
6037 // template<typename T> using Y = X<T>;
6038 // Y(int) -> Y<int>;
6039 // satisfies these rules but does not name a class template.
6040 TemplateName TN = Name.TemplateName.get().get();
6041 auto *Template = TN.getAsTemplateDecl();
6042 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
6043 Diag(Loc: Name.StartLocation,
6044 DiagID: diag::err_deduction_guide_name_not_class_template)
6045 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
6046 if (Template)
6047 NoteTemplateLocation(Decl: *Template);
6048 return DeclarationNameInfo();
6049 }
6050
6051 NameInfo.setName(
6052 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
6053 return NameInfo;
6054 }
6055
6056 case UnqualifiedIdKind::IK_OperatorFunctionId:
6057 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6058 Op: Name.OperatorFunctionId.Operator));
6059 NameInfo.setCXXOperatorNameRange(SourceRange(
6060 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6061 return NameInfo;
6062
6063 case UnqualifiedIdKind::IK_LiteralOperatorId:
6064 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6065 II: Name.Identifier));
6066 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6067 return NameInfo;
6068
6069 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6070 TypeSourceInfo *TInfo;
6071 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
6072 if (Ty.isNull())
6073 return DeclarationNameInfo();
6074 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6075 Ty: Context.getCanonicalType(T: Ty)));
6076 NameInfo.setNamedTypeInfo(TInfo);
6077 return NameInfo;
6078 }
6079
6080 case UnqualifiedIdKind::IK_ConstructorName: {
6081 TypeSourceInfo *TInfo;
6082 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
6083 if (Ty.isNull())
6084 return DeclarationNameInfo();
6085 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6086 Ty: Context.getCanonicalType(T: Ty)));
6087 NameInfo.setNamedTypeInfo(TInfo);
6088 return NameInfo;
6089 }
6090
6091 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6092 // In well-formed code, we can only have a constructor
6093 // template-id that refers to the current context, so go there
6094 // to find the actual type being constructed.
6095 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
6096 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6097 return DeclarationNameInfo();
6098
6099 // Determine the type of the class being constructed.
6100 CanQualType CurClassType = Context.getCanonicalTagType(TD: CurClass);
6101
6102 // FIXME: Check two things: that the template-id names the same type as
6103 // CurClassType, and that the template-id does not occur when the name
6104 // was qualified.
6105
6106 NameInfo.setName(
6107 Context.DeclarationNames.getCXXConstructorName(Ty: CurClassType));
6108 // FIXME: should we retrieve TypeSourceInfo?
6109 NameInfo.setNamedTypeInfo(nullptr);
6110 return NameInfo;
6111 }
6112
6113 case UnqualifiedIdKind::IK_DestructorName: {
6114 TypeSourceInfo *TInfo;
6115 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6116 if (Ty.isNull())
6117 return DeclarationNameInfo();
6118 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6119 Ty: Context.getCanonicalType(T: Ty)));
6120 NameInfo.setNamedTypeInfo(TInfo);
6121 return NameInfo;
6122 }
6123
6124 case UnqualifiedIdKind::IK_TemplateId: {
6125 TemplateName TName = Name.TemplateId->Template.get();
6126 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6127 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6128 }
6129
6130 } // switch (Name.getKind())
6131
6132 llvm_unreachable("Unknown name kind");
6133}
6134
6135static QualType getCoreType(QualType Ty) {
6136 do {
6137 if (Ty->isPointerOrReferenceType())
6138 Ty = Ty->getPointeeType();
6139 else if (Ty->isArrayType())
6140 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6141 else
6142 return Ty.withoutLocalFastQualifiers();
6143 } while (true);
6144}
6145
6146/// hasSimilarParameters - Determine whether the C++ functions Declaration
6147/// and Definition have "nearly" matching parameters. This heuristic is
6148/// used to improve diagnostics in the case where an out-of-line function
6149/// definition doesn't match any declaration within the class or namespace.
6150/// Also sets Params to the list of indices to the parameters that differ
6151/// between the declaration and the definition. If hasSimilarParameters
6152/// returns true and Params is empty, then all of the parameters match.
6153static bool hasSimilarParameters(ASTContext &Context,
6154 FunctionDecl *Declaration,
6155 FunctionDecl *Definition,
6156 SmallVectorImpl<unsigned> &Params) {
6157 Params.clear();
6158 if (Declaration->param_size() != Definition->param_size())
6159 return false;
6160 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6161 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6162 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6163
6164 // The parameter types are identical
6165 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6166 continue;
6167
6168 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6169 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6170 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6171 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6172
6173 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6174 (DeclTyName && DeclTyName == DefTyName))
6175 Params.push_back(Elt: Idx);
6176 else // The two parameters aren't even close
6177 return false;
6178 }
6179
6180 return true;
6181}
6182
6183/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6184/// declarator needs to be rebuilt in the current instantiation.
6185/// Any bits of declarator which appear before the name are valid for
6186/// consideration here. That's specifically the type in the decl spec
6187/// and the base type in any member-pointer chunks.
6188static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6189 DeclarationName Name) {
6190 // The types we specifically need to rebuild are:
6191 // - typenames, typeofs, and decltypes
6192 // - types which will become injected class names
6193 // Of course, we also need to rebuild any type referencing such a
6194 // type. It's safest to just say "dependent", but we call out a
6195 // few cases here.
6196
6197 DeclSpec &DS = D.getMutableDeclSpec();
6198 switch (DS.getTypeSpecType()) {
6199 case DeclSpec::TST_typename:
6200 case DeclSpec::TST_typeofType:
6201 case DeclSpec::TST_typeof_unqualType:
6202#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6203#include "clang/Basic/TransformTypeTraits.def"
6204 case DeclSpec::TST_atomic: {
6205 // Grab the type from the parser.
6206 TypeSourceInfo *TSI = nullptr;
6207 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6208 if (T.isNull() || !T->isInstantiationDependentType()) break;
6209
6210 // Make sure there's a type source info. This isn't really much
6211 // of a waste; most dependent types should have type source info
6212 // attached already.
6213 if (!TSI)
6214 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6215
6216 // Rebuild the type in the current instantiation.
6217 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6218 if (!TSI) return true;
6219
6220 // Store the new type back in the decl spec.
6221 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6222 DS.UpdateTypeRep(Rep: LocType);
6223 break;
6224 }
6225
6226 case DeclSpec::TST_decltype:
6227 case DeclSpec::TST_typeof_unqualExpr:
6228 case DeclSpec::TST_typeofExpr: {
6229 Expr *E = DS.getRepAsExpr();
6230 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6231 if (Result.isInvalid()) return true;
6232 DS.UpdateExprRep(Rep: Result.get());
6233 break;
6234 }
6235
6236 default:
6237 // Nothing to do for these decl specs.
6238 break;
6239 }
6240
6241 // It doesn't matter what order we do this in.
6242 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6243 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6244
6245 // The only type information in the declarator which can come
6246 // before the declaration name is the base type of a member
6247 // pointer.
6248 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6249 continue;
6250
6251 // Rebuild the scope specifier in-place.
6252 CXXScopeSpec &SS = Chunk.Mem.Scope();
6253 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6254 return true;
6255 }
6256
6257 return false;
6258}
6259
6260/// Returns true if the declaration is declared in a system header or from a
6261/// system macro.
6262static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6263 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6264 SM.isInSystemMacro(loc: D->getLocation());
6265}
6266
6267void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6268 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6269 // of system decl.
6270 if (D->getPreviousDecl() || D->isImplicit())
6271 return;
6272 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6273 if (Status != ReservedIdentifierStatus::NotReserved &&
6274 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6275 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6276 << D << static_cast<int>(Status);
6277 }
6278}
6279
6280Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6281 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6282
6283 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6284 // declaration only if the `bind_to_declaration` extension is set.
6285 SmallVector<FunctionDecl *, 4> Bases;
6286 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6287 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6288 TP: llvm::omp::TraitProperty::
6289 implementation_extension_bind_to_declaration))
6290 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6291 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6292
6293 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6294
6295 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6296 Dcl && Dcl->getDeclContext()->isFileContext())
6297 Dcl->setTopLevelDeclInObjCContainer();
6298
6299 if (!Bases.empty())
6300 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6301 Bases);
6302
6303 return Dcl;
6304}
6305
6306bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6307 DeclarationNameInfo NameInfo) {
6308 DeclarationName Name = NameInfo.getName();
6309
6310 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6311 while (Record && Record->isAnonymousStructOrUnion())
6312 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6313 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6314 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6315 return true;
6316 }
6317
6318 return false;
6319}
6320
6321bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6322 DeclarationName Name,
6323 SourceLocation Loc,
6324 TemplateIdAnnotation *TemplateId,
6325 bool IsMemberSpecialization) {
6326 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6327 "without nested-name-specifier");
6328 DeclContext *Cur = CurContext;
6329 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6330 Cur = Cur->getParent();
6331
6332 // If the user provided a superfluous scope specifier that refers back to the
6333 // class in which the entity is already declared, diagnose and ignore it.
6334 //
6335 // class X {
6336 // void X::f();
6337 // };
6338 //
6339 // Note, it was once ill-formed to give redundant qualification in all
6340 // contexts, but that rule was removed by DR482.
6341 if (Cur->Equals(DC)) {
6342 if (Cur->isRecord()) {
6343 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6344 : diag::err_member_extra_qualification)
6345 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6346 SS.clear();
6347 } else {
6348 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6349 }
6350 return false;
6351 }
6352
6353 // Check whether the qualifying scope encloses the scope of the original
6354 // declaration. For a template-id, we perform the checks in
6355 // CheckTemplateSpecializationScope.
6356 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6357 if (Cur->isRecord())
6358 Diag(Loc, DiagID: diag::err_member_qualification)
6359 << Name << SS.getRange();
6360 else if (isa<TranslationUnitDecl>(Val: DC))
6361 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6362 << Name << SS.getRange();
6363 else if (isa<FunctionDecl>(Val: Cur))
6364 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6365 << Name << SS.getRange();
6366 else if (isa<BlockDecl>(Val: Cur))
6367 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6368 << Name << SS.getRange();
6369 else if (isa<ExportDecl>(Val: Cur)) {
6370 if (!isa<NamespaceDecl>(Val: DC))
6371 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6372 << Name << SS.getRange();
6373 else
6374 // The cases that DC is not NamespaceDecl should be handled in
6375 // CheckRedeclarationExported.
6376 return false;
6377 } else
6378 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6379 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6380
6381 return true;
6382 }
6383
6384 if (Cur->isRecord()) {
6385 // Cannot qualify members within a class.
6386 Diag(Loc, DiagID: diag::err_member_qualification)
6387 << Name << SS.getRange();
6388 SS.clear();
6389
6390 // C++ constructors and destructors with incorrect scopes can break
6391 // our AST invariants by having the wrong underlying types. If
6392 // that's the case, then drop this declaration entirely.
6393 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6394 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6395 !Context.hasSameType(
6396 T1: Name.getCXXNameType(),
6397 T2: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: Cur))))
6398 return true;
6399
6400 return false;
6401 }
6402
6403 // C++23 [temp.names]p5:
6404 // The keyword template shall not appear immediately after a declarative
6405 // nested-name-specifier.
6406 //
6407 // First check the template-id (if any), and then check each component of the
6408 // nested-name-specifier in reverse order.
6409 //
6410 // FIXME: nested-name-specifiers in friend declarations are declarative,
6411 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6412 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6413 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6414 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6415
6416 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6417 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6418 TL = std::exchange(obj&: NextTL, new_val: TypeLoc())) {
6419 SourceLocation TemplateKeywordLoc;
6420 switch (TL.getTypeLocClass()) {
6421 case TypeLoc::TemplateSpecialization: {
6422 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6423 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6424 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6425 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6426 << TST.getLocalSourceRange();
6427 break;
6428 }
6429 case TypeLoc::Decltype:
6430 case TypeLoc::PackIndexing: {
6431 const Type *T = TL.getTypePtr();
6432 // C++23 [expr.prim.id.qual]p2:
6433 // [...] A declarative nested-name-specifier shall not have a
6434 // computed-type-specifier.
6435 //
6436 // CWG2858 changed this from 'decltype-specifier' to
6437 // 'computed-type-specifier'.
6438 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6439 << T->isDecltypeType() << TL.getSourceRange();
6440 break;
6441 }
6442 case TypeLoc::DependentName:
6443 NextTL =
6444 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6445 break;
6446 default:
6447 break;
6448 }
6449 if (TemplateKeywordLoc.isValid())
6450 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6451 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6452 }
6453
6454 return false;
6455}
6456
6457NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6458 MultiTemplateParamsArg TemplateParamLists) {
6459 // TODO: consider using NameInfo for diagnostic.
6460 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6461 DeclarationName Name = NameInfo.getName();
6462
6463 // All of these full declarators require an identifier. If it doesn't have
6464 // one, the ParsedFreeStandingDeclSpec action should be used.
6465 if (D.isDecompositionDeclarator()) {
6466 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6467 } else if (!Name) {
6468 if (!D.isInvalidType()) // Reject this if we think it is valid.
6469 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6470 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6471 return nullptr;
6472 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6473 return nullptr;
6474
6475 DeclContext *DC = CurContext;
6476 if (D.getCXXScopeSpec().isInvalid())
6477 D.setInvalidType();
6478 else if (D.getCXXScopeSpec().isSet()) {
6479 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6480 UPPC: UPPC_DeclarationQualifier))
6481 return nullptr;
6482
6483 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6484 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6485 if (!DC || isa<EnumDecl>(Val: DC)) {
6486 // If we could not compute the declaration context, it's because the
6487 // declaration context is dependent but does not refer to a class,
6488 // class template, or class template partial specialization. Complain
6489 // and return early, to avoid the coming semantic disaster.
6490 Diag(Loc: D.getIdentifierLoc(),
6491 DiagID: diag::err_template_qualified_declarator_no_match)
6492 << D.getCXXScopeSpec().getScopeRep()
6493 << D.getCXXScopeSpec().getRange();
6494 return nullptr;
6495 }
6496 bool IsDependentContext = DC->isDependentContext();
6497
6498 if (!IsDependentContext &&
6499 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6500 return nullptr;
6501
6502 // If a class is incomplete, do not parse entities inside it.
6503 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6504 Diag(Loc: D.getIdentifierLoc(),
6505 DiagID: diag::err_member_def_undefined_record)
6506 << Name << DC << D.getCXXScopeSpec().getRange();
6507 return nullptr;
6508 }
6509 if (!D.getDeclSpec().isFriendSpecified()) {
6510 TemplateIdAnnotation *TemplateId =
6511 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6512 ? D.getName().TemplateId
6513 : nullptr;
6514 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6515 Loc: D.getIdentifierLoc(), TemplateId,
6516 /*IsMemberSpecialization=*/false)) {
6517 if (DC->isRecord())
6518 return nullptr;
6519
6520 D.setInvalidType();
6521 }
6522 }
6523
6524 // Check whether we need to rebuild the type of the given
6525 // declaration in the current instantiation.
6526 if (EnteringContext && IsDependentContext &&
6527 TemplateParamLists.size() != 0) {
6528 ContextRAII SavedContext(*this, DC);
6529 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6530 D.setInvalidType();
6531 }
6532 }
6533
6534 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6535 QualType R = TInfo->getType();
6536
6537 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6538 UPPC: UPPC_DeclarationType))
6539 D.setInvalidType();
6540
6541 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6542 forRedeclarationInCurContext());
6543
6544 // See if this is a redefinition of a variable in the same scope.
6545 if (!D.getCXXScopeSpec().isSet()) {
6546 bool IsLinkageLookup = false;
6547 bool CreateBuiltins = false;
6548
6549 // If the declaration we're planning to build will be a function
6550 // or object with linkage, then look for another declaration with
6551 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6552 //
6553 // If the declaration we're planning to build will be declared with
6554 // external linkage in the translation unit, create any builtin with
6555 // the same name.
6556 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6557 /* Do nothing*/;
6558 else if (CurContext->isFunctionOrMethod() &&
6559 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6560 R->isFunctionType())) {
6561 IsLinkageLookup = true;
6562 CreateBuiltins =
6563 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6564 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6565 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6566 CreateBuiltins = true;
6567
6568 if (IsLinkageLookup) {
6569 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6570 Previous.setRedeclarationKind(
6571 RedeclarationKind::ForExternalRedeclaration);
6572 }
6573
6574 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6575 } else { // Something like "int foo::x;"
6576 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6577
6578 // C++ [dcl.meaning]p1:
6579 // When the declarator-id is qualified, the declaration shall refer to a
6580 // previously declared member of the class or namespace to which the
6581 // qualifier refers (or, in the case of a namespace, of an element of the
6582 // inline namespace set of that namespace (7.3.1)) or to a specialization
6583 // thereof; [...]
6584 //
6585 // Note that we already checked the context above, and that we do not have
6586 // enough information to make sure that Previous contains the declaration
6587 // we want to match. For example, given:
6588 //
6589 // class X {
6590 // void f();
6591 // void f(float);
6592 // };
6593 //
6594 // void X::f(int) { } // ill-formed
6595 //
6596 // In this case, Previous will point to the overload set
6597 // containing the two f's declared in X, but neither of them
6598 // matches.
6599
6600 RemoveUsingDecls(R&: Previous);
6601 }
6602
6603 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6604 TPD && TPD->isTemplateParameter()) {
6605 // Older versions of clang allowed the names of function/variable templates
6606 // to shadow the names of their template parameters. For the compatibility
6607 // purposes we detect such cases and issue a default-to-error warning that
6608 // can be disabled with -Wno-strict-primary-template-shadow.
6609 if (!D.isInvalidType()) {
6610 bool AllowForCompatibility = false;
6611 if (Scope *DeclParent = S->getDeclParent();
6612 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6613 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6614 TemplateParamParent->isDeclScope(D: TPD);
6615 }
6616 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6617 SupportedForCompatibility: AllowForCompatibility);
6618 }
6619
6620 // Just pretend that we didn't see the previous declaration.
6621 Previous.clear();
6622 }
6623
6624 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6625 // Forget that the previous declaration is the injected-class-name.
6626 Previous.clear();
6627
6628 // In C++, the previous declaration we find might be a tag type
6629 // (class or enum). In this case, the new declaration will hide the
6630 // tag type. Note that this applies to functions, function templates, and
6631 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6632 if (Previous.isSingleTagDecl() &&
6633 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6634 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6635 Previous.clear();
6636
6637 // Check that there are no default arguments other than in the parameters
6638 // of a function declaration (C++ only).
6639 if (getLangOpts().CPlusPlus)
6640 CheckExtraCXXDefaultArguments(D);
6641
6642 /// Get the innermost enclosing declaration scope.
6643 S = S->getDeclParent();
6644
6645 NamedDecl *New;
6646
6647 bool AddToScope = true;
6648 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6649 if (TemplateParamLists.size()) {
6650 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6651 return nullptr;
6652 }
6653
6654 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6655 } else if (R->isFunctionType()) {
6656 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6657 TemplateParamLists,
6658 AddToScope);
6659 } else {
6660 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6661 AddToScope);
6662 }
6663
6664 if (!New)
6665 return nullptr;
6666
6667 warnOnCTypeHiddenInCPlusPlus(D: New);
6668
6669 // If this has an identifier and is not a function template specialization,
6670 // add it to the scope stack.
6671 if (New->getDeclName() && AddToScope)
6672 PushOnScopeChains(D: New, S);
6673
6674 if (OpenMP().isInOpenMPDeclareTargetContext())
6675 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6676
6677 return New;
6678}
6679
6680/// Helper method to turn variable array types into constant array
6681/// types in certain situations which would otherwise be errors (for
6682/// GCC compatibility).
6683static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6684 ASTContext &Context,
6685 bool &SizeIsNegative,
6686 llvm::APSInt &Oversized) {
6687 // This method tries to turn a variable array into a constant
6688 // array even when the size isn't an ICE. This is necessary
6689 // for compatibility with code that depends on gcc's buggy
6690 // constant expression folding, like struct {char x[(int)(char*)2];}
6691 SizeIsNegative = false;
6692 Oversized = 0;
6693
6694 if (T->isDependentType())
6695 return QualType();
6696
6697 QualifierCollector Qs;
6698 const Type *Ty = Qs.strip(type: T);
6699
6700 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6701 QualType Pointee = PTy->getPointeeType();
6702 QualType FixedType =
6703 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6704 Oversized);
6705 if (FixedType.isNull()) return FixedType;
6706 FixedType = Context.getPointerType(T: FixedType);
6707 return Qs.apply(Context, QT: FixedType);
6708 }
6709 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6710 QualType Inner = PTy->getInnerType();
6711 QualType FixedType =
6712 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6713 Oversized);
6714 if (FixedType.isNull()) return FixedType;
6715 FixedType = Context.getParenType(NamedType: FixedType);
6716 return Qs.apply(Context, QT: FixedType);
6717 }
6718
6719 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6720 if (!VLATy)
6721 return QualType();
6722
6723 QualType ElemTy = VLATy->getElementType();
6724 if (ElemTy->isVariablyModifiedType()) {
6725 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6726 SizeIsNegative, Oversized);
6727 if (ElemTy.isNull())
6728 return QualType();
6729 }
6730
6731 Expr::EvalResult Result;
6732 if (!VLATy->getSizeExpr() ||
6733 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6734 return QualType();
6735
6736 llvm::APSInt Res = Result.Val.getInt();
6737
6738 // Check whether the array size is negative.
6739 if (Res.isSigned() && Res.isNegative()) {
6740 SizeIsNegative = true;
6741 return QualType();
6742 }
6743
6744 // Check whether the array is too large to be addressed.
6745 unsigned ActiveSizeBits =
6746 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6747 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6748 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6749 : Res.getActiveBits();
6750 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6751 Oversized = std::move(Res);
6752 return QualType();
6753 }
6754
6755 QualType FoldedArrayType = Context.getConstantArrayType(
6756 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6757 return Qs.apply(Context, QT: FoldedArrayType);
6758}
6759
6760static void
6761FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6762 SrcTL = SrcTL.getUnqualifiedLoc();
6763 DstTL = DstTL.getUnqualifiedLoc();
6764 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6765 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6766 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6767 DstTL: DstPTL.getPointeeLoc());
6768 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6769 return;
6770 }
6771 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6772 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6773 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6774 DstTL: DstPTL.getInnerLoc());
6775 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6776 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6777 return;
6778 }
6779 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6780 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6781 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6782 TypeLoc DstElemTL = DstATL.getElementLoc();
6783 if (VariableArrayTypeLoc SrcElemATL =
6784 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6785 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6786 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6787 } else {
6788 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6789 }
6790 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6791 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6792 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6793}
6794
6795/// Helper method to turn variable array types into constant array
6796/// types in certain situations which would otherwise be errors (for
6797/// GCC compatibility).
6798static TypeSourceInfo*
6799TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6800 ASTContext &Context,
6801 bool &SizeIsNegative,
6802 llvm::APSInt &Oversized) {
6803 QualType FixedTy
6804 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6805 SizeIsNegative, Oversized);
6806 if (FixedTy.isNull())
6807 return nullptr;
6808 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6809 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6810 DstTL: FixedTInfo->getTypeLoc());
6811 return FixedTInfo;
6812}
6813
6814bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6815 QualType &T, SourceLocation Loc,
6816 unsigned FailedFoldDiagID) {
6817 bool SizeIsNegative;
6818 llvm::APSInt Oversized;
6819 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6820 TInfo, Context, SizeIsNegative, Oversized);
6821 if (FixedTInfo) {
6822 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6823 TInfo = FixedTInfo;
6824 T = FixedTInfo->getType();
6825 return true;
6826 }
6827
6828 if (SizeIsNegative)
6829 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6830 else if (Oversized.getBoolValue())
6831 Diag(Loc, DiagID: diag::err_array_too_large) << toString(
6832 I: Oversized, Radix: 10, Signed: Oversized.isSigned(), /*formatAsCLiteral=*/false,
6833 /*UpperCase=*/false, /*InsertSeparators=*/true);
6834 else if (FailedFoldDiagID)
6835 Diag(Loc, DiagID: FailedFoldDiagID);
6836 return false;
6837}
6838
6839void
6840Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6841 if (!getLangOpts().CPlusPlus &&
6842 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6843 // Don't need to track declarations in the TU in C.
6844 return;
6845
6846 // Note that we have a locally-scoped external with this name.
6847 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6848}
6849
6850NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6851 // FIXME: We can have multiple results via __attribute__((overloadable)).
6852 auto Result = Context.getExternCContextDecl()->lookup(Name);
6853 return Result.empty() ? nullptr : *Result.begin();
6854}
6855
6856void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6857 // FIXME: We should probably indicate the identifier in question to avoid
6858 // confusion for constructs like "virtual int a(), b;"
6859 if (DS.isVirtualSpecified())
6860 Diag(Loc: DS.getVirtualSpecLoc(),
6861 DiagID: diag::err_virtual_non_function);
6862
6863 if (DS.hasExplicitSpecifier())
6864 Diag(Loc: DS.getExplicitSpecLoc(),
6865 DiagID: diag::err_explicit_non_function);
6866
6867 if (DS.isNoreturnSpecified())
6868 Diag(Loc: DS.getNoreturnSpecLoc(),
6869 DiagID: diag::err_noreturn_non_function);
6870}
6871
6872NamedDecl*
6873Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6874 TypeSourceInfo *TInfo, LookupResult &Previous) {
6875 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6876 if (D.getCXXScopeSpec().isSet()) {
6877 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6878 << D.getCXXScopeSpec().getRange();
6879 D.setInvalidType();
6880 // Pretend we didn't see the scope specifier.
6881 DC = CurContext;
6882 Previous.clear();
6883 }
6884
6885 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6886
6887 if (D.getDeclSpec().isInlineSpecified())
6888 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6889 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6890 ? diag::warn_ms_inline_non_function
6891 : diag::err_inline_non_function)
6892 << getLangOpts().CPlusPlus17;
6893 if (D.getDeclSpec().hasConstexprSpecifier())
6894 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6895 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6896
6897 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6898 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6899 Diag(Loc: D.getName().StartLocation,
6900 DiagID: diag::err_deduction_guide_invalid_specifier)
6901 << "typedef";
6902 else
6903 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
6904 << D.getName().getSourceRange();
6905 return nullptr;
6906 }
6907
6908 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6909 if (!NewTD) return nullptr;
6910
6911 // Handle attributes prior to checking for duplicates in MergeVarDecl
6912 ProcessDeclAttributes(S, D: NewTD, PD: D);
6913
6914 CheckTypedefForVariablyModifiedType(S, D: NewTD);
6915
6916 bool Redeclaration = D.isRedeclaration();
6917 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
6918 D.setRedeclaration(Redeclaration);
6919 return ND;
6920}
6921
6922void
6923Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6924 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6925 // then it shall have block scope.
6926 // Note that variably modified types must be fixed before merging the decl so
6927 // that redeclarations will match.
6928 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6929 QualType T = TInfo->getType();
6930 if (T->isVariablyModifiedType()) {
6931 setFunctionHasBranchProtectedScope();
6932
6933 if (S->getFnParent() == nullptr) {
6934 bool SizeIsNegative;
6935 llvm::APSInt Oversized;
6936 TypeSourceInfo *FixedTInfo =
6937 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6938 SizeIsNegative,
6939 Oversized);
6940 if (FixedTInfo) {
6941 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
6942 NewTD->setTypeSourceInfo(FixedTInfo);
6943 } else {
6944 if (SizeIsNegative)
6945 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
6946 else if (T->isVariableArrayType())
6947 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
6948 else if (Oversized.getBoolValue())
6949 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
6950 << toString(I: Oversized, Radix: 10);
6951 else
6952 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
6953 NewTD->setInvalidDecl();
6954 }
6955 }
6956 }
6957}
6958
6959NamedDecl*
6960Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6961 LookupResult &Previous, bool &Redeclaration) {
6962
6963 // Find the shadowed declaration before filtering for scope.
6964 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
6965
6966 // Merge the decl with the existing one if appropriate. If the decl is
6967 // in an outer scope, it isn't the same thing.
6968 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
6969 /*AllowInlineNamespace*/false);
6970 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
6971 if (!Previous.empty()) {
6972 Redeclaration = true;
6973 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
6974 } else {
6975 inferGslPointerAttribute(TD: NewTD);
6976 }
6977
6978 if (ShadowedDecl && !Redeclaration)
6979 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
6980
6981 // If this is the C FILE type, notify the AST context.
6982 if (IdentifierInfo *II = NewTD->getIdentifier())
6983 if (!NewTD->isInvalidDecl() &&
6984 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6985 switch (II->getNotableIdentifierID()) {
6986 case tok::NotableIdentifierKind::FILE:
6987 Context.setFILEDecl(NewTD);
6988 break;
6989 case tok::NotableIdentifierKind::jmp_buf:
6990 Context.setjmp_bufDecl(NewTD);
6991 break;
6992 case tok::NotableIdentifierKind::sigjmp_buf:
6993 Context.setsigjmp_bufDecl(NewTD);
6994 break;
6995 case tok::NotableIdentifierKind::ucontext_t:
6996 Context.setucontext_tDecl(NewTD);
6997 break;
6998 case tok::NotableIdentifierKind::float_t:
6999 case tok::NotableIdentifierKind::double_t:
7000 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
7001 break;
7002 default:
7003 break;
7004 }
7005 }
7006
7007 return NewTD;
7008}
7009
7010/// Determines whether the given declaration is an out-of-scope
7011/// previous declaration.
7012///
7013/// This routine should be invoked when name lookup has found a
7014/// previous declaration (PrevDecl) that is not in the scope where a
7015/// new declaration by the same name is being introduced. If the new
7016/// declaration occurs in a local scope, previous declarations with
7017/// linkage may still be considered previous declarations (C99
7018/// 6.2.2p4-5, C++ [basic.link]p6).
7019///
7020/// \param PrevDecl the previous declaration found by name
7021/// lookup
7022///
7023/// \param DC the context in which the new declaration is being
7024/// declared.
7025///
7026/// \returns true if PrevDecl is an out-of-scope previous declaration
7027/// for a new delcaration with the same name.
7028static bool
7029isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7030 ASTContext &Context) {
7031 if (!PrevDecl)
7032 return false;
7033
7034 if (!PrevDecl->hasLinkage())
7035 return false;
7036
7037 if (Context.getLangOpts().CPlusPlus) {
7038 // C++ [basic.link]p6:
7039 // If there is a visible declaration of an entity with linkage
7040 // having the same name and type, ignoring entities declared
7041 // outside the innermost enclosing namespace scope, the block
7042 // scope declaration declares that same entity and receives the
7043 // linkage of the previous declaration.
7044 DeclContext *OuterContext = DC->getRedeclContext();
7045 if (!OuterContext->isFunctionOrMethod())
7046 // This rule only applies to block-scope declarations.
7047 return false;
7048
7049 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7050 if (PrevOuterContext->isRecord())
7051 // We found a member function: ignore it.
7052 return false;
7053
7054 // Find the innermost enclosing namespace for the new and
7055 // previous declarations.
7056 OuterContext = OuterContext->getEnclosingNamespaceContext();
7057 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7058
7059 // The previous declaration is in a different namespace, so it
7060 // isn't the same function.
7061 if (!OuterContext->Equals(DC: PrevOuterContext))
7062 return false;
7063 }
7064
7065 return true;
7066}
7067
7068static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7069 CXXScopeSpec &SS = D.getCXXScopeSpec();
7070 if (!SS.isSet()) return;
7071 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
7072}
7073
7074void Sema::deduceOpenCLAddressSpace(VarDecl *Var) {
7075 QualType Type = Var->getType();
7076 if (Type.hasAddressSpace())
7077 return;
7078 if (Type->isDependentType())
7079 return;
7080 if (Type->isSamplerT() || Type->isVoidType())
7081 return;
7082 LangAS ImplAS = LangAS::opencl_private;
7083 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7084 // __opencl_c_program_scope_global_variables feature, the address space
7085 // for a variable at program scope or a static or extern variable inside
7086 // a function are inferred to be __global.
7087 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7088 Var->hasGlobalStorage())
7089 ImplAS = LangAS::opencl_global;
7090 // If the original type from a decayed type is an array type and that array
7091 // type has no address space yet, deduce it now.
7092 if (auto DT = dyn_cast<DecayedType>(Val&: Type)) {
7093 auto OrigTy = DT->getOriginalType();
7094 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7095 // Add the address space to the original array type and then propagate
7096 // that to the element type through `getAsArrayType`.
7097 OrigTy = Context.getAddrSpaceQualType(T: OrigTy, AddressSpace: ImplAS);
7098 OrigTy = QualType(Context.getAsArrayType(T: OrigTy), 0);
7099 // Re-generate the decayed type.
7100 Type = Context.getDecayedType(T: OrigTy);
7101 }
7102 }
7103 Type = Context.getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
7104 // Apply any qualifiers (including address space) from the array type to
7105 // the element type. This implements C99 6.7.3p8: "If the specification of
7106 // an array type includes any type qualifiers, the element type is so
7107 // qualified, not the array type."
7108 if (Type->isArrayType())
7109 Type = QualType(Context.getAsArrayType(T: Type), 0);
7110 Var->setType(Type);
7111}
7112
7113static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7114 // 'weak' only applies to declarations with external linkage.
7115 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7116 if (!ND.isExternallyVisible()) {
7117 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
7118 ND.dropAttr<WeakAttr>();
7119 }
7120 }
7121}
7122
7123static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7124 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7125 if (ND.isExternallyVisible()) {
7126 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
7127 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7128 }
7129 }
7130}
7131
7132static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7133 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7134 if (VD->hasInit()) {
7135 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7136 assert(VD->isThisDeclarationADefinition() &&
7137 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7138 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
7139 VD->dropAttr<AliasAttr>();
7140 }
7141 }
7142 }
7143}
7144
7145static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7146 // 'selectany' only applies to externally visible variable declarations.
7147 // It does not apply to functions.
7148 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7149 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7150 S.Diag(Loc: Attr->getLocation(),
7151 DiagID: diag::err_attribute_selectany_non_extern_data);
7152 ND.dropAttr<SelectAnyAttr>();
7153 }
7154 }
7155}
7156
7157static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7158 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7159 if (!ND.isExternallyVisible())
7160 S.Diag(Loc: Attr->getLocation(),
7161 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7162 }
7163}
7164
7165static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7166 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7167 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7168 bool IsAnonymousNS = false;
7169 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7170 if (VD) {
7171 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7172 while (NS && !IsAnonymousNS) {
7173 IsAnonymousNS = NS->isAnonymousNamespace();
7174 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7175 }
7176 }
7177 // dll attributes require external linkage. Static locals may have external
7178 // linkage but still cannot be explicitly imported or exported.
7179 // In Microsoft mode, a variable defined in anonymous namespace must have
7180 // external linkage in order to be exported.
7181 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7182 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7183 (!AnonNSInMicrosoftMode &&
7184 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7185 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7186 << &ND << Attr;
7187 ND.setInvalidDecl();
7188 }
7189 }
7190}
7191
7192static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7193 // Check the attributes on the function type and function params, if any.
7194 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7195 FD = FD->getMostRecentDecl();
7196 // Don't declare this variable in the second operand of the for-statement;
7197 // GCC miscompiles that by ending its lifetime before evaluating the
7198 // third operand. See gcc.gnu.org/PR86769.
7199 AttributedTypeLoc ATL;
7200 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7201 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7202 TL = ATL.getModifiedLoc()) {
7203 // The [[lifetimebound]] attribute can be applied to the implicit object
7204 // parameter of a non-static member function (other than a ctor or dtor)
7205 // by applying it to the function type.
7206 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7207 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7208 int NoImplicitObjectError = -1;
7209 if (!MD)
7210 NoImplicitObjectError = 0;
7211 else if (MD->isStatic())
7212 NoImplicitObjectError = 1;
7213 else if (MD->isExplicitObjectMemberFunction())
7214 NoImplicitObjectError = 2;
7215 if (NoImplicitObjectError != -1) {
7216 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7217 << NoImplicitObjectError << A->getRange();
7218 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7219 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7220 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7221 } else if (MD->getReturnType()->isVoidType()) {
7222 S.Diag(
7223 Loc: MD->getLocation(),
7224 DiagID: diag::
7225 err_lifetimebound_implicit_object_parameter_void_return_type);
7226 }
7227 }
7228 }
7229
7230 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7231 const ParmVarDecl *P = FD->getParamDecl(i: I);
7232
7233 // The [[lifetimebound]] attribute can be applied to a function parameter
7234 // only if the function returns a value.
7235 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7236 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7237 S.Diag(Loc: A->getLocation(),
7238 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7239 }
7240 }
7241 }
7242 }
7243}
7244
7245static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7246 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7247 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_modular_format_attribute_no_format);
7248}
7249
7250static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7251 // Ensure that an auto decl is deduced otherwise the checks below might cache
7252 // the wrong linkage.
7253 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7254
7255 checkWeakAttr(S, ND);
7256 checkWeakRefAttr(S, ND);
7257 checkAliasAttr(S, ND);
7258 checkSelectAnyAttr(S, ND);
7259 checkHybridPatchableAttr(S, ND);
7260 checkInheritableAttr(S, ND);
7261 checkLifetimeBoundAttr(S, ND);
7262 checkModularFormatAttr(S, ND);
7263}
7264
7265static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7266 NamedDecl *NewDecl,
7267 bool IsSpecialization,
7268 bool IsDefinition) {
7269 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7270 return;
7271
7272 bool IsTemplate = false;
7273 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7274 OldDecl = OldTD->getTemplatedDecl();
7275 IsTemplate = true;
7276 if (!IsSpecialization)
7277 IsDefinition = false;
7278 }
7279 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7280 NewDecl = NewTD->getTemplatedDecl();
7281 IsTemplate = true;
7282 }
7283
7284 if (!OldDecl || !NewDecl)
7285 return;
7286
7287 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7288 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7289 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7290 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7291
7292 // dllimport and dllexport are inheritable attributes so we have to exclude
7293 // inherited attribute instances.
7294 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7295 (NewExportAttr && !NewExportAttr->isInherited());
7296
7297 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7298 // the only exception being explicit specializations.
7299 // Implicitly generated declarations are also excluded for now because there
7300 // is no other way to switch these to use dllimport or dllexport.
7301 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7302
7303 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7304 // Allow with a warning for free functions and global variables.
7305 bool JustWarn = false;
7306 if (!OldDecl->isCXXClassMember()) {
7307 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7308 if (VD && !VD->getDescribedVarTemplate())
7309 JustWarn = true;
7310 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7311 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7312 JustWarn = true;
7313 }
7314
7315 // We cannot change a declaration that's been used because IR has already
7316 // been emitted. Dllimported functions will still work though (modulo
7317 // address equality) as they can use the thunk.
7318 if (OldDecl->isUsed())
7319 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7320 JustWarn = false;
7321
7322 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7323 : diag::err_attribute_dll_redeclaration;
7324 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7325 << NewDecl
7326 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7327 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7328 if (!JustWarn) {
7329 NewDecl->setInvalidDecl();
7330 return;
7331 }
7332 }
7333
7334 // A redeclaration is not allowed to drop a dllimport attribute, the only
7335 // exceptions being inline function definitions (except for function
7336 // templates), local extern declarations, qualified friend declarations or
7337 // special MSVC extension: in the last case, the declaration is treated as if
7338 // it were marked dllexport.
7339 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7340 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7341 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7342 // Ignore static data because out-of-line definitions are diagnosed
7343 // separately.
7344 IsStaticDataMember = VD->isStaticDataMember();
7345 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7346 VarDecl::DeclarationOnly;
7347 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7348 IsInline = FD->isInlined();
7349 IsQualifiedFriend = FD->getQualifier() &&
7350 FD->getFriendObjectKind() == Decl::FOK_Declared;
7351 }
7352
7353 if (OldImportAttr && !HasNewAttr &&
7354 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7355 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7356 if (IsMicrosoftABI && IsDefinition) {
7357 if (IsSpecialization) {
7358 S.Diag(
7359 Loc: NewDecl->getLocation(),
7360 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7361 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7362 NewDecl->dropAttr<DLLImportAttr>();
7363 } else {
7364 S.Diag(Loc: NewDecl->getLocation(),
7365 DiagID: diag::warn_redeclaration_without_import_attribute)
7366 << NewDecl;
7367 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7368 NewDecl->dropAttr<DLLImportAttr>();
7369 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7370 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7371 }
7372 } else if (IsMicrosoftABI && IsSpecialization) {
7373 assert(!IsDefinition);
7374 // MSVC allows this. Keep the inherited attribute.
7375 } else {
7376 S.Diag(Loc: NewDecl->getLocation(),
7377 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7378 << NewDecl << OldImportAttr;
7379 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7380 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7381 OldDecl->dropAttr<DLLImportAttr>();
7382 NewDecl->dropAttr<DLLImportAttr>();
7383 }
7384 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7385 // In MinGW, seeing a function declared inline drops the dllimport
7386 // attribute.
7387 OldDecl->dropAttr<DLLImportAttr>();
7388 NewDecl->dropAttr<DLLImportAttr>();
7389 S.Diag(Loc: NewDecl->getLocation(),
7390 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7391 << NewDecl << OldImportAttr;
7392 }
7393
7394 // A specialization of a class template member function is processed here
7395 // since it's a redeclaration. If the parent class is dllexport, the
7396 // specialization inherits that attribute. This doesn't happen automatically
7397 // since the parent class isn't instantiated until later.
7398 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7399 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7400 !NewImportAttr && !NewExportAttr) {
7401 if (const DLLExportAttr *ParentExportAttr =
7402 MD->getParent()->getAttr<DLLExportAttr>()) {
7403 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7404 NewAttr->setInherited(true);
7405 NewDecl->addAttr(A: NewAttr);
7406 }
7407 }
7408 }
7409}
7410
7411/// Given that we are within the definition of the given function,
7412/// will that definition behave like C99's 'inline', where the
7413/// definition is discarded except for optimization purposes?
7414static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7415 // Try to avoid calling GetGVALinkageForFunction.
7416
7417 // All cases of this require the 'inline' keyword.
7418 if (!FD->isInlined()) return false;
7419
7420 // This is only possible in C++ with the gnu_inline attribute.
7421 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7422 return false;
7423
7424 // Okay, go ahead and call the relatively-more-expensive function.
7425 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7426}
7427
7428/// Determine whether a variable is extern "C" prior to attaching
7429/// an initializer. We can't just call isExternC() here, because that
7430/// will also compute and cache whether the declaration is externally
7431/// visible, which might change when we attach the initializer.
7432///
7433/// This can only be used if the declaration is known to not be a
7434/// redeclaration of an internal linkage declaration.
7435///
7436/// For instance:
7437///
7438/// auto x = []{};
7439///
7440/// Attaching the initializer here makes this declaration not externally
7441/// visible, because its type has internal linkage.
7442///
7443/// FIXME: This is a hack.
7444template<typename T>
7445static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7446 if (S.getLangOpts().CPlusPlus) {
7447 // In C++, the overloadable attribute negates the effects of extern "C".
7448 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7449 return false;
7450
7451 // So do CUDA's host/device attributes.
7452 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7453 D->template hasAttr<CUDAHostAttr>()))
7454 return false;
7455 }
7456 return D->isExternC();
7457}
7458
7459static bool shouldConsiderLinkage(const VarDecl *VD) {
7460 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7461 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7462 isa<OMPDeclareMapperDecl>(Val: DC))
7463 return VD->hasExternalStorage();
7464 if (DC->isFileContext())
7465 return true;
7466 if (DC->isRecord())
7467 return false;
7468 if (DC->getDeclKind() == Decl::HLSLBuffer)
7469 return false;
7470
7471 if (isa<RequiresExprBodyDecl>(Val: DC))
7472 return false;
7473 llvm_unreachable("Unexpected context");
7474}
7475
7476static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7477 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7478 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7479 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7480 return true;
7481 if (DC->isRecord())
7482 return false;
7483 llvm_unreachable("Unexpected context");
7484}
7485
7486static bool hasParsedAttr(Scope *S, const Declarator &PD,
7487 ParsedAttr::Kind Kind) {
7488 // Check decl attributes on the DeclSpec.
7489 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7490 return true;
7491
7492 // Walk the declarator structure, checking decl attributes that were in a type
7493 // position to the decl itself.
7494 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7495 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7496 return true;
7497 }
7498
7499 // Finally, check attributes on the decl itself.
7500 return PD.getAttributes().hasAttribute(K: Kind) ||
7501 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7502}
7503
7504bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7505 if (!DC->isFunctionOrMethod())
7506 return false;
7507
7508 // If this is a local extern function or variable declared within a function
7509 // template, don't add it into the enclosing namespace scope until it is
7510 // instantiated; it might have a dependent type right now.
7511 if (DC->isDependentContext())
7512 return true;
7513
7514 // C++11 [basic.link]p7:
7515 // When a block scope declaration of an entity with linkage is not found to
7516 // refer to some other declaration, then that entity is a member of the
7517 // innermost enclosing namespace.
7518 //
7519 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7520 // semantically-enclosing namespace, not a lexically-enclosing one.
7521 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7522 DC = DC->getParent();
7523 return true;
7524}
7525
7526/// Returns true if given declaration has external C language linkage.
7527static bool isDeclExternC(const Decl *D) {
7528 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7529 return FD->isExternC();
7530 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7531 return VD->isExternC();
7532
7533 llvm_unreachable("Unknown type of decl!");
7534}
7535
7536/// Returns true if there hasn't been any invalid type diagnosed.
7537static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7538 DeclContext *DC = NewVD->getDeclContext();
7539 QualType R = NewVD->getType();
7540
7541 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7542 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7543 // argument.
7544 if (R->isImageType() || R->isPipeType()) {
7545 Se.Diag(Loc: NewVD->getLocation(),
7546 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7547 << R;
7548 NewVD->setInvalidDecl();
7549 return false;
7550 }
7551
7552 // OpenCL v1.2 s6.9.r:
7553 // The event type cannot be used to declare a program scope variable.
7554 // OpenCL v2.0 s6.9.q:
7555 // The clk_event_t and reserve_id_t types cannot be declared in program
7556 // scope.
7557 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7558 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7559 Se.Diag(Loc: NewVD->getLocation(),
7560 DiagID: diag::err_invalid_type_for_program_scope_var)
7561 << R;
7562 NewVD->setInvalidDecl();
7563 return false;
7564 }
7565 }
7566
7567 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7568 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7569 LO: Se.getLangOpts())) {
7570 QualType NR = R.getCanonicalType();
7571 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7572 NR->isReferenceType()) {
7573 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7574 NR->isFunctionReferenceType()) {
7575 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7576 << NR->isReferenceType();
7577 NewVD->setInvalidDecl();
7578 return false;
7579 }
7580 NR = NR->getPointeeType();
7581 }
7582 }
7583
7584 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7585 LO: Se.getLangOpts())) {
7586 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7587 // half array type (unless the cl_khr_fp16 extension is enabled).
7588 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7589 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7590 NewVD->setInvalidDecl();
7591 return false;
7592 }
7593 }
7594
7595 // OpenCL v1.2 s6.9.r:
7596 // The event type cannot be used with the __local, __constant and __global
7597 // address space qualifiers.
7598 if (R->isEventT()) {
7599 if (R.getAddressSpace() != LangAS::opencl_private) {
7600 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7601 NewVD->setInvalidDecl();
7602 return false;
7603 }
7604 }
7605
7606 if (R->isSamplerT()) {
7607 // OpenCL v1.2 s6.9.b p4:
7608 // The sampler type cannot be used with the __local and __global address
7609 // space qualifiers.
7610 if (R.getAddressSpace() == LangAS::opencl_local ||
7611 R.getAddressSpace() == LangAS::opencl_global) {
7612 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7613 NewVD->setInvalidDecl();
7614 }
7615
7616 // OpenCL v1.2 s6.12.14.1:
7617 // A global sampler must be declared with either the constant address
7618 // space qualifier or with the const qualifier.
7619 if (DC->isTranslationUnit() &&
7620 !(R.getAddressSpace() == LangAS::opencl_constant ||
7621 R.isConstQualified())) {
7622 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7623 NewVD->setInvalidDecl();
7624 }
7625 if (NewVD->isInvalidDecl())
7626 return false;
7627 }
7628
7629 return true;
7630}
7631
7632template <typename AttrTy>
7633static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7634 const TypedefNameDecl *TND = TT->getDecl();
7635 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7636 AttrTy *Clone = Attribute->clone(S.Context);
7637 Clone->setInherited(true);
7638 D->addAttr(A: Clone);
7639 }
7640}
7641
7642// This function emits warning and a corresponding note based on the
7643// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7644// declarations of an annotated type must be const qualified.
7645static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7646 QualType VarType = VD->getType().getCanonicalType();
7647
7648 // Ignore local declarations (for now) and those with const qualification.
7649 // TODO: Local variables should not be allowed if their type declaration has
7650 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7651 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7652 return;
7653
7654 if (VarType->isArrayType()) {
7655 // Retrieve element type for array declarations.
7656 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7657 }
7658
7659 const RecordDecl *RD = VarType->getAsRecordDecl();
7660
7661 // Check if the record declaration is present and if it has any attributes.
7662 if (RD == nullptr)
7663 return;
7664
7665 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7666 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7667 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7668 return;
7669 }
7670}
7671
7672void Sema::ProcessPragmaExport(DeclaratorDecl *NewD) {
7673 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7674 "NewD is not a function or variable");
7675
7676 if (PendingExportedNames.empty())
7677 return;
7678 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: NewD)) {
7679 if (getLangOpts().CPlusPlus && !FD->isExternC())
7680 return;
7681 }
7682 IdentifierInfo *IdentName = NewD->getIdentifier();
7683 if (IdentName == nullptr)
7684 return;
7685 auto PendingName = PendingExportedNames.find(Val: IdentName);
7686 if (PendingName != PendingExportedNames.end()) {
7687 auto &Label = PendingName->second;
7688 if (!Label.Used) {
7689 Label.Used = true;
7690 if (NewD->hasExternalFormalLinkage())
7691 mergeVisibilityType(D: NewD, Loc: Label.NameLoc, Type: VisibilityAttr::Default);
7692 else
7693 Diag(Loc: Label.NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << NewD;
7694 }
7695 }
7696}
7697
7698// Checks if VD is declared at global scope or with C language linkage.
7699static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7700 return Name.getAsIdentifierInfo() &&
7701 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7702 !VD->getDescribedVarTemplate() &&
7703 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7704 VD->isExternC());
7705}
7706
7707void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7708 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7709
7710 // Quickly return if the function does not have an `asm` attribute.
7711 if (E == nullptr)
7712 return;
7713
7714 // The parser guarantees this is a string.
7715 StringLiteral *SE = cast<StringLiteral>(Val: E);
7716 StringRef Label = SE->getString();
7717 QualType R = TInfo->getType();
7718 if (S->getFnParent() != nullptr) {
7719 switch (SC) {
7720 case SC_None:
7721 case SC_Auto:
7722 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
7723 break;
7724 case SC_Register:
7725 // Local Named register
7726 if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) &&
7727 DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl()))
7728 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7729 break;
7730 case SC_Static:
7731 case SC_Extern:
7732 case SC_PrivateExtern:
7733 break;
7734 }
7735 } else if (SC == SC_Register) {
7736 // Global Named register
7737 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
7738 const auto &TI = Context.getTargetInfo();
7739 bool HasSizeMismatch;
7740
7741 if (!TI.isValidGCCRegisterName(Name: Label))
7742 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7743 else if (!TI.validateGlobalRegisterVariable(RegName: Label, RegSize: Context.getTypeSize(T: R),
7744 HasSizeMismatch))
7745 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
7746 else if (HasSizeMismatch)
7747 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
7748 }
7749
7750 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
7751 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
7752 DiagID: diag::err_asm_unsupported_register_type)
7753 << TInfo->getTypeLoc().getSourceRange();
7754 NewVD->setInvalidDecl(true);
7755 }
7756 }
7757}
7758
7759NamedDecl *Sema::ActOnVariableDeclarator(
7760 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7761 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7762 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7763 QualType R = TInfo->getType();
7764 DeclarationName Name = GetNameForDeclarator(D).getName();
7765
7766 IdentifierInfo *II = Name.getAsIdentifierInfo();
7767 bool IsPlaceholderVariable = false;
7768
7769 if (D.isDecompositionDeclarator()) {
7770 // Take the name of the first declarator as our name for diagnostic
7771 // purposes.
7772 auto &Decomp = D.getDecompositionDeclarator();
7773 if (!Decomp.bindings().empty()) {
7774 II = Decomp.bindings()[0].Name;
7775 Name = II;
7776 }
7777 } else if (!II) {
7778 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7779 return nullptr;
7780 }
7781
7782
7783 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7784 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7785 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7786 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7787
7788 IsPlaceholderVariable = true;
7789
7790 if (!Previous.empty()) {
7791 NamedDecl *PrevDecl = *Previous.begin();
7792 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7793 DC: DC->getRedeclContext());
7794 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7795 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7796 if (IsPlaceholderVariable)
7797 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7798 }
7799 }
7800 }
7801
7802 // dllimport globals without explicit storage class are treated as extern. We
7803 // have to change the storage class this early to get the right DeclContext.
7804 if (SC == SC_None && !DC->isRecord() &&
7805 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7806 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7807 SC = SC_Extern;
7808
7809 DeclContext *OriginalDC = DC;
7810 bool IsLocalExternDecl = SC == SC_Extern &&
7811 adjustContextForLocalExternDecl(DC);
7812
7813 if (SCSpec == DeclSpec::SCS_mutable) {
7814 // mutable can only appear on non-static class members, so it's always
7815 // an error here
7816 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7817 D.setInvalidType();
7818 SC = SC_None;
7819 }
7820
7821 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7822 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7823 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7824 // In C++11, the 'register' storage class specifier is deprecated.
7825 // Suppress the warning in system macros, it's used in macros in some
7826 // popular C system headers, such as in glibc's htonl() macro.
7827 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7828 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7829 : diag::warn_deprecated_register)
7830 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7831 }
7832
7833 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7834
7835 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7836 // C99 6.9p2: The storage-class specifiers auto and register shall not
7837 // appear in the declaration specifiers in an external declaration.
7838 // Global Register+Asm is a GNU extension we support.
7839 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7840 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7841 D.setInvalidType();
7842 }
7843 }
7844
7845 // If this variable has a VLA type and an initializer, try to
7846 // fold to a constant-sized type. This is otherwise invalid.
7847 if (D.hasInitializer() && R->isVariableArrayType())
7848 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7849 /*DiagID=*/FailedFoldDiagID: 0);
7850
7851 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7852 const AutoType *AT = TL.getTypePtr();
7853 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7854 }
7855
7856 bool IsMemberSpecialization = false;
7857 bool IsVariableTemplateSpecialization = false;
7858 bool IsPartialSpecialization = false;
7859 bool IsVariableTemplate = false;
7860 VarDecl *NewVD = nullptr;
7861 VarTemplateDecl *NewTemplate = nullptr;
7862 TemplateParameterList *TemplateParams = nullptr;
7863 if (!getLangOpts().CPlusPlus) {
7864 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7865 Id: II, T: R, TInfo, S: SC);
7866
7867 if (R->getContainedDeducedType())
7868 ParsingInitForAutoVars.insert(Ptr: NewVD);
7869
7870 if (D.isInvalidType())
7871 NewVD->setInvalidDecl();
7872
7873 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7874 NewVD->hasLocalStorage())
7875 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7876 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7877 } else {
7878 bool Invalid = false;
7879 // Match up the template parameter lists with the scope specifier, then
7880 // determine whether we have a template or a template specialization.
7881 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7882 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7883 SS: D.getCXXScopeSpec(),
7884 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7885 ? D.getName().TemplateId
7886 : nullptr,
7887 ParamLists: TemplateParamLists,
7888 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7889
7890 if (TemplateParams) {
7891 if (DC->isDependentContext()) {
7892 ContextRAII SavedContext(*this, DC);
7893 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7894 Invalid = true;
7895 }
7896
7897 if (!TemplateParams->size() &&
7898 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7899 // There is an extraneous 'template<>' for this variable. Complain
7900 // about it, but allow the declaration of the variable.
7901 Diag(Loc: TemplateParams->getTemplateLoc(),
7902 DiagID: diag::err_template_variable_noparams)
7903 << II
7904 << SourceRange(TemplateParams->getTemplateLoc(),
7905 TemplateParams->getRAngleLoc());
7906 TemplateParams = nullptr;
7907 } else {
7908 // Check that we can declare a template here.
7909 if (CheckTemplateDeclScope(S, TemplateParams))
7910 return nullptr;
7911
7912 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7913 // This is an explicit specialization or a partial specialization.
7914 IsVariableTemplateSpecialization = true;
7915 IsPartialSpecialization = TemplateParams->size() > 0;
7916 } else { // if (TemplateParams->size() > 0)
7917 // This is a template declaration.
7918 IsVariableTemplate = true;
7919
7920 // Only C++1y supports variable templates (N3651).
7921 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
7922 }
7923 }
7924 } else {
7925 // Check that we can declare a member specialization here.
7926 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7927 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7928 return nullptr;
7929 assert((Invalid ||
7930 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7931 "should have a 'template<>' for this decl");
7932 }
7933
7934 bool IsExplicitSpecialization =
7935 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7936
7937 // C++ [temp.expl.spec]p2:
7938 // The declaration in an explicit-specialization shall not be an
7939 // export-declaration. An explicit specialization shall not use a
7940 // storage-class-specifier other than thread_local.
7941 //
7942 // We use the storage-class-specifier from DeclSpec because we may have
7943 // added implicit 'extern' for declarations with __declspec(dllimport)!
7944 if (SCSpec != DeclSpec::SCS_unspecified &&
7945 (IsExplicitSpecialization || IsMemberSpecialization)) {
7946 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7947 DiagID: diag::ext_explicit_specialization_storage_class)
7948 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7949 }
7950
7951 if (CurContext->isRecord()) {
7952 if (SC == SC_Static) {
7953 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7954 // Walk up the enclosing DeclContexts to check for any that are
7955 // incompatible with static data members.
7956 const DeclContext *FunctionOrMethod = nullptr;
7957 const CXXRecordDecl *AnonStruct = nullptr;
7958 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7959 if (Ctxt->isFunctionOrMethod()) {
7960 FunctionOrMethod = Ctxt;
7961 break;
7962 }
7963 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
7964 if (ParentDecl && !ParentDecl->getDeclName()) {
7965 AnonStruct = ParentDecl;
7966 break;
7967 }
7968 }
7969 if (FunctionOrMethod) {
7970 // C++ [class.static.data]p5: A local class shall not have static
7971 // data members.
7972 Diag(Loc: D.getIdentifierLoc(),
7973 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
7974 << Name << RD->getDeclName() << RD->getTagKind();
7975 Invalid = true;
7976 RD->setInvalidDecl();
7977 } else if (AnonStruct) {
7978 // C++ [class.static.data]p4: Unnamed classes and classes contained
7979 // directly or indirectly within unnamed classes shall not contain
7980 // static data members.
7981 Diag(Loc: D.getIdentifierLoc(),
7982 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
7983 << Name << AnonStruct->getTagKind();
7984 Invalid = true;
7985 } else if (RD->isUnion()) {
7986 // C++98 [class.union]p1: If a union contains a static data member,
7987 // the program is ill-formed. C++11 drops this restriction.
7988 DiagCompat(Loc: D.getIdentifierLoc(),
7989 CompatDiagId: diag_compat::static_data_member_in_union)
7990 << Name;
7991 }
7992 }
7993 } else if (IsVariableTemplate || IsPartialSpecialization) {
7994 // There is no such thing as a member field template.
7995 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
7996 << II << TemplateParams->getSourceRange();
7997 // Recover by pretending this is a static data member template.
7998 SC = SC_Static;
7999 }
8000 } else if (DC->isRecord()) {
8001 // This is an out-of-line definition of a static data member.
8002 switch (SC) {
8003 case SC_None:
8004 break;
8005 case SC_Static:
8006 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8007 DiagID: diag::err_static_out_of_line)
8008 << FixItHint::CreateRemoval(
8009 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8010 break;
8011 case SC_Auto:
8012 case SC_Register:
8013 case SC_Extern:
8014 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8015 // to names of variables declared in a block or to function parameters.
8016 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8017 // of class members
8018
8019 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8020 DiagID: diag::err_storage_class_for_static_member)
8021 << FixItHint::CreateRemoval(
8022 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8023 break;
8024 case SC_PrivateExtern:
8025 llvm_unreachable("C storage class in c++!");
8026 }
8027 }
8028
8029 if (IsVariableTemplateSpecialization) {
8030 SourceLocation TemplateKWLoc =
8031 TemplateParamLists.size() > 0
8032 ? TemplateParamLists[0]->getTemplateLoc()
8033 : SourceLocation();
8034 DeclResult Res = ActOnVarTemplateSpecialization(
8035 S, D, TSI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8036 IsPartialSpecialization);
8037 if (Res.isInvalid())
8038 return nullptr;
8039 NewVD = cast<VarDecl>(Val: Res.get());
8040 AddToScope = false;
8041 } else if (D.isDecompositionDeclarator()) {
8042 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8043 LSquareLoc: D.getIdentifierLoc(), T: R, TInfo, S: SC,
8044 Bindings);
8045 } else
8046 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8047 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
8048
8049 // If this is supposed to be a variable template, create it as such.
8050 if (IsVariableTemplate) {
8051 NewTemplate =
8052 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
8053 Params: TemplateParams, Decl: NewVD);
8054 NewVD->setDescribedVarTemplate(NewTemplate);
8055 }
8056
8057 // If this decl has an auto type in need of deduction, make a note of the
8058 // Decl so we can diagnose uses of it in its own initializer.
8059 if (R->getContainedDeducedType())
8060 ParsingInitForAutoVars.insert(Ptr: NewVD);
8061
8062 if (D.isInvalidType() || Invalid) {
8063 NewVD->setInvalidDecl();
8064 if (NewTemplate)
8065 NewTemplate->setInvalidDecl();
8066 }
8067
8068 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
8069
8070 // If we have any template parameter lists that don't directly belong to
8071 // the variable (matching the scope specifier), store them.
8072 // An explicit variable template specialization does not own any template
8073 // parameter lists.
8074 unsigned VDTemplateParamLists =
8075 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8076 if (TemplateParamLists.size() > VDTemplateParamLists)
8077 NewVD->setTemplateParameterListsInfo(
8078 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
8079 }
8080
8081 if (D.getDeclSpec().isInlineSpecified()) {
8082 if (!getLangOpts().CPlusPlus) {
8083 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
8084 << 0;
8085 } else if (CurContext->isFunctionOrMethod()) {
8086 // 'inline' is not allowed on block scope variable declaration.
8087 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8088 DiagID: diag::err_inline_declaration_block_scope) << Name
8089 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
8090 } else {
8091 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8092 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8093 : diag::compat_pre_cxx17_inline_variable);
8094 NewVD->setInlineSpecified();
8095 }
8096 }
8097
8098 // Set the lexical context. If the declarator has a C++ scope specifier, the
8099 // lexical context will be different from the semantic context.
8100 NewVD->setLexicalDeclContext(CurContext);
8101 if (NewTemplate)
8102 NewTemplate->setLexicalDeclContext(CurContext);
8103
8104 if (IsLocalExternDecl) {
8105 if (D.isDecompositionDeclarator())
8106 for (auto *B : Bindings)
8107 B->setLocalExternDecl();
8108 else
8109 NewVD->setLocalExternDecl();
8110 }
8111
8112 bool EmitTLSUnsupportedError = false;
8113 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8114 // C++11 [dcl.stc]p4:
8115 // When thread_local is applied to a variable of block scope the
8116 // storage-class-specifier static is implied if it does not appear
8117 // explicitly.
8118 // Core issue: 'static' is not implied if the variable is declared
8119 // 'extern'.
8120 if (NewVD->hasLocalStorage() &&
8121 (SCSpec != DeclSpec::SCS_unspecified ||
8122 TSCS != DeclSpec::TSCS_thread_local ||
8123 !DC->isFunctionOrMethod()))
8124 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8125 DiagID: diag::err_thread_non_global)
8126 << DeclSpec::getSpecifierName(S: TSCS);
8127 else if (!Context.getTargetInfo().isTLSSupported()) {
8128 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8129 // Postpone error emission until we've collected attributes required to
8130 // figure out whether it's a host or device variable and whether the
8131 // error should be ignored.
8132 EmitTLSUnsupportedError = true;
8133 // We still need to mark the variable as TLS so it shows up in AST with
8134 // proper storage class for other tools to use even if we're not going
8135 // to emit any code for it.
8136 NewVD->setTSCSpec(TSCS);
8137 } else
8138 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8139 DiagID: diag::err_thread_unsupported);
8140 } else
8141 NewVD->setTSCSpec(TSCS);
8142 }
8143
8144 switch (D.getDeclSpec().getConstexprSpecifier()) {
8145 case ConstexprSpecKind::Unspecified:
8146 break;
8147
8148 case ConstexprSpecKind::Consteval:
8149 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8150 DiagID: diag::err_constexpr_wrong_decl_kind)
8151 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8152 [[fallthrough]];
8153
8154 case ConstexprSpecKind::Constexpr:
8155 NewVD->setConstexpr(true);
8156 // C++1z [dcl.spec.constexpr]p1:
8157 // A static data member declared with the constexpr specifier is
8158 // implicitly an inline variable.
8159 if (NewVD->isStaticDataMember() &&
8160 (getLangOpts().CPlusPlus17 ||
8161 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8162 NewVD->setImplicitlyInline();
8163 break;
8164
8165 case ConstexprSpecKind::Constinit:
8166 if (!NewVD->hasGlobalStorage())
8167 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8168 DiagID: diag::err_constinit_local_variable);
8169 else
8170 NewVD->addAttr(
8171 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
8172 S: ConstInitAttr::Keyword_constinit));
8173 break;
8174 }
8175
8176 // C99 6.7.4p3
8177 // An inline definition of a function with external linkage shall
8178 // not contain a definition of a modifiable object with static or
8179 // thread storage duration...
8180 // We only apply this when the function is required to be defined
8181 // elsewhere, i.e. when the function is not 'extern inline'. Note
8182 // that a local variable with thread storage duration still has to
8183 // be marked 'static'. Also note that it's possible to get these
8184 // semantics in C++ using __attribute__((gnu_inline)).
8185 if (SC == SC_Static && S->getFnParent() != nullptr &&
8186 !NewVD->getType().isConstQualified()) {
8187 FunctionDecl *CurFD = getCurFunctionDecl();
8188 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
8189 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8190 DiagID: diag::warn_static_local_in_extern_inline);
8191 MaybeSuggestAddingStaticToDecl(D: CurFD);
8192 }
8193 }
8194
8195 if (D.getDeclSpec().isModulePrivateSpecified()) {
8196 if (IsVariableTemplateSpecialization)
8197 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8198 << (IsPartialSpecialization ? 1 : 0)
8199 << FixItHint::CreateRemoval(
8200 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8201 else if (IsMemberSpecialization)
8202 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8203 << 2
8204 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8205 else if (NewVD->hasLocalStorage())
8206 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
8207 << 0 << NewVD
8208 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8209 << FixItHint::CreateRemoval(
8210 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8211 else {
8212 NewVD->setModulePrivate();
8213 if (NewTemplate)
8214 NewTemplate->setModulePrivate();
8215 for (auto *B : Bindings)
8216 B->setModulePrivate();
8217 }
8218 }
8219
8220 if (getLangOpts().OpenCL) {
8221 deduceOpenCLAddressSpace(Var: NewVD);
8222
8223 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8224 if (TSC != TSCS_unspecified) {
8225 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8226 DiagID: diag::err_opencl_unknown_type_specifier)
8227 << getLangOpts().getOpenCLVersionString()
8228 << DeclSpec::getSpecifierName(S: TSC) << 1;
8229 NewVD->setInvalidDecl();
8230 }
8231 }
8232
8233 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8234 // address space if the table has local storage (semantic checks elsewhere
8235 // will produce an error anyway).
8236 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8237 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8238 !NewVD->hasLocalStorage()) {
8239 QualType Type = Context.getAddrSpaceQualType(
8240 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8241 NewVD->setType(Type);
8242 }
8243 }
8244
8245 LoadExternalExtnameUndeclaredIdentifiers();
8246
8247 if (Expr *E = D.getAsmLabel()) {
8248 // The parser guarantees this is a string.
8249 StringLiteral *SE = cast<StringLiteral>(Val: E);
8250 StringRef Label = SE->getString();
8251
8252 // Insert the asm attribute.
8253 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, Range: SE->getStrTokenLoc(TokNum: 0)));
8254 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8255 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8256 ExtnameUndeclaredIdentifiers.find(Val: NewVD->getIdentifier());
8257 if (I != ExtnameUndeclaredIdentifiers.end()) {
8258 if (isDeclExternC(D: NewVD)) {
8259 NewVD->addAttr(A: I->second);
8260 ExtnameUndeclaredIdentifiers.erase(I);
8261 } else if (NewVD->getDeclContext()
8262 ->getRedeclContext()
8263 ->isTranslationUnit())
8264 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8265 << /*Variable*/ 1 << NewVD;
8266 }
8267 }
8268
8269 // Handle attributes prior to checking for duplicates in MergeVarDecl
8270 ProcessDeclAttributes(S, D: NewVD, PD: D);
8271
8272 if (getLangOpts().HLSL)
8273 HLSL().ActOnVariableDeclarator(VD: NewVD);
8274
8275 if (getLangOpts().OpenACC)
8276 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8277
8278 // FIXME: This is probably the wrong location to be doing this and we should
8279 // probably be doing this for more attributes (especially for function
8280 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8281 // the code to copy attributes would be generated by TableGen.
8282 if (R->isFunctionPointerType())
8283 if (const auto *TT = R->getAs<TypedefType>())
8284 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8285
8286 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8287 if (EmitTLSUnsupportedError &&
8288 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8289 (getLangOpts().OpenMPIsTargetDevice &&
8290 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8291 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8292 DiagID: diag::err_thread_unsupported);
8293
8294 if (EmitTLSUnsupportedError &&
8295 (LangOpts.SYCLIsDevice ||
8296 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8297 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8298 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8299 // storage [duration]."
8300 if (SC == SC_None && S->getFnParent() != nullptr &&
8301 (NewVD->hasAttr<CUDASharedAttr>() ||
8302 NewVD->hasAttr<CUDAConstantAttr>())) {
8303 NewVD->setStorageClass(SC_Static);
8304 }
8305 }
8306
8307 // Ensure that dllimport globals without explicit storage class are treated as
8308 // extern. The storage class is set above using parsed attributes. Now we can
8309 // check the VarDecl itself.
8310 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8311 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8312 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8313
8314 // In auto-retain/release, infer strong retension for variables of
8315 // retainable type.
8316 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8317 NewVD->setInvalidDecl();
8318
8319 // Check the ASM label here, as we need to know all other attributes of the
8320 // Decl first. Otherwise, we can't know if the asm label refers to the
8321 // host or device in a CUDA context. The device has other registers than
8322 // host and we must know where the function will be placed.
8323 CheckAsmLabel(S, E: D.getAsmLabel(), SC, TInfo, NewVD);
8324
8325 // Find the shadowed declaration before filtering for scope.
8326 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8327 ? getShadowedDeclaration(D: NewVD, R: Previous)
8328 : nullptr;
8329
8330 // Don't consider existing declarations that are in a different
8331 // scope and are out-of-semantic-context declarations (if the new
8332 // declaration has linkage).
8333 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8334 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8335 IsMemberSpecialization ||
8336 IsVariableTemplateSpecialization);
8337
8338 // Check whether the previous declaration is in the same block scope. This
8339 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8340 if (getLangOpts().CPlusPlus &&
8341 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8342 NewVD->setPreviousDeclInSameBlockScope(
8343 Previous.isSingleResult() && !Previous.isShadowed() &&
8344 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8345
8346 if (!getLangOpts().CPlusPlus) {
8347 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8348 } else {
8349 // If this is an explicit specialization of a static data member, check it.
8350 if (IsMemberSpecialization && !IsVariableTemplate &&
8351 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8352 CheckMemberSpecialization(Member: NewVD, Previous))
8353 NewVD->setInvalidDecl();
8354
8355 // Merge the decl with the existing one if appropriate.
8356 if (!Previous.empty()) {
8357 if (Previous.isSingleResult() &&
8358 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8359 D.getCXXScopeSpec().isSet()) {
8360 // The user tried to define a non-static data member
8361 // out-of-line (C++ [dcl.meaning]p1).
8362 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8363 << D.getCXXScopeSpec().getRange();
8364 Previous.clear();
8365 NewVD->setInvalidDecl();
8366 }
8367 } else if (D.getCXXScopeSpec().isSet() &&
8368 !IsVariableTemplateSpecialization) {
8369 // No previous declaration in the qualifying scope.
8370 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8371 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8372 << D.getCXXScopeSpec().getRange();
8373 NewVD->setInvalidDecl();
8374 }
8375
8376 if (!IsPlaceholderVariable)
8377 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8378
8379 // CheckVariableDeclaration will set NewVD as invalid if something is in
8380 // error like WebAssembly tables being declared as arrays with a non-zero
8381 // size, but then parsing continues and emits further errors on that line.
8382 // To avoid that we check here if it happened and return nullptr.
8383 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8384 return nullptr;
8385
8386 if (NewTemplate) {
8387 VarTemplateDecl *PrevVarTemplate =
8388 NewVD->getPreviousDecl()
8389 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8390 : nullptr;
8391
8392 // Check the template parameter list of this declaration, possibly
8393 // merging in the template parameter list from the previous variable
8394 // template declaration.
8395 if (CheckTemplateParameterList(
8396 NewParams: TemplateParams,
8397 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8398 : nullptr,
8399 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8400 DC->isDependentContext())
8401 ? TPC_ClassTemplateMember
8402 : TPC_Other))
8403 NewVD->setInvalidDecl();
8404
8405 // If we are providing an explicit specialization of a static variable
8406 // template, make a note of that.
8407 if (PrevVarTemplate &&
8408 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8409 PrevVarTemplate->setMemberSpecialization();
8410 }
8411 }
8412
8413 // Diagnose shadowed variables iff this isn't a redeclaration.
8414 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8415 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8416
8417 ProcessPragmaWeak(S, D: NewVD);
8418 ProcessPragmaExport(NewD: NewVD);
8419
8420 // If this is the first declaration of an extern C variable, update
8421 // the map of such variables.
8422 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8423 isIncompleteDeclExternC(S&: *this, D: NewVD))
8424 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8425
8426 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8427 MangleNumberingContext *MCtx;
8428 Decl *ManglingContextDecl;
8429 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8430 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8431 if (MCtx) {
8432 Context.setManglingNumber(
8433 ND: NewVD, Number: MCtx->getManglingNumber(
8434 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8435 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8436 }
8437 }
8438
8439 // Special handling of variable named 'main'.
8440 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8441 // C++ [basic.start.main]p3:
8442 // A program that declares
8443 // - a variable main at global scope, or
8444 // - an entity named main with C language linkage (in any namespace)
8445 // is ill-formed
8446 if (getLangOpts().CPlusPlus)
8447 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8448 << NewVD->isExternC();
8449
8450 // In C, and external-linkage variable named main results in undefined
8451 // behavior.
8452 else if (NewVD->hasExternalFormalLinkage())
8453 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8454 }
8455
8456 if (D.isRedeclaration() && !Previous.empty()) {
8457 NamedDecl *Prev = Previous.getRepresentativeDecl();
8458 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8459 IsDefinition: D.isFunctionDefinition());
8460 }
8461
8462 if (NewTemplate) {
8463 if (NewVD->isInvalidDecl())
8464 NewTemplate->setInvalidDecl();
8465 ActOnDocumentableDecl(D: NewTemplate);
8466 return NewTemplate;
8467 }
8468
8469 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8470 CompleteMemberSpecialization(Member: NewVD, Previous);
8471
8472 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8473
8474 return NewVD;
8475}
8476
8477/// Enum describing the %select options in diag::warn_decl_shadow.
8478enum ShadowedDeclKind {
8479 SDK_Local,
8480 SDK_Global,
8481 SDK_StaticMember,
8482 SDK_Field,
8483 SDK_Typedef,
8484 SDK_Using,
8485 SDK_StructuredBinding
8486};
8487
8488/// Determine what kind of declaration we're shadowing.
8489static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8490 const DeclContext *OldDC) {
8491 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8492 return SDK_Using;
8493 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8494 return SDK_Typedef;
8495 else if (isa<BindingDecl>(Val: ShadowedDecl))
8496 return SDK_StructuredBinding;
8497 else if (isa<RecordDecl>(Val: OldDC))
8498 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8499
8500 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8501}
8502
8503/// Return the location of the capture if the given lambda captures the given
8504/// variable \p VD, or an invalid source location otherwise.
8505static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8506 const ValueDecl *VD) {
8507 for (const Capture &Capture : LSI->Captures) {
8508 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8509 return Capture.getLocation();
8510 }
8511 return SourceLocation();
8512}
8513
8514static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8515 const LookupResult &R) {
8516 // Only diagnose if we're shadowing an unambiguous field or variable.
8517 if (R.getResultKind() != LookupResultKind::Found)
8518 return false;
8519
8520 // Return false if warning is ignored.
8521 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8522}
8523
8524NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8525 const LookupResult &R) {
8526 if (!shouldWarnIfShadowedDecl(Diags, R))
8527 return nullptr;
8528
8529 // Don't diagnose declarations at file scope.
8530 if (D->hasGlobalStorage() && !D->isStaticLocal())
8531 return nullptr;
8532
8533 NamedDecl *ShadowedDecl = R.getFoundDecl();
8534 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8535 : nullptr;
8536}
8537
8538NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8539 const LookupResult &R) {
8540 // Don't warn if typedef declaration is part of a class
8541 if (D->getDeclContext()->isRecord())
8542 return nullptr;
8543
8544 if (!shouldWarnIfShadowedDecl(Diags, R))
8545 return nullptr;
8546
8547 NamedDecl *ShadowedDecl = R.getFoundDecl();
8548 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8549}
8550
8551NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8552 const LookupResult &R) {
8553 if (!shouldWarnIfShadowedDecl(Diags, R))
8554 return nullptr;
8555
8556 NamedDecl *ShadowedDecl = R.getFoundDecl();
8557 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8558 : nullptr;
8559}
8560
8561void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8562 const LookupResult &R) {
8563 DeclContext *NewDC = D->getDeclContext();
8564
8565 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8566 if (const auto *MD =
8567 dyn_cast<CXXMethodDecl>(Val: getFunctionLevelDeclContext())) {
8568 // Fields aren't shadowed in C++ static members or in member functions
8569 // with an explicit object parameter.
8570 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8571 return;
8572 }
8573 // Fields shadowed by constructor parameters are a special case. Usually
8574 // the constructor initializes the field with the parameter.
8575 if (isa<CXXConstructorDecl>(Val: NewDC))
8576 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8577 // Remember that this was shadowed so we can either warn about its
8578 // modification or its existence depending on warning settings.
8579 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8580 return;
8581 }
8582 }
8583
8584 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8585 if (shadowedVar->isExternC()) {
8586 // For shadowing external vars, make sure that we point to the global
8587 // declaration, not a locally scoped extern declaration.
8588 for (auto *I : shadowedVar->redecls())
8589 if (I->isFileVarDecl()) {
8590 ShadowedDecl = I;
8591 break;
8592 }
8593 }
8594
8595 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8596
8597 unsigned WarningDiag = diag::warn_decl_shadow;
8598 SourceLocation CaptureLoc;
8599 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8600 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8601 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8602 // Handle both VarDecl and BindingDecl in lambda contexts
8603 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8604 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8605 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8606 if (RD->getLambdaCaptureDefault() == LCD_None) {
8607 // Try to avoid warnings for lambdas with an explicit capture
8608 // list. Warn only when the lambda captures the shadowed decl
8609 // explicitly.
8610 CaptureLoc = getCaptureLocation(LSI, VD);
8611 if (CaptureLoc.isInvalid())
8612 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8613 } else {
8614 // Remember that this was shadowed so we can avoid the warning if
8615 // the shadowed decl isn't captured and the warning settings allow
8616 // it.
8617 cast<LambdaScopeInfo>(Val: getCurFunction())
8618 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8619 return;
8620 }
8621 }
8622 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8623 // If lambda can capture this, then emit default shadowing warning,
8624 // Otherwise it is not really a shadowing case since field is not
8625 // available in lambda's body.
8626 // At this point we don't know that lambda can capture this, so
8627 // remember that this was shadowed and delay until we know.
8628 cast<LambdaScopeInfo>(Val: getCurFunction())
8629 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8630 return;
8631 }
8632 }
8633 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8634 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8635 bool HasLocalStorage = false;
8636 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl))
8637 HasLocalStorage = VD->hasLocalStorage();
8638 else if (const auto *BD = dyn_cast<BindingDecl>(Val: ShadowedDecl))
8639 HasLocalStorage =
8640 cast<VarDecl>(Val: BD->getDecomposedDecl())->hasLocalStorage();
8641
8642 if (HasLocalStorage) {
8643 // A variable can't shadow a local variable or binding in an enclosing
8644 // scope, if they are separated by a non-capturing declaration
8645 // context.
8646 for (DeclContext *ParentDC = NewDC;
8647 ParentDC && !ParentDC->Equals(DC: OldDC);
8648 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8649 // Only block literals, captured statements, and lambda expressions
8650 // can capture; other scopes don't.
8651 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8652 !isLambdaCallOperator(DC: ParentDC))
8653 return;
8654 }
8655 }
8656 }
8657 }
8658 }
8659
8660 // Never warn about shadowing a placeholder variable.
8661 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8662 return;
8663
8664 // Only warn about certain kinds of shadowing for class members.
8665 if (NewDC) {
8666 // In particular, don't warn about shadowing non-class members.
8667 if (NewDC->isRecord() && !OldDC->isRecord())
8668 return;
8669
8670 // Skip shadowing check if we're in a class scope, dealing with an enum
8671 // constant in a different context.
8672 DeclContext *ReDC = NewDC->getRedeclContext();
8673 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8674 return;
8675
8676 // TODO: should we warn about static data members shadowing
8677 // static data members from base classes?
8678
8679 // TODO: don't diagnose for inaccessible shadowed members.
8680 // This is hard to do perfectly because we might friend the
8681 // shadowing context, but that's just a false negative.
8682 }
8683
8684 DeclarationName Name = R.getLookupName();
8685
8686 // Emit warning and note.
8687 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8688 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8689 if (!CaptureLoc.isInvalid())
8690 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8691 << Name << /*explicitly*/ 1;
8692 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8693}
8694
8695void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8696 for (const auto &Shadow : LSI->ShadowingDecls) {
8697 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8698 // Try to avoid the warning when the shadowed decl isn't captured.
8699 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8700 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8701 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8702 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8703 Diag(Loc: Shadow.VD->getLocation(),
8704 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8705 : diag::warn_decl_shadow)
8706 << Shadow.VD->getDeclName()
8707 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8708 if (CaptureLoc.isValid())
8709 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8710 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8711 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8712 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8713 Diag(Loc: Shadow.VD->getLocation(),
8714 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8715 : diag::warn_decl_shadow_uncaptured_local)
8716 << Shadow.VD->getDeclName()
8717 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8718 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8719 }
8720 }
8721}
8722
8723void Sema::CheckShadow(Scope *S, VarDecl *D) {
8724 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8725 return;
8726
8727 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8728 Sema::LookupOrdinaryName,
8729 RedeclarationKind::ForVisibleRedeclaration);
8730 LookupName(R, S);
8731 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8732 CheckShadow(D, ShadowedDecl, R);
8733}
8734
8735/// Check if 'E', which is an expression that is about to be modified, refers
8736/// to a constructor parameter that shadows a field.
8737void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8738 // Quickly ignore expressions that can't be shadowing ctor parameters.
8739 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8740 return;
8741 E = E->IgnoreParenImpCasts();
8742 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8743 if (!DRE)
8744 return;
8745 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8746 auto I = ShadowingDecls.find(Val: D);
8747 if (I == ShadowingDecls.end())
8748 return;
8749 const NamedDecl *ShadowedDecl = I->second;
8750 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8751 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8752 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8753 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8754
8755 // Avoid issuing multiple warnings about the same decl.
8756 ShadowingDecls.erase(I);
8757}
8758
8759/// Check for conflict between this global or extern "C" declaration and
8760/// previous global or extern "C" declarations. This is only used in C++.
8761template<typename T>
8762static bool checkGlobalOrExternCConflict(
8763 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8764 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8765 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8766
8767 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8768 // The common case: this global doesn't conflict with any extern "C"
8769 // declaration.
8770 return false;
8771 }
8772
8773 if (Prev) {
8774 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8775 // Both the old and new declarations have C language linkage. This is a
8776 // redeclaration.
8777 Previous.clear();
8778 Previous.addDecl(D: Prev);
8779 return true;
8780 }
8781
8782 // This is a global, non-extern "C" declaration, and there is a previous
8783 // non-global extern "C" declaration. Diagnose if this is a variable
8784 // declaration.
8785 if (!isa<VarDecl>(ND))
8786 return false;
8787 } else {
8788 // The declaration is extern "C". Check for any declaration in the
8789 // translation unit which might conflict.
8790 if (IsGlobal) {
8791 // We have already performed the lookup into the translation unit.
8792 IsGlobal = false;
8793 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8794 I != E; ++I) {
8795 if (isa<VarDecl>(Val: *I)) {
8796 Prev = *I;
8797 break;
8798 }
8799 }
8800 } else {
8801 DeclContext::lookup_result R =
8802 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8803 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8804 I != E; ++I) {
8805 if (isa<VarDecl>(Val: *I)) {
8806 Prev = *I;
8807 break;
8808 }
8809 // FIXME: If we have any other entity with this name in global scope,
8810 // the declaration is ill-formed, but that is a defect: it breaks the
8811 // 'stat' hack, for instance. Only variables can have mangled name
8812 // clashes with extern "C" declarations, so only they deserve a
8813 // diagnostic.
8814 }
8815 }
8816
8817 if (!Prev)
8818 return false;
8819 }
8820
8821 // Use the first declaration's location to ensure we point at something which
8822 // is lexically inside an extern "C" linkage-spec.
8823 assert(Prev && "should have found a previous declaration to diagnose");
8824 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8825 Prev = FD->getFirstDecl();
8826 else
8827 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8828
8829 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8830 << IsGlobal << ND;
8831 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8832 << IsGlobal;
8833 return false;
8834}
8835
8836/// Apply special rules for handling extern "C" declarations. Returns \c true
8837/// if we have found that this is a redeclaration of some prior entity.
8838///
8839/// Per C++ [dcl.link]p6:
8840/// Two declarations [for a function or variable] with C language linkage
8841/// with the same name that appear in different scopes refer to the same
8842/// [entity]. An entity with C language linkage shall not be declared with
8843/// the same name as an entity in global scope.
8844template<typename T>
8845static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8846 LookupResult &Previous) {
8847 if (!S.getLangOpts().CPlusPlus) {
8848 // In C, when declaring a global variable, look for a corresponding 'extern'
8849 // variable declared in function scope. We don't need this in C++, because
8850 // we find local extern decls in the surrounding file-scope DeclContext.
8851 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8852 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8853 Previous.clear();
8854 Previous.addDecl(D: Prev);
8855 return true;
8856 }
8857 }
8858 return false;
8859 }
8860
8861 // A declaration in the translation unit can conflict with an extern "C"
8862 // declaration.
8863 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8864 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8865
8866 // An extern "C" declaration can conflict with a declaration in the
8867 // translation unit or can be a redeclaration of an extern "C" declaration
8868 // in another scope.
8869 if (isIncompleteDeclExternC(S,ND))
8870 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8871
8872 // Neither global nor extern "C": nothing to do.
8873 return false;
8874}
8875
8876static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8877 QualType T) {
8878 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8879 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8880 // any of its members, even recursively, shall not have an atomic type, or a
8881 // variably modified type, or a type that is volatile or restrict qualified.
8882 if (CanonT->isVariablyModifiedType()) {
8883 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8884 return true;
8885 }
8886
8887 // Arrays are qualified by their element type, so get the base type (this
8888 // works on non-arrays as well).
8889 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8890
8891 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8892 CanonT.isRestrictQualified()) {
8893 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8894 return true;
8895 }
8896
8897 if (CanonT->isRecordType()) {
8898 const RecordDecl *RD = CanonT->getAsRecordDecl();
8899 if (!RD->isInvalidDecl() &&
8900 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8901 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
8902 }))
8903 return true;
8904 }
8905
8906 return false;
8907}
8908
8909void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8910 // If the decl is already known invalid, don't check it.
8911 if (NewVD->isInvalidDecl())
8912 return;
8913
8914 QualType T = NewVD->getType();
8915
8916 // Defer checking an 'auto' type until its initializer is attached.
8917 if (T->isUndeducedType())
8918 return;
8919
8920 if (NewVD->hasAttrs())
8921 CheckAlignasUnderalignment(D: NewVD);
8922
8923 if (T->isObjCObjectType()) {
8924 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
8925 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
8926 T = Context.getObjCObjectPointerType(OIT: T);
8927 NewVD->setType(T);
8928 }
8929
8930 // Emit an error if an address space was applied to decl with local storage.
8931 // This includes arrays of objects with address space qualifiers, but not
8932 // automatic variables that point to other address spaces.
8933 // ISO/IEC TR 18037 S5.1.2
8934 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8935 T.getAddressSpace() != LangAS::Default) {
8936 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
8937 NewVD->setInvalidDecl();
8938 return;
8939 }
8940
8941 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8942 // scope.
8943 if (getLangOpts().OpenCLVersion == 120 &&
8944 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
8945 LO: getLangOpts()) &&
8946 NewVD->isStaticLocal()) {
8947 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
8948 NewVD->setInvalidDecl();
8949 return;
8950 }
8951
8952 if (getLangOpts().OpenCL) {
8953 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
8954 return;
8955
8956 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8957 if (NewVD->hasAttr<BlocksAttr>()) {
8958 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
8959 return;
8960 }
8961
8962 if (T->isBlockPointerType()) {
8963 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8964 // can't use 'extern' storage class.
8965 if (!T.isConstQualified()) {
8966 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
8967 << 0 /*const*/;
8968 NewVD->setInvalidDecl();
8969 return;
8970 }
8971 if (NewVD->hasExternalStorage()) {
8972 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
8973 NewVD->setInvalidDecl();
8974 return;
8975 }
8976 }
8977
8978 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8979 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8980 NewVD->hasExternalStorage()) {
8981 if (!T->isSamplerT() && !T->isDependentType() &&
8982 !(T.getAddressSpace() == LangAS::opencl_constant ||
8983 (T.getAddressSpace() == LangAS::opencl_global &&
8984 getOpenCLOptions().areProgramScopeVariablesSupported(
8985 Opts: getLangOpts())))) {
8986 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8987 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
8988 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8989 << Scope << "global or constant";
8990 else
8991 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8992 << Scope << "constant";
8993 NewVD->setInvalidDecl();
8994 return;
8995 }
8996 } else {
8997 if (T.getAddressSpace() == LangAS::opencl_global) {
8998 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8999 << 1 /*is any function*/ << "global";
9000 NewVD->setInvalidDecl();
9001 return;
9002 }
9003 // When this extension is enabled, 'local' variables are permitted in
9004 // non-kernel functions and within nested scopes of kernel functions,
9005 // bypassing standard OpenCL address space restrictions.
9006 bool AllowFunctionScopeLocalVariables =
9007 T.getAddressSpace() == LangAS::opencl_local &&
9008 getOpenCLOptions().isAvailableOption(
9009 Ext: "__cl_clang_function_scope_local_variables", LO: getLangOpts());
9010 if (AllowFunctionScopeLocalVariables) {
9011 // Direct pass: No further diagnostics needed for this specific case.
9012 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9013 T.getAddressSpace() == LangAS::opencl_local) {
9014 FunctionDecl *FD = getCurFunctionDecl();
9015 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9016 // in functions.
9017 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9018 if (T.getAddressSpace() == LangAS::opencl_constant)
9019 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9020 << 0 /*non-kernel only*/ << "constant";
9021 else
9022 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9023 << 0 /*non-kernel only*/ << "local";
9024 NewVD->setInvalidDecl();
9025 return;
9026 }
9027 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9028 // in the outermost scope of a kernel function.
9029 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9030 if (!getCurScope()->isFunctionScope()) {
9031 if (T.getAddressSpace() == LangAS::opencl_constant)
9032 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9033 << "constant";
9034 else
9035 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9036 << "local";
9037 NewVD->setInvalidDecl();
9038 return;
9039 }
9040 }
9041 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9042 // If we are parsing a template we didn't deduce an addr
9043 // space yet.
9044 T.getAddressSpace() != LangAS::Default) {
9045 // Do not allow other address spaces on automatic variable.
9046 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
9047 NewVD->setInvalidDecl();
9048 return;
9049 }
9050 }
9051 }
9052
9053 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9054 && !NewVD->hasAttr<BlocksAttr>()) {
9055 if (getLangOpts().getGC() != LangOptions::NonGC)
9056 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
9057 else {
9058 assert(!getLangOpts().ObjCAutoRefCount);
9059 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
9060 }
9061 }
9062
9063 // WebAssembly tables must be static with a zero length and can't be
9064 // declared within functions.
9065 if (T->isWebAssemblyTableType()) {
9066 if (getCurScope()->getParent()) { // Parent is null at top-level
9067 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
9068 NewVD->setInvalidDecl();
9069 return;
9070 }
9071 if (NewVD->getStorageClass() != SC_Static) {
9072 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
9073 NewVD->setInvalidDecl();
9074 return;
9075 }
9076 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
9077 if (!ATy || ATy->getZExtSize() != 0) {
9078 Diag(Loc: NewVD->getLocation(),
9079 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
9080 NewVD->setInvalidDecl();
9081 return;
9082 }
9083 }
9084
9085 // zero sized static arrays are not allowed in HIP device functions
9086 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9087 if (FunctionDecl *FD = getCurFunctionDecl();
9088 FD &&
9089 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9090 if (const ConstantArrayType *ArrayT =
9091 getASTContext().getAsConstantArrayType(T);
9092 ArrayT && ArrayT->isZeroSize()) {
9093 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
9094 }
9095 }
9096 }
9097
9098 bool isVM = T->isVariablyModifiedType();
9099 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9100 NewVD->hasAttr<BlocksAttr>())
9101 setFunctionHasBranchProtectedScope();
9102
9103 if ((isVM && NewVD->hasLinkage()) ||
9104 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9105 bool SizeIsNegative;
9106 llvm::APSInt Oversized;
9107 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9108 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9109 QualType FixedT;
9110 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9111 FixedT = FixedTInfo->getType();
9112 else if (FixedTInfo) {
9113 // Type and type-as-written are canonically different. We need to fix up
9114 // both types separately.
9115 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9116 Oversized);
9117 }
9118 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9119 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9120 // FIXME: This won't give the correct result for
9121 // int a[10][n];
9122 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9123
9124 if (NewVD->isFileVarDecl())
9125 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
9126 << SizeRange;
9127 else if (NewVD->isStaticLocal())
9128 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
9129 << SizeRange;
9130 else
9131 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
9132 << SizeRange;
9133 NewVD->setInvalidDecl();
9134 return;
9135 }
9136
9137 if (!FixedTInfo) {
9138 if (NewVD->isFileVarDecl())
9139 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
9140 else
9141 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
9142 NewVD->setInvalidDecl();
9143 return;
9144 }
9145
9146 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
9147 NewVD->setType(FixedT);
9148 NewVD->setTypeSourceInfo(FixedTInfo);
9149 }
9150
9151 if (T->isVoidType()) {
9152 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9153 // of objects and functions.
9154 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9155 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
9156 << T;
9157 NewVD->setInvalidDecl();
9158 return;
9159 }
9160 }
9161
9162 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9163 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_nonlocal);
9164 NewVD->setInvalidDecl();
9165 return;
9166 }
9167
9168 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9169 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9170 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
9171 NewVD->setInvalidDecl();
9172 return;
9173 }
9174
9175 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9176 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_vm);
9177 NewVD->setInvalidDecl();
9178 return;
9179 }
9180
9181 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9182 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
9183 NewVD->setInvalidDecl();
9184 return;
9185 }
9186
9187 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9188 !T->isDependentType() &&
9189 RequireLiteralType(Loc: NewVD->getLocation(), T,
9190 DiagID: diag::err_constexpr_var_non_literal)) {
9191 NewVD->setInvalidDecl();
9192 return;
9193 }
9194
9195 // PPC MMA non-pointer types are not allowed as non-local variable types.
9196 if (Context.getTargetInfo().getTriple().isPPC64() &&
9197 !NewVD->isLocalVarDecl() &&
9198 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
9199 NewVD->setInvalidDecl();
9200 return;
9201 }
9202
9203 // Check that SVE types are only used in functions with SVE available.
9204 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9205 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9206 llvm::StringMap<bool> CallerFeatureMap;
9207 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9208 if (ARM().checkSVETypeSupport(Ty: T, Loc: NewVD->getLocation(), FD,
9209 FeatureMap: CallerFeatureMap)) {
9210 NewVD->setInvalidDecl();
9211 return;
9212 }
9213 }
9214
9215 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9216 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9217 llvm::StringMap<bool> CallerFeatureMap;
9218 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9219 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9220 FeatureMap: CallerFeatureMap);
9221 }
9222
9223 if (T.hasAddressSpace() &&
9224 !CheckVarDeclSizeAddressSpace(VD: NewVD, AS: T.getAddressSpace())) {
9225 NewVD->setInvalidDecl();
9226 return;
9227 }
9228}
9229
9230bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9231 CheckVariableDeclarationType(NewVD);
9232
9233 // If the decl is already known invalid, don't check it.
9234 if (NewVD->isInvalidDecl())
9235 return false;
9236
9237 // If we did not find anything by this name, look for a non-visible
9238 // extern "C" declaration with the same name.
9239 if (Previous.empty() &&
9240 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9241 Previous.setShadowed();
9242
9243 if (!Previous.empty()) {
9244 MergeVarDecl(New: NewVD, Previous);
9245 return true;
9246 }
9247 return false;
9248}
9249
9250bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9251 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9252
9253 // Look for methods in base classes that this method might override.
9254 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9255 /*DetectVirtual=*/false);
9256 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9257 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9258 DeclarationName Name = MD->getDeclName();
9259
9260 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9261 // We really want to find the base class destructor here.
9262 Name = Context.DeclarationNames.getCXXDestructorName(
9263 Ty: Context.getCanonicalTagType(TD: BaseRecord));
9264 }
9265
9266 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9267 CXXMethodDecl *BaseMD =
9268 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9269 if (!BaseMD || !BaseMD->isVirtual() ||
9270 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9271 /*ConsiderCudaAttrs=*/true))
9272 continue;
9273 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9274 continue;
9275 if (Overridden.insert(Ptr: BaseMD).second) {
9276 MD->addOverriddenMethod(MD: BaseMD);
9277 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9278 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9279 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9280 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9281 }
9282
9283 // A method can only override one function from each base class. We
9284 // don't track indirectly overridden methods from bases of bases.
9285 return true;
9286 }
9287
9288 return false;
9289 };
9290
9291 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9292 return !Overridden.empty();
9293}
9294
9295namespace {
9296 // Struct for holding all of the extra arguments needed by
9297 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9298 struct ActOnFDArgs {
9299 Scope *S;
9300 Declarator &D;
9301 MultiTemplateParamsArg TemplateParamLists;
9302 bool AddToScope;
9303 };
9304} // end anonymous namespace
9305
9306namespace {
9307
9308// Callback to only accept typo corrections that have a non-zero edit distance.
9309// Also only accept corrections that have the same parent decl.
9310class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9311 public:
9312 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9313 CXXRecordDecl *Parent)
9314 : Context(Context), OriginalFD(TypoFD),
9315 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9316
9317 bool ValidateCandidate(const TypoCorrection &candidate) override {
9318 if (candidate.getEditDistance() == 0)
9319 return false;
9320
9321 SmallVector<unsigned, 1> MismatchedParams;
9322 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9323 CDeclEnd = candidate.end();
9324 CDecl != CDeclEnd; ++CDecl) {
9325 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9326
9327 if (FD && !FD->hasBody() &&
9328 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9329 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9330 CXXRecordDecl *Parent = MD->getParent();
9331 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9332 return true;
9333 } else if (!ExpectedParent) {
9334 return true;
9335 }
9336 }
9337 }
9338
9339 return false;
9340 }
9341
9342 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9343 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9344 }
9345
9346 private:
9347 ASTContext &Context;
9348 FunctionDecl *OriginalFD;
9349 CXXRecordDecl *ExpectedParent;
9350};
9351
9352} // end anonymous namespace
9353
9354void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9355 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9356}
9357
9358/// Generate diagnostics for an invalid function redeclaration.
9359///
9360/// This routine handles generating the diagnostic messages for an invalid
9361/// function redeclaration, including finding possible similar declarations
9362/// or performing typo correction if there are no previous declarations with
9363/// the same name.
9364///
9365/// Returns a NamedDecl iff typo correction was performed and substituting in
9366/// the new declaration name does not cause new errors.
9367static NamedDecl *DiagnoseInvalidRedeclaration(
9368 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9369 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9370 DeclarationName Name = NewFD->getDeclName();
9371 DeclContext *NewDC = NewFD->getDeclContext();
9372 SmallVector<unsigned, 1> MismatchedParams;
9373 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9374 TypoCorrection Correction;
9375 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9376 unsigned DiagMsg =
9377 IsLocalFriend ? diag::err_no_matching_local_friend :
9378 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9379 diag::err_member_decl_does_not_match;
9380 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9381 IsLocalFriend ? Sema::LookupLocalFriendName
9382 : Sema::LookupOrdinaryName,
9383 RedeclarationKind::ForVisibleRedeclaration);
9384
9385 NewFD->setInvalidDecl();
9386 if (IsLocalFriend)
9387 SemaRef.LookupName(R&: Prev, S);
9388 else
9389 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9390 assert(!Prev.isAmbiguous() &&
9391 "Cannot have an ambiguity in previous-declaration lookup");
9392 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9393 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9394 MD ? MD->getParent() : nullptr);
9395 if (!Prev.empty()) {
9396 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9397 Func != FuncEnd; ++Func) {
9398 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9399 if (FD &&
9400 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9401 // Add 1 to the index so that 0 can mean the mismatch didn't
9402 // involve a parameter
9403 unsigned ParamNum =
9404 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9405 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9406 }
9407 }
9408 // If the qualified name lookup yielded nothing, try typo correction
9409 } else if ((Correction = SemaRef.CorrectTypo(
9410 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9411 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9412 Mode: CorrectTypoKind::ErrorRecovery,
9413 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9414 // Set up everything for the call to ActOnFunctionDeclarator
9415 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9416 IdLoc: ExtraArgs.D.getIdentifierLoc());
9417 Previous.clear();
9418 Previous.setLookupName(Correction.getCorrection());
9419 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9420 CDeclEnd = Correction.end();
9421 CDecl != CDeclEnd; ++CDecl) {
9422 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9423 if (FD && !FD->hasBody() &&
9424 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9425 Previous.addDecl(D: FD);
9426 }
9427 }
9428 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9429
9430 NamedDecl *Result;
9431 // Retry building the function declaration with the new previous
9432 // declarations, and with errors suppressed.
9433 {
9434 // Trap errors.
9435 Sema::SFINAETrap Trap(SemaRef);
9436
9437 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9438 // pieces need to verify the typo-corrected C++ declaration and hopefully
9439 // eliminate the need for the parameter pack ExtraArgs.
9440 Result = SemaRef.ActOnFunctionDeclarator(
9441 S: ExtraArgs.S, D&: ExtraArgs.D,
9442 DC: Correction.getCorrectionDecl()->getDeclContext(),
9443 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9444 AddToScope&: ExtraArgs.AddToScope);
9445
9446 if (Trap.hasErrorOccurred())
9447 Result = nullptr;
9448 }
9449
9450 if (Result) {
9451 // Determine which correction we picked.
9452 Decl *Canonical = Result->getCanonicalDecl();
9453 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9454 I != E; ++I)
9455 if ((*I)->getCanonicalDecl() == Canonical)
9456 Correction.setCorrectionDecl(*I);
9457
9458 // Let Sema know about the correction.
9459 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9460 SemaRef.diagnoseTypo(
9461 Correction,
9462 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9463 ? diag::err_no_matching_local_friend_suggest
9464 : diag::err_member_decl_does_not_match_suggest)
9465 << Name << NewDC << IsDefinition);
9466 return Result;
9467 }
9468
9469 // Pretend the typo correction never occurred
9470 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9471 IdLoc: ExtraArgs.D.getIdentifierLoc());
9472 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9473 Previous.clear();
9474 Previous.setLookupName(Name);
9475 }
9476
9477 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9478 << Name << NewDC << IsDefinition << NewFD->getLocation();
9479
9480 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9481 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9482 CXXRecordDecl *RD = NewMD->getParent();
9483 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9484 << RD->getName() << RD->getLocation();
9485 }
9486
9487 bool NewFDisConst = NewMD && NewMD->isConst();
9488
9489 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9490 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9491 NearMatch != NearMatchEnd; ++NearMatch) {
9492 FunctionDecl *FD = NearMatch->first;
9493 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9494 bool FDisConst = MD && MD->isConst();
9495 bool IsMember = MD || !IsLocalFriend;
9496
9497 // FIXME: These notes are poorly worded for the local friend case.
9498 if (unsigned Idx = NearMatch->second) {
9499 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9500 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9501 if (Loc.isInvalid()) Loc = FD->getLocation();
9502 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9503 : diag::note_local_decl_close_param_match)
9504 << Idx << FDParam->getType()
9505 << NewFD->getParamDecl(i: Idx - 1)->getType();
9506 } else if (FDisConst != NewFDisConst) {
9507 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9508 DiagID: diag::note_member_def_close_const_match)
9509 << NewFDisConst << FD->getSourceRange().getEnd();
9510 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9511 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9512 Code: " const");
9513 else if (FTI.hasMethodTypeQualifiers() &&
9514 FTI.getConstQualifierLoc().isValid())
9515 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9516 } else {
9517 SemaRef.Diag(Loc: FD->getLocation(),
9518 DiagID: IsMember ? diag::note_member_def_close_match
9519 : diag::note_local_decl_close_match);
9520 }
9521 }
9522 return nullptr;
9523}
9524
9525static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9526 switch (D.getDeclSpec().getStorageClassSpec()) {
9527 default: llvm_unreachable("Unknown storage class!");
9528 case DeclSpec::SCS_auto:
9529 case DeclSpec::SCS_register:
9530 case DeclSpec::SCS_mutable:
9531 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9532 DiagID: diag::err_typecheck_sclass_func);
9533 D.getMutableDeclSpec().ClearStorageClassSpecs();
9534 D.setInvalidType();
9535 break;
9536 case DeclSpec::SCS_unspecified: break;
9537 case DeclSpec::SCS_extern:
9538 if (D.getDeclSpec().isExternInLinkageSpec())
9539 return SC_None;
9540 return SC_Extern;
9541 case DeclSpec::SCS_static: {
9542 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9543 // C99 6.7.1p5:
9544 // The declaration of an identifier for a function that has
9545 // block scope shall have no explicit storage-class specifier
9546 // other than extern
9547 // See also (C++ [dcl.stc]p4).
9548 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9549 DiagID: diag::err_static_block_func);
9550 break;
9551 } else
9552 return SC_Static;
9553 }
9554 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9555 }
9556
9557 // No explicit storage class has already been returned
9558 return SC_None;
9559}
9560
9561static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9562 DeclContext *DC, QualType &R,
9563 TypeSourceInfo *TInfo,
9564 StorageClass SC,
9565 bool &IsVirtualOkay) {
9566 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9567 DeclarationName Name = NameInfo.getName();
9568
9569 FunctionDecl *NewFD = nullptr;
9570 bool isInline = D.getDeclSpec().isInlineSpecified();
9571
9572 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9573 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9574 (SemaRef.getLangOpts().C23 &&
9575 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9576
9577 if (SemaRef.getLangOpts().C23)
9578 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9579 DiagID: diag::err_c23_constexpr_not_variable);
9580 else
9581 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9582 DiagID: diag::err_constexpr_wrong_decl_kind)
9583 << static_cast<int>(ConstexprKind);
9584 ConstexprKind = ConstexprSpecKind::Unspecified;
9585 D.getMutableDeclSpec().ClearConstexprSpec();
9586 }
9587
9588 if (!SemaRef.getLangOpts().CPlusPlus) {
9589 // Determine whether the function was written with a prototype. This is
9590 // true when:
9591 // - there is a prototype in the declarator, or
9592 // - the type R of the function is some kind of typedef or other non-
9593 // attributed reference to a type name (which eventually refers to a
9594 // function type). Note, we can't always look at the adjusted type to
9595 // check this case because attributes may cause a non-function
9596 // declarator to still have a function type. e.g.,
9597 // typedef void func(int a);
9598 // __attribute__((noreturn)) func other_func; // This has a prototype
9599 bool HasPrototype =
9600 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9601 (D.getDeclSpec().isTypeRep() &&
9602 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9603 ->isFunctionProtoType()) ||
9604 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9605 assert(
9606 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9607 "Strict prototypes are required");
9608
9609 NewFD = FunctionDecl::Create(
9610 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9611 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9612 ConstexprKind: ConstexprSpecKind::Unspecified,
9613 /*TrailingRequiresClause=*/{});
9614 if (D.isInvalidType())
9615 NewFD->setInvalidDecl();
9616
9617 return NewFD;
9618 }
9619
9620 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9621 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9622
9623 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9624
9625 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9626 // This is a C++ constructor declaration.
9627 assert(DC->isRecord() &&
9628 "Constructors can only be declared in a member context");
9629
9630 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9631 return CXXConstructorDecl::Create(
9632 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9633 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9634 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9635 Inherited: InheritedConstructor(), TrailingRequiresClause);
9636
9637 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9638 // This is a C++ destructor declaration.
9639 if (DC->isRecord()) {
9640 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9641 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9642 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9643 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9644 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9645 /*isImplicitlyDeclared=*/false, ConstexprKind,
9646 TrailingRequiresClause);
9647 // User defined destructors start as not selected if the class definition is still
9648 // not done.
9649 if (Record->isBeingDefined())
9650 NewDD->setIneligibleOrNotSelected(true);
9651
9652 // If the destructor needs an implicit exception specification, set it
9653 // now. FIXME: It'd be nice to be able to create the right type to start
9654 // with, but the type needs to reference the destructor declaration.
9655 if (SemaRef.getLangOpts().CPlusPlus11)
9656 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9657
9658 IsVirtualOkay = true;
9659 return NewDD;
9660
9661 } else {
9662 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9663 D.setInvalidType();
9664
9665 // Create a FunctionDecl to satisfy the function definition parsing
9666 // code path.
9667 return FunctionDecl::Create(
9668 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9669 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9670 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9671 }
9672
9673 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9674 if (!DC->isRecord()) {
9675 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9676 DiagID: diag::err_conv_function_not_member);
9677 return nullptr;
9678 }
9679
9680 SemaRef.CheckConversionDeclarator(D, R, SC);
9681 if (D.isInvalidType())
9682 return nullptr;
9683
9684 IsVirtualOkay = true;
9685 return CXXConversionDecl::Create(
9686 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9687 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9688 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9689 TrailingRequiresClause);
9690
9691 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9692 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9693 return nullptr;
9694 return CXXDeductionGuideDecl::Create(
9695 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9696 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9697 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9698 } else if (DC->isRecord()) {
9699 // If the name of the function is the same as the name of the record,
9700 // then this must be an invalid constructor that has a return type.
9701 // (The parser checks for a return type and makes the declarator a
9702 // constructor if it has no return type).
9703 if (Name.getAsIdentifierInfo() &&
9704 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9705 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9706 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9707 << SourceRange(D.getIdentifierLoc());
9708 return nullptr;
9709 }
9710
9711 // This is a C++ method declaration.
9712 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9713 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9714 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9715 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9716 IsVirtualOkay = !Ret->isStatic();
9717 return Ret;
9718 } else {
9719 bool isFriend =
9720 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9721 if (!isFriend && SemaRef.CurContext->isRecord())
9722 return nullptr;
9723
9724 // Determine whether the function was written with a
9725 // prototype. This true when:
9726 // - we're in C++ (where every function has a prototype),
9727 return FunctionDecl::Create(
9728 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9729 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9730 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9731 }
9732}
9733
9734enum OpenCLParamType {
9735 ValidKernelParam,
9736 PtrPtrKernelParam,
9737 PtrKernelParam,
9738 InvalidAddrSpacePtrKernelParam,
9739 InvalidKernelParam,
9740 RecordKernelParam
9741};
9742
9743static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9744 // Size dependent types are just typedefs to normal integer types
9745 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9746 // integers other than by their names.
9747 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9748
9749 // Remove typedefs one by one until we reach a typedef
9750 // for a size dependent type.
9751 QualType DesugaredTy = Ty;
9752 do {
9753 ArrayRef<StringRef> Names(SizeTypeNames);
9754 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9755 if (Names.end() != Match)
9756 return true;
9757
9758 Ty = DesugaredTy;
9759 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9760 } while (DesugaredTy != Ty);
9761
9762 return false;
9763}
9764
9765static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9766 if (PT->isDependentType())
9767 return InvalidKernelParam;
9768
9769 if (PT->isPointerOrReferenceType()) {
9770 QualType PointeeType = PT->getPointeeType();
9771 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9772 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9773 PointeeType.getAddressSpace() == LangAS::Default)
9774 return InvalidAddrSpacePtrKernelParam;
9775
9776 if (PointeeType->isPointerType()) {
9777 // This is a pointer to pointer parameter.
9778 // Recursively check inner type.
9779 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9780 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9781 ParamKind == InvalidKernelParam)
9782 return ParamKind;
9783
9784 // OpenCL v3.0 s6.11.a:
9785 // A restriction to pass pointers to pointers only applies to OpenCL C
9786 // v1.2 or below.
9787 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9788 return ValidKernelParam;
9789
9790 return PtrPtrKernelParam;
9791 }
9792
9793 // C++ for OpenCL v1.0 s2.4:
9794 // Moreover the types used in parameters of the kernel functions must be:
9795 // Standard layout types for pointer parameters. The same applies to
9796 // reference if an implementation supports them in kernel parameters.
9797 if (S.getLangOpts().OpenCLCPlusPlus &&
9798 !S.getOpenCLOptions().isAvailableOption(
9799 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9800 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9801 bool IsStandardLayoutType = true;
9802 if (CXXRec) {
9803 // If template type is not ODR-used its definition is only available
9804 // in the template definition not its instantiation.
9805 // FIXME: This logic doesn't work for types that depend on template
9806 // parameter (PR58590).
9807 if (!CXXRec->hasDefinition())
9808 CXXRec = CXXRec->getTemplateInstantiationPattern();
9809 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9810 IsStandardLayoutType = false;
9811 }
9812 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9813 !IsStandardLayoutType)
9814 return InvalidKernelParam;
9815 }
9816
9817 // OpenCL v1.2 s6.9.p:
9818 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9819 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9820 return ValidKernelParam;
9821
9822 return PtrKernelParam;
9823 }
9824
9825 // OpenCL v1.2 s6.9.k:
9826 // Arguments to kernel functions in a program cannot be declared with the
9827 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9828 // uintptr_t or a struct and/or union that contain fields declared to be one
9829 // of these built-in scalar types.
9830 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9831 return InvalidKernelParam;
9832
9833 if (PT->isImageType())
9834 return PtrKernelParam;
9835
9836 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9837 return InvalidKernelParam;
9838
9839 // OpenCL extension spec v1.2 s9.5:
9840 // This extension adds support for half scalar and vector types as built-in
9841 // types that can be used for arithmetic operations, conversions etc.
9842 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9843 PT->isHalfType())
9844 return InvalidKernelParam;
9845
9846 // Look into an array argument to check if it has a forbidden type.
9847 if (PT->isArrayType()) {
9848 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9849 // Call ourself to check an underlying type of an array. Since the
9850 // getPointeeOrArrayElementType returns an innermost type which is not an
9851 // array, this recursive call only happens once.
9852 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9853 }
9854
9855 // C++ for OpenCL v1.0 s2.4:
9856 // Moreover the types used in parameters of the kernel functions must be:
9857 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9858 // types) for parameters passed by value;
9859 if (S.getLangOpts().OpenCLCPlusPlus &&
9860 !S.getOpenCLOptions().isAvailableOption(
9861 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9862 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9863 return InvalidKernelParam;
9864
9865 if (PT->isRecordType())
9866 return RecordKernelParam;
9867
9868 return ValidKernelParam;
9869}
9870
9871static void checkIsValidOpenCLKernelParameter(
9872 Sema &S,
9873 Declarator &D,
9874 ParmVarDecl *Param,
9875 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9876 QualType PT = Param->getType();
9877
9878 // Cache the valid types we encounter to avoid rechecking structs that are
9879 // used again
9880 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9881 return;
9882
9883 switch (getOpenCLKernelParameterType(S, PT)) {
9884 case PtrPtrKernelParam:
9885 // OpenCL v3.0 s6.11.a:
9886 // A kernel function argument cannot be declared as a pointer to a pointer
9887 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9888 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
9889 D.setInvalidType();
9890 return;
9891
9892 case InvalidAddrSpacePtrKernelParam:
9893 // OpenCL v1.0 s6.5:
9894 // __kernel function arguments declared to be a pointer of a type can point
9895 // to one of the following address spaces only : __global, __local or
9896 // __constant.
9897 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
9898 D.setInvalidType();
9899 return;
9900
9901 // OpenCL v1.2 s6.9.k:
9902 // Arguments to kernel functions in a program cannot be declared with the
9903 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9904 // uintptr_t or a struct and/or union that contain fields declared to be
9905 // one of these built-in scalar types.
9906
9907 case InvalidKernelParam:
9908 // OpenCL v1.2 s6.8 n:
9909 // A kernel function argument cannot be declared
9910 // of event_t type.
9911 // Do not diagnose half type since it is diagnosed as invalid argument
9912 // type for any function elsewhere.
9913 if (!PT->isHalfType()) {
9914 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9915
9916 // Explain what typedefs are involved.
9917 const TypedefType *Typedef = nullptr;
9918 while ((Typedef = PT->getAs<TypedefType>())) {
9919 SourceLocation Loc = Typedef->getDecl()->getLocation();
9920 // SourceLocation may be invalid for a built-in type.
9921 if (Loc.isValid())
9922 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
9923 PT = Typedef->desugar();
9924 }
9925 }
9926
9927 D.setInvalidType();
9928 return;
9929
9930 case PtrKernelParam:
9931 case ValidKernelParam:
9932 ValidTypes.insert(Ptr: PT.getTypePtr());
9933 return;
9934
9935 case RecordKernelParam:
9936 break;
9937 }
9938
9939 // Track nested structs we will inspect
9940 SmallVector<const Decl *, 4> VisitStack;
9941
9942 // Track where we are in the nested structs. Items will migrate from
9943 // VisitStack to HistoryStack as we do the DFS for bad field.
9944 SmallVector<const FieldDecl *, 4> HistoryStack;
9945 HistoryStack.push_back(Elt: nullptr);
9946
9947 // At this point we already handled everything except of a RecordType.
9948 assert(PT->isRecordType() && "Unexpected type.");
9949 const auto *PD = PT->castAsRecordDecl();
9950 VisitStack.push_back(Elt: PD);
9951 assert(VisitStack.back() && "First decl null?");
9952
9953 do {
9954 const Decl *Next = VisitStack.pop_back_val();
9955 if (!Next) {
9956 assert(!HistoryStack.empty());
9957 // Found a marker, we have gone up a level
9958 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9959 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
9960
9961 continue;
9962 }
9963
9964 // Adds everything except the original parameter declaration (which is not a
9965 // field itself) to the history stack.
9966 const RecordDecl *RD;
9967 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
9968 HistoryStack.push_back(Elt: Field);
9969
9970 QualType FieldTy = Field->getType();
9971 // Other field types (known to be valid or invalid) are handled while we
9972 // walk around RecordDecl::fields().
9973 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9974 "Unexpected type.");
9975 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9976
9977 RD = FieldRecTy->castAsRecordDecl();
9978 } else {
9979 RD = cast<RecordDecl>(Val: Next);
9980 }
9981
9982 // Add a null marker so we know when we've gone back up a level
9983 VisitStack.push_back(Elt: nullptr);
9984
9985 for (const auto *FD : RD->fields()) {
9986 QualType QT = FD->getType();
9987
9988 if (ValidTypes.count(Ptr: QT.getTypePtr()))
9989 continue;
9990
9991 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
9992 if (ParamType == ValidKernelParam)
9993 continue;
9994
9995 if (ParamType == RecordKernelParam) {
9996 VisitStack.push_back(Elt: FD);
9997 continue;
9998 }
9999
10000 // OpenCL v1.2 s6.9.p:
10001 // Arguments to kernel functions that are declared to be a struct or union
10002 // do not allow OpenCL objects to be passed as elements of the struct or
10003 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10004 // of SVM.
10005 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10006 ParamType == InvalidAddrSpacePtrKernelParam) {
10007 S.Diag(Loc: Param->getLocation(),
10008 DiagID: diag::err_record_with_pointers_kernel_param)
10009 << PT->isUnionType()
10010 << PT;
10011 } else {
10012 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10013 }
10014
10015 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
10016 << PD->getDeclName();
10017
10018 // We have an error, now let's go back up through history and show where
10019 // the offending field came from
10020 for (ArrayRef<const FieldDecl *>::const_iterator
10021 I = HistoryStack.begin() + 1,
10022 E = HistoryStack.end();
10023 I != E; ++I) {
10024 const FieldDecl *OuterField = *I;
10025 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
10026 << OuterField->getType();
10027 }
10028
10029 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
10030 << QT->isPointerType()
10031 << QT;
10032 D.setInvalidType();
10033 return;
10034 }
10035 } while (!VisitStack.empty());
10036}
10037
10038/// Find the DeclContext in which a tag is implicitly declared if we see an
10039/// elaborated type specifier in the specified context, and lookup finds
10040/// nothing.
10041static DeclContext *getTagInjectionContext(DeclContext *DC) {
10042 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10043 DC = DC->getParent();
10044 return DC;
10045}
10046
10047/// Find the Scope in which a tag is implicitly declared if we see an
10048/// elaborated type specifier in the specified context, and lookup finds
10049/// nothing.
10050static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10051 while (S->isClassScope() ||
10052 (LangOpts.CPlusPlus &&
10053 S->isFunctionPrototypeScope()) ||
10054 ((S->getFlags() & Scope::DeclScope) == 0) ||
10055 (S->getEntity() && S->getEntity()->isTransparentContext()))
10056 S = S->getParent();
10057 return S;
10058}
10059
10060/// Determine whether a declaration matches a known function in namespace std.
10061static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10062 unsigned BuiltinID) {
10063 switch (BuiltinID) {
10064 case Builtin::BI__GetExceptionInfo:
10065 // No type checking whatsoever.
10066 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10067
10068 case Builtin::BIaddressof:
10069 case Builtin::BI__addressof:
10070 case Builtin::BIforward:
10071 case Builtin::BIforward_like:
10072 case Builtin::BImove:
10073 case Builtin::BImove_if_noexcept:
10074 case Builtin::BIas_const: {
10075 // Ensure that we don't treat the algorithm
10076 // OutputIt std::move(InputIt, InputIt, OutputIt)
10077 // as the builtin std::move.
10078 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10079 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10080 }
10081
10082 default:
10083 return false;
10084 }
10085}
10086
10087NamedDecl*
10088Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10089 TypeSourceInfo *TInfo, LookupResult &Previous,
10090 MultiTemplateParamsArg TemplateParamListsRef,
10091 bool &AddToScope) {
10092 QualType R = TInfo->getType();
10093
10094 assert(R->isFunctionType());
10095 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10096 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
10097
10098 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10099 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
10100 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10101 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10102 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10103 TemplateParamLists.back() = Invented;
10104 else
10105 TemplateParamLists.push_back(Elt: Invented);
10106 }
10107
10108 // TODO: consider using NameInfo for diagnostic.
10109 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10110 DeclarationName Name = NameInfo.getName();
10111 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
10112
10113 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10114 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
10115 DiagID: diag::err_invalid_thread)
10116 << DeclSpec::getSpecifierName(S: TSCS);
10117
10118 if (D.isFirstDeclarationOfMember())
10119 adjustMemberFunctionCC(
10120 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10121 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
10122
10123 bool isFriend = false;
10124 FunctionTemplateDecl *FunctionTemplate = nullptr;
10125 bool isMemberSpecialization = false;
10126 bool isFunctionTemplateSpecialization = false;
10127
10128 bool HasExplicitTemplateArgs = false;
10129 TemplateArgumentListInfo TemplateArgs;
10130
10131 bool isVirtualOkay = false;
10132
10133 DeclContext *OriginalDC = DC;
10134 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10135
10136 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
10137 IsVirtualOkay&: isVirtualOkay);
10138 if (!NewFD) return nullptr;
10139
10140 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10141 NewFD->setTopLevelDeclInObjCContainer();
10142
10143 // Set the lexical context. If this is a function-scope declaration, or has a
10144 // C++ scope specifier, or is the object of a friend declaration, the lexical
10145 // context will be different from the semantic context.
10146 NewFD->setLexicalDeclContext(CurContext);
10147
10148 if (IsLocalExternDecl)
10149 NewFD->setLocalExternDecl();
10150
10151 if (getLangOpts().CPlusPlus) {
10152 // The rules for implicit inlines changed in C++20 for methods and friends
10153 // with an in-class definition (when such a definition is not attached to
10154 // the global module). This does not affect declarations that are already
10155 // inline (whether explicitly or implicitly by being declared constexpr,
10156 // consteval, etc).
10157 // FIXME: We need a better way to separate C++ standard and clang modules.
10158 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10159 !NewFD->getOwningModule() ||
10160 NewFD->isFromGlobalModule() ||
10161 NewFD->getOwningModule()->isHeaderLikeModule();
10162 bool isInline = D.getDeclSpec().isInlineSpecified();
10163 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10164 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10165 isFriend = D.getDeclSpec().isFriendSpecified();
10166 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10167 // Pre-C++20 [class.friend]p5
10168 // A function can be defined in a friend declaration of a
10169 // class . . . . Such a function is implicitly inline.
10170 // Post C++20 [class.friend]p7
10171 // Such a function is implicitly an inline function if it is attached
10172 // to the global module.
10173 NewFD->setImplicitlyInline();
10174 }
10175
10176 // If this is a method defined in an __interface, and is not a constructor
10177 // or an overloaded operator, then set the pure flag (isVirtual will already
10178 // return true).
10179 if (const CXXRecordDecl *Parent =
10180 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
10181 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
10182 NewFD->setIsPureVirtual(true);
10183
10184 // C++ [class.union]p2
10185 // A union can have member functions, but not virtual functions.
10186 if (isVirtual && Parent->isUnion()) {
10187 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
10188 NewFD->setInvalidDecl();
10189 }
10190 if ((Parent->isClass() || Parent->isStruct()) &&
10191 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10192 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10193 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10194 if (auto *Def = Parent->getDefinition())
10195 Def->setInitMethod(true);
10196 }
10197 }
10198
10199 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
10200 isMemberSpecialization = false;
10201 isFunctionTemplateSpecialization = false;
10202 if (D.isInvalidType())
10203 NewFD->setInvalidDecl();
10204
10205 // Match up the template parameter lists with the scope specifier, then
10206 // determine whether we have a template or a template specialization.
10207 bool Invalid = false;
10208 TemplateIdAnnotation *TemplateId =
10209 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10210 ? D.getName().TemplateId
10211 : nullptr;
10212 TemplateParameterList *TemplateParams =
10213 MatchTemplateParametersToScopeSpecifier(
10214 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10215 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10216 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10217 if (TemplateParams) {
10218 // Check that we can declare a template here.
10219 if (CheckTemplateDeclScope(S, TemplateParams))
10220 NewFD->setInvalidDecl();
10221
10222 if (TemplateParams->size() > 0) {
10223 // This is a function template
10224
10225 // A destructor cannot be a template.
10226 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10227 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10228 NewFD->setInvalidDecl();
10229 // Function template with explicit template arguments.
10230 } else if (TemplateId) {
10231 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10232 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10233 NewFD->setInvalidDecl();
10234 }
10235
10236 // If we're adding a template to a dependent context, we may need to
10237 // rebuilding some of the types used within the template parameter list,
10238 // now that we know what the current instantiation is.
10239 if (DC->isDependentContext()) {
10240 ContextRAII SavedContext(*this, DC);
10241 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10242 Invalid = true;
10243 }
10244
10245 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10246 L: NewFD->getLocation(),
10247 Name, Params: TemplateParams,
10248 Decl: NewFD);
10249 FunctionTemplate->setLexicalDeclContext(CurContext);
10250 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10251
10252 // For source fidelity, store the other template param lists.
10253 if (TemplateParamLists.size() > 1) {
10254 NewFD->setTemplateParameterListsInfo(Context,
10255 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10256 .drop_back(N: 1));
10257 }
10258 } else {
10259 // This is a function template specialization.
10260 isFunctionTemplateSpecialization = true;
10261 // For source fidelity, store all the template param lists.
10262 if (TemplateParamLists.size() > 0)
10263 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10264
10265 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10266 if (isFriend) {
10267 // We want to remove the "template<>", found here.
10268 SourceRange RemoveRange = TemplateParams->getSourceRange();
10269
10270 // If we remove the template<> and the name is not a
10271 // template-id, we're actually silently creating a problem:
10272 // the friend declaration will refer to an untemplated decl,
10273 // and clearly the user wants a template specialization. So
10274 // we need to insert '<>' after the name.
10275 SourceLocation InsertLoc;
10276 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10277 InsertLoc = D.getName().getSourceRange().getEnd();
10278 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10279 }
10280
10281 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10282 << Name << RemoveRange
10283 << FixItHint::CreateRemoval(RemoveRange)
10284 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10285 Invalid = true;
10286
10287 // Recover by faking up an empty template argument list.
10288 HasExplicitTemplateArgs = true;
10289 TemplateArgs.setLAngleLoc(InsertLoc);
10290 TemplateArgs.setRAngleLoc(InsertLoc);
10291 }
10292 }
10293 } else {
10294 // Check that we can declare a template here.
10295 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10296 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10297 NewFD->setInvalidDecl();
10298
10299 // All template param lists were matched against the scope specifier:
10300 // this is NOT (an explicit specialization of) a template.
10301 if (TemplateParamLists.size() > 0)
10302 // For source fidelity, store all the template param lists.
10303 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10304
10305 // "friend void foo<>(int);" is an implicit specialization decl.
10306 if (isFriend && TemplateId)
10307 isFunctionTemplateSpecialization = true;
10308 }
10309
10310 // If this is a function template specialization and the unqualified-id of
10311 // the declarator-id is a template-id, convert the template argument list
10312 // into our AST format and check for unexpanded packs.
10313 if (isFunctionTemplateSpecialization && TemplateId) {
10314 HasExplicitTemplateArgs = true;
10315
10316 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10317 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10318 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10319 TemplateId->NumArgs);
10320 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10321
10322 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10323 // declaration of a function template partial specialization? Should we
10324 // consider the unexpanded pack context to be a partial specialization?
10325 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10326 if (DiagnoseUnexpandedParameterPack(
10327 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10328 : UPPC_ExplicitSpecialization))
10329 NewFD->setInvalidDecl();
10330 }
10331 }
10332
10333 if (Invalid) {
10334 NewFD->setInvalidDecl();
10335 if (FunctionTemplate)
10336 FunctionTemplate->setInvalidDecl();
10337 }
10338
10339 // C++ [dcl.fct.spec]p5:
10340 // The virtual specifier shall only be used in declarations of
10341 // nonstatic class member functions that appear within a
10342 // member-specification of a class declaration; see 10.3.
10343 //
10344 if (isVirtual && !NewFD->isInvalidDecl()) {
10345 if (!isVirtualOkay) {
10346 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10347 DiagID: diag::err_virtual_non_function);
10348 } else if (!CurContext->isRecord()) {
10349 // 'virtual' was specified outside of the class.
10350 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10351 DiagID: diag::err_virtual_out_of_class)
10352 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10353 } else if (NewFD->getDescribedFunctionTemplate()) {
10354 // C++ [temp.mem]p3:
10355 // A member function template shall not be virtual.
10356 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10357 DiagID: diag::err_virtual_member_function_template)
10358 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10359 } else {
10360 // Okay: Add virtual to the method.
10361 NewFD->setVirtualAsWritten(true);
10362 }
10363
10364 if (getLangOpts().CPlusPlus14 &&
10365 NewFD->getReturnType()->isUndeducedType())
10366 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10367 }
10368
10369 // C++ [dcl.fct.spec]p3:
10370 // The inline specifier shall not appear on a block scope function
10371 // declaration.
10372 if (isInline && !NewFD->isInvalidDecl()) {
10373 if (CurContext->isFunctionOrMethod()) {
10374 // 'inline' is not allowed on block scope function declaration.
10375 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10376 DiagID: diag::err_inline_declaration_block_scope) << Name
10377 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10378 }
10379 }
10380
10381 // C++ [dcl.fct.spec]p6:
10382 // The explicit specifier shall be used only in the declaration of a
10383 // constructor or conversion function within its class definition;
10384 // see 12.3.1 and 12.3.2.
10385 if (hasExplicit && !NewFD->isInvalidDecl() &&
10386 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10387 if (!CurContext->isRecord()) {
10388 // 'explicit' was specified outside of the class.
10389 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10390 DiagID: diag::err_explicit_out_of_class)
10391 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10392 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10393 !isa<CXXConversionDecl>(Val: NewFD)) {
10394 // 'explicit' was specified on a function that wasn't a constructor
10395 // or conversion function.
10396 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10397 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10398 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10399 }
10400 }
10401
10402 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10403 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10404 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10405 // are implicitly inline.
10406 NewFD->setImplicitlyInline();
10407
10408 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10409 // be either constructors or to return a literal type. Therefore,
10410 // destructors cannot be declared constexpr.
10411 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10412 (!getLangOpts().CPlusPlus20 ||
10413 ConstexprKind == ConstexprSpecKind::Consteval)) {
10414 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10415 << static_cast<int>(ConstexprKind);
10416 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10417 ? ConstexprSpecKind::Unspecified
10418 : ConstexprSpecKind::Constexpr);
10419 }
10420 // C++20 [dcl.constexpr]p2: An allocation function, or a
10421 // deallocation function shall not be declared with the consteval
10422 // specifier.
10423 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10424 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10425 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10426 DiagID: diag::err_invalid_consteval_decl_kind)
10427 << NewFD;
10428 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10429 }
10430 }
10431
10432 // If __module_private__ was specified, mark the function accordingly.
10433 if (D.getDeclSpec().isModulePrivateSpecified()) {
10434 if (isFunctionTemplateSpecialization) {
10435 SourceLocation ModulePrivateLoc
10436 = D.getDeclSpec().getModulePrivateSpecLoc();
10437 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10438 << 0
10439 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10440 } else {
10441 NewFD->setModulePrivate();
10442 if (FunctionTemplate)
10443 FunctionTemplate->setModulePrivate();
10444 }
10445 }
10446
10447 if (isFriend) {
10448 if (FunctionTemplate) {
10449 FunctionTemplate->setObjectOfFriendDecl();
10450 FunctionTemplate->setAccess(AS_public);
10451 }
10452 NewFD->setObjectOfFriendDecl();
10453 NewFD->setAccess(AS_public);
10454 }
10455
10456 // If a function is defined as defaulted or deleted, mark it as such now.
10457 // We'll do the relevant checks on defaulted / deleted functions later.
10458 switch (D.getFunctionDefinitionKind()) {
10459 case FunctionDefinitionKind::Declaration:
10460 case FunctionDefinitionKind::Definition:
10461 break;
10462
10463 case FunctionDefinitionKind::Defaulted:
10464 NewFD->setDefaulted();
10465 break;
10466
10467 case FunctionDefinitionKind::Deleted:
10468 NewFD->setDeletedAsWritten();
10469 break;
10470 }
10471
10472 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10473 D.isFunctionDefinition()) {
10474 // Pre C++20 [class.mfct]p2:
10475 // A member function may be defined (8.4) in its class definition, in
10476 // which case it is an inline member function (7.1.2)
10477 // Post C++20 [class.mfct]p1:
10478 // If a member function is attached to the global module and is defined
10479 // in its class definition, it is inline.
10480 NewFD->setImplicitlyInline();
10481 }
10482
10483 if (!isFriend && SC != SC_None) {
10484 // C++ [temp.expl.spec]p2:
10485 // The declaration in an explicit-specialization shall not be an
10486 // export-declaration. An explicit specialization shall not use a
10487 // storage-class-specifier other than thread_local.
10488 //
10489 // We diagnose friend declarations with storage-class-specifiers
10490 // elsewhere.
10491 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10492 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10493 DiagID: diag::ext_explicit_specialization_storage_class)
10494 << FixItHint::CreateRemoval(
10495 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10496 }
10497
10498 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10499 assert(isa<CXXMethodDecl>(NewFD) &&
10500 "Out-of-line member function should be a CXXMethodDecl");
10501 // C++ [class.static]p1:
10502 // A data or function member of a class may be declared static
10503 // in a class definition, in which case it is a static member of
10504 // the class.
10505
10506 // Complain about the 'static' specifier if it's on an out-of-line
10507 // member function definition.
10508
10509 // MSVC permits the use of a 'static' storage specifier on an
10510 // out-of-line member function template declaration and class member
10511 // template declaration (MSVC versions before 2015), warn about this.
10512 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10513 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10514 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10515 (getLangOpts().MSVCCompat &&
10516 NewFD->getDescribedFunctionTemplate()))
10517 ? diag::ext_static_out_of_line
10518 : diag::err_static_out_of_line)
10519 << FixItHint::CreateRemoval(
10520 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10521 }
10522 }
10523
10524 // C++11 [except.spec]p15:
10525 // A deallocation function with no exception-specification is treated
10526 // as if it were specified with noexcept(true).
10527 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10528 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10529 !FPT->hasExceptionSpec())
10530 NewFD->setType(Context.getFunctionType(
10531 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10532 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10533
10534 // C++20 [dcl.inline]/7
10535 // If an inline function or variable that is attached to a named module
10536 // is declared in a definition domain, it shall be defined in that
10537 // domain.
10538 // So, if the current declaration does not have a definition, we must
10539 // check at the end of the TU (or when the PMF starts) to see that we
10540 // have a definition at that point.
10541 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10542 NewFD->isInNamedModule()) {
10543 PendingInlineFuncDecls.insert(Ptr: NewFD);
10544 }
10545 }
10546
10547 // Filter out previous declarations that don't match the scope.
10548 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10549 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10550 isMemberSpecialization ||
10551 isFunctionTemplateSpecialization);
10552
10553 LoadExternalExtnameUndeclaredIdentifiers();
10554
10555 // Handle GNU asm-label extension (encoded as an attribute).
10556 if (Expr *E = D.getAsmLabel()) {
10557 // The parser guarantees this is a string.
10558 StringLiteral *SE = cast<StringLiteral>(Val: E);
10559 NewFD->addAttr(
10560 A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), Range: SE->getStrTokenLoc(TokNum: 0)));
10561 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10562 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10563 ExtnameUndeclaredIdentifiers.find(Val: NewFD->getIdentifier());
10564 if (I != ExtnameUndeclaredIdentifiers.end()) {
10565 if (isDeclExternC(D: NewFD)) {
10566 NewFD->addAttr(A: I->second);
10567 ExtnameUndeclaredIdentifiers.erase(I);
10568 } else if (NewFD->getDeclContext()
10569 ->getRedeclContext()
10570 ->isTranslationUnit())
10571 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10572 << /*Variable*/0 << NewFD;
10573 }
10574 }
10575
10576 // Copy the parameter declarations from the declarator D to the function
10577 // declaration NewFD, if they are available. First scavenge them into Params.
10578 SmallVector<ParmVarDecl*, 16> Params;
10579 unsigned FTIIdx;
10580 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10581 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10582
10583 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10584 // function that takes no arguments, not a function that takes a
10585 // single void argument.
10586 // We let through "const void" here because Sema::GetTypeForDeclarator
10587 // already checks for that case.
10588 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10589 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10590 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10591 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10592 Param->setDeclContext(NewFD);
10593 Params.push_back(Elt: Param);
10594
10595 if (Param->isInvalidDecl())
10596 NewFD->setInvalidDecl();
10597 }
10598 }
10599
10600 if (!getLangOpts().CPlusPlus) {
10601 // In C, find all the tag declarations from the prototype and move them
10602 // into the function DeclContext. Remove them from the surrounding tag
10603 // injection context of the function, which is typically but not always
10604 // the TU.
10605 DeclContext *PrototypeTagContext =
10606 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10607 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10608 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10609
10610 // We don't want to reparent enumerators. Look at their parent enum
10611 // instead.
10612 if (!TD) {
10613 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10614 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10615 }
10616 if (!TD)
10617 continue;
10618 DeclContext *TagDC = TD->getLexicalDeclContext();
10619 if (!TagDC->containsDecl(D: TD))
10620 continue;
10621 TagDC->removeDecl(D: TD);
10622 TD->setDeclContext(NewFD);
10623 NewFD->addDecl(D: TD);
10624
10625 // Preserve the lexical DeclContext if it is not the surrounding tag
10626 // injection context of the FD. In this example, the semantic context of
10627 // E will be f and the lexical context will be S, while both the
10628 // semantic and lexical contexts of S will be f:
10629 // void f(struct S { enum E { a } f; } s);
10630 if (TagDC != PrototypeTagContext)
10631 TD->setLexicalDeclContext(TagDC);
10632 }
10633 }
10634 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10635 // When we're declaring a function with a typedef, typeof, etc as in the
10636 // following example, we'll need to synthesize (unnamed)
10637 // parameters for use in the declaration.
10638 //
10639 // @code
10640 // typedef void fn(int);
10641 // fn f;
10642 // @endcode
10643
10644 // Synthesize a parameter for each argument type.
10645 for (const auto &AI : FT->param_types()) {
10646 ParmVarDecl *Param =
10647 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10648 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10649 Params.push_back(Elt: Param);
10650 }
10651 } else {
10652 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10653 "Should not need args for typedef of non-prototype fn");
10654 }
10655
10656 // Finally, we know we have the right number of parameters, install them.
10657 NewFD->setParams(Params);
10658
10659 // If this declarator is a declaration and not a definition, its parameters
10660 // will not be pushed onto a scope chain. That means we will not issue any
10661 // reserved identifier warnings for the declaration, but we will for the
10662 // definition. Handle those here.
10663 if (!D.isFunctionDefinition()) {
10664 for (const ParmVarDecl *PVD : Params)
10665 warnOnReservedIdentifier(D: PVD);
10666 }
10667
10668 if (D.getDeclSpec().isNoreturnSpecified())
10669 NewFD->addAttr(
10670 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10671
10672 // Functions returning a variably modified type violate C99 6.7.5.2p2
10673 // because all functions have linkage.
10674 if (!NewFD->isInvalidDecl() &&
10675 NewFD->getReturnType()->isVariablyModifiedType()) {
10676 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10677 NewFD->setInvalidDecl();
10678 }
10679
10680 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10681 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10682 !NewFD->hasAttr<SectionAttr>())
10683 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10684 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10685 Range: PragmaClangTextSection.PragmaLocation));
10686
10687 // Apply an implicit SectionAttr if #pragma code_seg is active.
10688 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10689 !NewFD->hasAttr<SectionAttr>()) {
10690 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10691 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10692 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10693 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10694 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10695 ASTContext::PSF_Read,
10696 TheDecl: NewFD))
10697 NewFD->dropAttr<SectionAttr>();
10698 }
10699
10700 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10701 // active.
10702 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10703 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10704 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10705 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10706
10707 // Apply an implicit CodeSegAttr from class declspec or
10708 // apply an implicit SectionAttr from #pragma code_seg if active.
10709 if (!NewFD->hasAttr<CodeSegAttr>()) {
10710 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10711 IsDefinition: D.isFunctionDefinition())) {
10712 NewFD->addAttr(A: SAttr);
10713 }
10714 }
10715
10716 // Handle attributes.
10717 ProcessDeclAttributes(S, D: NewFD, PD: D);
10718 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10719 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10720 !NewTVA->isDefaultVersion() &&
10721 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10722 // Don't add to scope fmv functions declarations if fmv disabled
10723 AddToScope = false;
10724 return NewFD;
10725 }
10726
10727 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10728 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10729 // type.
10730 //
10731 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10732 // type declaration will generate a compilation error.
10733 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10734 if (AddressSpace != LangAS::Default) {
10735 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10736 NewFD->setInvalidDecl();
10737 }
10738 }
10739
10740 if (!getLangOpts().CPlusPlus) {
10741 // Perform semantic checking on the function declaration.
10742 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10743 CheckMain(FD: NewFD, D: D.getDeclSpec());
10744
10745 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10746 CheckMSVCRTEntryPoint(FD: NewFD);
10747
10748 if (!NewFD->isInvalidDecl())
10749 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10750 IsMemberSpecialization: isMemberSpecialization,
10751 DeclIsDefn: D.isFunctionDefinition()));
10752 else if (!Previous.empty())
10753 // Recover gracefully from an invalid redeclaration.
10754 D.setRedeclaration(true);
10755 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10756 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10757 "previous declaration set still overloaded");
10758
10759 // Diagnose no-prototype function declarations with calling conventions that
10760 // don't support variadic calls. Only do this in C and do it after merging
10761 // possibly prototyped redeclarations.
10762 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10763 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10764 CallingConv CC = FT->getExtInfo().getCC();
10765 if (!supportsVariadicCall(CC)) {
10766 // Windows system headers sometimes accidentally use stdcall without
10767 // (void) parameters, so we relax this to a warning.
10768 int DiagID =
10769 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10770 Diag(Loc: NewFD->getLocation(), DiagID)
10771 << FunctionType::getNameForCallConv(CC);
10772 }
10773 }
10774
10775 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10776 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10777 checkNonTrivialCUnion(
10778 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10779 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10780 } else {
10781 // C++11 [replacement.functions]p3:
10782 // The program's definitions shall not be specified as inline.
10783 //
10784 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10785 //
10786 // Suppress the diagnostic if the function is __attribute__((used)), since
10787 // that forces an external definition to be emitted.
10788 if (D.getDeclSpec().isInlineSpecified() &&
10789 NewFD->isReplaceableGlobalAllocationFunction() &&
10790 !NewFD->hasAttr<UsedAttr>())
10791 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10792 DiagID: diag::ext_operator_new_delete_declared_inline)
10793 << NewFD->getDeclName();
10794
10795 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10796 // C++20 [dcl.decl.general]p4:
10797 // The optional requires-clause in an init-declarator or
10798 // member-declarator shall be present only if the declarator declares a
10799 // templated function.
10800 //
10801 // C++20 [temp.pre]p8:
10802 // An entity is templated if it is
10803 // - a template,
10804 // - an entity defined or created in a templated entity,
10805 // - a member of a templated entity,
10806 // - an enumerator for an enumeration that is a templated entity, or
10807 // - the closure type of a lambda-expression appearing in the
10808 // declaration of a templated entity.
10809 //
10810 // [Note 6: A local class, a local or block variable, or a friend
10811 // function defined in a templated entity is a templated entity.
10812 // — end note]
10813 //
10814 // A templated function is a function template or a function that is
10815 // templated. A templated class is a class template or a class that is
10816 // templated. A templated variable is a variable template or a variable
10817 // that is templated.
10818 if (!FunctionTemplate) {
10819 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10820 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10821 // An explicit specialization shall not have a trailing
10822 // requires-clause unless it declares a function template.
10823 //
10824 // Since a friend function template specialization cannot be
10825 // definition, and since a non-template friend declaration with a
10826 // trailing requires-clause must be a definition, we diagnose
10827 // friend function template specializations with trailing
10828 // requires-clauses on the same path as explicit specializations
10829 // even though they aren't necessarily prohibited by the same
10830 // language rule.
10831 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
10832 << isFriend;
10833 } else if (isFriend && NewFD->isTemplated() &&
10834 !D.isFunctionDefinition()) {
10835 // C++ [temp.friend]p9:
10836 // A non-template friend declaration with a requires-clause shall be
10837 // a definition.
10838 Diag(Loc: NewFD->getBeginLoc(),
10839 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10840 NewFD->setInvalidDecl();
10841 } else if (!NewFD->isTemplated() ||
10842 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10843 Diag(Loc: TRC->getBeginLoc(),
10844 DiagID: diag::err_constrained_non_templated_function);
10845 }
10846 }
10847 }
10848
10849 // We do not add HD attributes to specializations here because
10850 // they may have different constexpr-ness compared to their
10851 // templates and, after maybeAddHostDeviceAttrs() is applied,
10852 // may end up with different effective targets. Instead, a
10853 // specialization inherits its target attributes from its template
10854 // in the CheckFunctionTemplateSpecialization() call below.
10855 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10856 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
10857
10858 // Handle explicit specializations of function templates
10859 // and friend function declarations with an explicit
10860 // template argument list.
10861 if (isFunctionTemplateSpecialization) {
10862 bool isDependentSpecialization = false;
10863 if (isFriend) {
10864 // For friend function specializations, this is a dependent
10865 // specialization if its semantic context is dependent, its
10866 // type is dependent, or if its template-id is dependent.
10867 isDependentSpecialization =
10868 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10869 (HasExplicitTemplateArgs &&
10870 TemplateSpecializationType::
10871 anyInstantiationDependentTemplateArguments(
10872 Args: TemplateArgs.arguments()));
10873 assert((!isDependentSpecialization ||
10874 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10875 "dependent friend function specialization without template "
10876 "args");
10877 } else {
10878 // For class-scope explicit specializations of function templates,
10879 // if the lexical context is dependent, then the specialization
10880 // is dependent.
10881 isDependentSpecialization =
10882 CurContext->isRecord() && CurContext->isDependentContext();
10883 }
10884
10885 TemplateArgumentListInfo *ExplicitTemplateArgs =
10886 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10887 if (isDependentSpecialization) {
10888 // If it's a dependent specialization, it may not be possible
10889 // to determine the primary template (for explicit specializations)
10890 // or befriended declaration (for friends) until the enclosing
10891 // template is instantiated. In such cases, we store the declarations
10892 // found by name lookup and defer resolution until instantiation.
10893 if (CheckDependentFunctionTemplateSpecialization(
10894 FD: NewFD, ExplicitTemplateArgs, Previous))
10895 NewFD->setInvalidDecl();
10896 } else if (!NewFD->isInvalidDecl()) {
10897 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
10898 Previous))
10899 NewFD->setInvalidDecl();
10900 }
10901 } else if (isMemberSpecialization && !FunctionTemplate) {
10902 if (CheckMemberSpecialization(Member: NewFD, Previous))
10903 NewFD->setInvalidDecl();
10904 }
10905
10906 // Perform semantic checking on the function declaration.
10907 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10908 CheckMain(FD: NewFD, D: D.getDeclSpec());
10909
10910 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10911 CheckMSVCRTEntryPoint(FD: NewFD);
10912
10913 if (!NewFD->isInvalidDecl())
10914 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10915 IsMemberSpecialization: isMemberSpecialization,
10916 DeclIsDefn: D.isFunctionDefinition()));
10917 else if (!Previous.empty())
10918 // Recover gracefully from an invalid redeclaration.
10919 D.setRedeclaration(true);
10920
10921 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10922 !D.isRedeclaration() ||
10923 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10924 "previous declaration set still overloaded");
10925
10926 NamedDecl *PrincipalDecl = (FunctionTemplate
10927 ? cast<NamedDecl>(Val: FunctionTemplate)
10928 : NewFD);
10929
10930 if (isFriend && NewFD->getPreviousDecl()) {
10931 AccessSpecifier Access = AS_public;
10932 if (!NewFD->isInvalidDecl())
10933 Access = NewFD->getPreviousDecl()->getAccess();
10934
10935 NewFD->setAccess(Access);
10936 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10937 }
10938
10939 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10940 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
10941 PrincipalDecl->setNonMemberOperator();
10942
10943 // If we have a function template, check the template parameter
10944 // list. This will check and merge default template arguments.
10945 if (FunctionTemplate) {
10946 FunctionTemplateDecl *PrevTemplate =
10947 FunctionTemplate->getPreviousDecl();
10948 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
10949 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
10950 : nullptr,
10951 TPC: D.getDeclSpec().isFriendSpecified()
10952 ? (D.isFunctionDefinition()
10953 ? TPC_FriendFunctionTemplateDefinition
10954 : TPC_FriendFunctionTemplate)
10955 : (D.getCXXScopeSpec().isSet() &&
10956 DC && DC->isRecord() &&
10957 DC->isDependentContext())
10958 ? TPC_ClassTemplateMember
10959 : TPC_FunctionTemplate);
10960 }
10961
10962 if (NewFD->isInvalidDecl()) {
10963 // Ignore all the rest of this.
10964 } else if (!D.isRedeclaration()) {
10965 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
10966 .AddToScope: AddToScope };
10967 // Fake up an access specifier if it's supposed to be a class member.
10968 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
10969 NewFD->setAccess(AS_public);
10970
10971 // Qualified decls generally require a previous declaration.
10972 if (D.getCXXScopeSpec().isSet()) {
10973 // ...with the major exception of templated-scope or
10974 // dependent-scope friend declarations.
10975
10976 // TODO: we currently also suppress this check in dependent
10977 // contexts because (1) the parameter depth will be off when
10978 // matching friend templates and (2) we might actually be
10979 // selecting a friend based on a dependent factor. But there
10980 // are situations where these conditions don't apply and we
10981 // can actually do this check immediately.
10982 //
10983 // Unless the scope is dependent, it's always an error if qualified
10984 // redeclaration lookup found nothing at all. Diagnose that now;
10985 // nothing will diagnose that error later.
10986 if (isFriend &&
10987 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
10988 (!Previous.empty() && CurContext->isDependentContext()))) {
10989 // ignore these
10990 } else if (NewFD->isCPUDispatchMultiVersion() ||
10991 NewFD->isCPUSpecificMultiVersion()) {
10992 // ignore this, we allow the redeclaration behavior here to create new
10993 // versions of the function.
10994 } else {
10995 // The user tried to provide an out-of-line definition for a
10996 // function that is a member of a class or namespace, but there
10997 // was no such member function declared (C++ [class.mfct]p2,
10998 // C++ [namespace.memdef]p2). For example:
10999 //
11000 // class X {
11001 // void f() const;
11002 // };
11003 //
11004 // void X::f() { } // ill-formed
11005 //
11006 // Complain about this problem, and attempt to suggest close
11007 // matches (e.g., those that differ only in cv-qualifiers and
11008 // whether the parameter types are references).
11009
11010 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11011 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
11012 AddToScope = ExtraArgs.AddToScope;
11013 return Result;
11014 }
11015 }
11016
11017 // Unqualified local friend declarations are required to resolve
11018 // to something.
11019 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
11020 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11021 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
11022 AddToScope = ExtraArgs.AddToScope;
11023 return Result;
11024 }
11025 }
11026 } else if (!D.isFunctionDefinition() &&
11027 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
11028 !isFriend && !isFunctionTemplateSpecialization &&
11029 !isMemberSpecialization) {
11030 // An out-of-line member function declaration must also be a
11031 // definition (C++ [class.mfct]p2).
11032 // Note that this is not the case for explicit specializations of
11033 // function templates or member functions of class templates, per
11034 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11035 // extension for compatibility with old SWIG code which likes to
11036 // generate them.
11037 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
11038 << D.getCXXScopeSpec().getRange();
11039 }
11040 }
11041
11042 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11043 // Any top level function could potentially be specified as an entry.
11044 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11045 HLSL().ActOnTopLevelFunction(FD: NewFD);
11046
11047 if (NewFD->hasAttr<HLSLShaderAttr>())
11048 HLSL().CheckEntryPoint(FD: NewFD);
11049 }
11050
11051 // If this is the first declaration of a library builtin function, add
11052 // attributes as appropriate.
11053 if (!D.isRedeclaration()) {
11054 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11055 if (unsigned BuiltinID = II->getBuiltinID()) {
11056 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
11057 if (!InStdNamespace &&
11058 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11059 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11060 // Validate the type matches unless this builtin is specified as
11061 // matching regardless of its declared type.
11062 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
11063 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11064 } else {
11065 ASTContext::GetBuiltinTypeError Error;
11066 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
11067 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
11068
11069 if (!Error && !BuiltinType.isNull() &&
11070 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11071 T: NewFD->getType(), U: BuiltinType))
11072 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11073 }
11074 }
11075 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11076 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
11077 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11078 }
11079 }
11080 }
11081 }
11082
11083 ProcessPragmaWeak(S, D: NewFD);
11084 ProcessPragmaExport(NewD: NewFD);
11085 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
11086
11087 AddKnownFunctionAttributes(FD: NewFD);
11088
11089 if (NewFD->hasAttr<OverloadableAttr>() &&
11090 !NewFD->getType()->getAs<FunctionProtoType>()) {
11091 Diag(Loc: NewFD->getLocation(),
11092 DiagID: diag::err_attribute_overloadable_no_prototype)
11093 << NewFD;
11094 NewFD->dropAttr<OverloadableAttr>();
11095 }
11096
11097 // If there's a #pragma GCC visibility in scope, and this isn't a class
11098 // member, set the visibility of this function.
11099 if (!DC->isRecord() && NewFD->isExternallyVisible())
11100 AddPushedVisibilityAttribute(RD: NewFD);
11101
11102 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11103 // marking the function.
11104 ObjC().AddCFAuditedAttribute(D: NewFD);
11105
11106 // If this is a function definition, check if we have to apply any
11107 // attributes (i.e. optnone and no_builtin) due to a pragma.
11108 if (D.isFunctionDefinition()) {
11109 AddRangeBasedOptnone(FD: NewFD);
11110 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
11111 AddSectionMSAllocText(FD: NewFD);
11112 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
11113 }
11114
11115 // If this is the first declaration of an extern C variable, update
11116 // the map of such variables.
11117 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11118 isIncompleteDeclExternC(S&: *this, D: NewFD))
11119 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
11120
11121 // Set this FunctionDecl's range up to the right paren.
11122 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11123
11124 if (D.isRedeclaration() && !Previous.empty()) {
11125 NamedDecl *Prev = Previous.getRepresentativeDecl();
11126 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
11127 IsSpecialization: isMemberSpecialization ||
11128 isFunctionTemplateSpecialization,
11129 IsDefinition: D.isFunctionDefinition());
11130 }
11131
11132 if (getLangOpts().CUDA) {
11133 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11134 if (II->isStr(Str: CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11135 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11136 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11137 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11138 << CUDA().getConfigureFuncName();
11139 Context.setcudaConfigureCallDecl(NewFD);
11140 }
11141 if (II->isStr(Str: CUDA().getGetParameterBufferFuncName()) &&
11142 !NewFD->isInvalidDecl() &&
11143 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11144 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11145 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_pointer_return)
11146 << CUDA().getConfigureFuncName();
11147 Context.setcudaGetParameterBufferDecl(NewFD);
11148 }
11149 if (II->isStr(Str: CUDA().getLaunchDeviceFuncName()) &&
11150 !NewFD->isInvalidDecl() &&
11151 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11152 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11153 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11154 << CUDA().getConfigureFuncName();
11155 Context.setcudaLaunchDeviceDecl(NewFD);
11156 }
11157 }
11158 }
11159
11160 MarkUnusedFileScopedDecl(D: NewFD);
11161
11162 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11163 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11164 if (SC == SC_Static) {
11165 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
11166 D.setInvalidType();
11167 }
11168
11169 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11170 if (!NewFD->getReturnType()->isVoidType()) {
11171 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11172 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
11173 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
11174 : FixItHint());
11175 D.setInvalidType();
11176 }
11177
11178 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11179 for (auto *Param : NewFD->parameters())
11180 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
11181
11182 if (getLangOpts().OpenCLCPlusPlus) {
11183 if (DC->isRecord()) {
11184 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
11185 D.setInvalidType();
11186 }
11187 if (FunctionTemplate) {
11188 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
11189 D.setInvalidType();
11190 }
11191 }
11192 }
11193
11194 if (getLangOpts().CPlusPlus) {
11195 // Precalculate whether this is a friend function template with a constraint
11196 // that depends on an enclosing template, per [temp.friend]p9.
11197 if (isFriend && FunctionTemplate &&
11198 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
11199 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11200
11201 // C++ [temp.friend]p9:
11202 // A friend function template with a constraint that depends on a
11203 // template parameter from an enclosing template shall be a definition.
11204 if (!D.isFunctionDefinition()) {
11205 Diag(Loc: NewFD->getBeginLoc(),
11206 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11207 NewFD->setInvalidDecl();
11208 }
11209 }
11210
11211 if (FunctionTemplate) {
11212 if (NewFD->isInvalidDecl())
11213 FunctionTemplate->setInvalidDecl();
11214 return FunctionTemplate;
11215 }
11216
11217 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11218 CompleteMemberSpecialization(Member: NewFD, Previous);
11219 }
11220
11221 for (const ParmVarDecl *Param : NewFD->parameters()) {
11222 QualType PT = Param->getType();
11223
11224 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11225 // types.
11226 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11227 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11228 QualType ElemTy = PipeTy->getElementType();
11229 if (ElemTy->isPointerOrReferenceType()) {
11230 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11231 D.setInvalidType();
11232 }
11233 }
11234 }
11235 // WebAssembly tables can't be used as function parameters.
11236 if (Context.getTargetInfo().getTriple().isWasm()) {
11237 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11238 Diag(Loc: Param->getTypeSpecStartLoc(),
11239 DiagID: diag::err_wasm_table_as_function_parameter);
11240 D.setInvalidType();
11241 }
11242 }
11243 }
11244
11245 // Diagnose availability attributes. Availability cannot be used on functions
11246 // that are run during load/unload.
11247 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11248 if (NewFD->hasAttr<ConstructorAttr>()) {
11249 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11250 << 1;
11251 NewFD->dropAttr<AvailabilityAttr>();
11252 }
11253 if (NewFD->hasAttr<DestructorAttr>()) {
11254 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11255 << 2;
11256 NewFD->dropAttr<AvailabilityAttr>();
11257 }
11258 }
11259
11260 // Diagnose no_builtin attribute on function declaration that are not a
11261 // definition.
11262 // FIXME: We should really be doing this in
11263 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11264 // the FunctionDecl and at this point of the code
11265 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11266 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11267 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11268 switch (D.getFunctionDefinitionKind()) {
11269 case FunctionDefinitionKind::Defaulted:
11270 case FunctionDefinitionKind::Deleted:
11271 Diag(Loc: NBA->getLocation(),
11272 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11273 << NBA->getSpelling();
11274 break;
11275 case FunctionDefinitionKind::Declaration:
11276 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11277 << NBA->getSpelling();
11278 break;
11279 case FunctionDefinitionKind::Definition:
11280 break;
11281 }
11282
11283 // Similar to no_builtin logic above, at this point of the code
11284 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11285 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11286 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11287 !NewFD->isInvalidDecl() &&
11288 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11289 ExternalDeclarations.push_back(Elt: NewFD);
11290
11291 // Used for a warning on the 'next' declaration when used with a
11292 // `routine(name)`.
11293 if (getLangOpts().OpenACC)
11294 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11295
11296 return NewFD;
11297}
11298
11299/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11300/// when __declspec(code_seg) "is applied to a class, all member functions of
11301/// the class and nested classes -- this includes compiler-generated special
11302/// member functions -- are put in the specified segment."
11303/// The actual behavior is a little more complicated. The Microsoft compiler
11304/// won't check outer classes if there is an active value from #pragma code_seg.
11305/// The CodeSeg is always applied from the direct parent but only from outer
11306/// classes when the #pragma code_seg stack is empty. See:
11307/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11308/// available since MS has removed the page.
11309static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11310 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11311 if (!Method)
11312 return nullptr;
11313 const CXXRecordDecl *Parent = Method->getParent();
11314 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11315 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11316 NewAttr->setImplicit(true);
11317 return NewAttr;
11318 }
11319
11320 // The Microsoft compiler won't check outer classes for the CodeSeg
11321 // when the #pragma code_seg stack is active.
11322 if (S.CodeSegStack.CurrentValue)
11323 return nullptr;
11324
11325 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11326 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11327 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11328 NewAttr->setImplicit(true);
11329 return NewAttr;
11330 }
11331 }
11332 return nullptr;
11333}
11334
11335Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11336 bool IsDefinition) {
11337 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11338 return A;
11339 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11340 CodeSegStack.CurrentValue)
11341 return SectionAttr::CreateImplicit(
11342 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11343 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11344 return nullptr;
11345}
11346
11347bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11348 QualType NewT, QualType OldT) {
11349 if (!NewD->getLexicalDeclContext()->isDependentContext())
11350 return true;
11351
11352 // For dependently-typed local extern declarations and friends, we can't
11353 // perform a correct type check in general until instantiation:
11354 //
11355 // int f();
11356 // template<typename T> void g() { T f(); }
11357 //
11358 // (valid if g() is only instantiated with T = int).
11359 if (NewT->isDependentType() &&
11360 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11361 return false;
11362
11363 // Similarly, if the previous declaration was a dependent local extern
11364 // declaration, we don't really know its type yet.
11365 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11366 return false;
11367
11368 return true;
11369}
11370
11371bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11372 if (!D->getLexicalDeclContext()->isDependentContext())
11373 return true;
11374
11375 // Don't chain dependent friend function definitions until instantiation, to
11376 // permit cases like
11377 //
11378 // void func();
11379 // template<typename T> class C1 { friend void func() {} };
11380 // template<typename T> class C2 { friend void func() {} };
11381 //
11382 // ... which is valid if only one of C1 and C2 is ever instantiated.
11383 //
11384 // FIXME: This need only apply to function definitions. For now, we proxy
11385 // this by checking for a file-scope function. We do not want this to apply
11386 // to friend declarations nominating member functions, because that gets in
11387 // the way of access checks.
11388 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11389 return false;
11390
11391 auto *VD = dyn_cast<ValueDecl>(Val: D);
11392 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11393 return !VD || !PrevVD ||
11394 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11395 OldT: PrevVD->getType());
11396}
11397
11398/// Check the target or target_version attribute of the function for
11399/// MultiVersion validity.
11400///
11401/// Returns true if there was an error, false otherwise.
11402static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11403 const auto *TA = FD->getAttr<TargetAttr>();
11404 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11405
11406 assert((TA || TVA) && "Expecting target or target_version attribute");
11407
11408 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11409 enum ErrType { Feature = 0, Architecture = 1 };
11410
11411 if (TA) {
11412 ParsedTargetAttr ParseInfo =
11413 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11414 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11415 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11416 << Architecture << ParseInfo.CPU;
11417 return true;
11418 }
11419 for (const auto &Feat : ParseInfo.Features) {
11420 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11421 if (Feat[0] == '-') {
11422 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11423 << Feature << ("no-" + BareFeat).str();
11424 return true;
11425 }
11426
11427 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11428 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11429 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11430 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11431 << Feature << BareFeat;
11432 return true;
11433 }
11434 }
11435 }
11436
11437 if (TVA) {
11438 llvm::SmallVector<StringRef, 8> Feats;
11439 ParsedTargetAttr ParseInfo;
11440 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11441 ParseInfo =
11442 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11443 for (auto &Feat : ParseInfo.Features)
11444 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11445 } else {
11446 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11447 TVA->getFeatures(Out&: Feats);
11448 }
11449 for (const auto &Feat : Feats) {
11450 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11451 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11452 << Feature << Feat;
11453 return true;
11454 }
11455 }
11456 }
11457 return false;
11458}
11459
11460// Provide a white-list of attributes that are allowed to be combined with
11461// multiversion functions.
11462static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11463 MultiVersionKind MVKind) {
11464 // Note: this list/diagnosis must match the list in
11465 // checkMultiversionAttributesAllSame.
11466 switch (Kind) {
11467 default:
11468 return false;
11469 case attr::ArmLocallyStreaming:
11470 return MVKind == MultiVersionKind::TargetVersion ||
11471 MVKind == MultiVersionKind::TargetClones;
11472 case attr::Used:
11473 return MVKind == MultiVersionKind::Target;
11474 case attr::NonNull:
11475 case attr::NoThrow:
11476 return true;
11477 }
11478}
11479
11480static bool checkNonMultiVersionCompatAttributes(Sema &S,
11481 const FunctionDecl *FD,
11482 const FunctionDecl *CausedFD,
11483 MultiVersionKind MVKind) {
11484 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11485 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11486 << static_cast<unsigned>(MVKind) << A;
11487 if (CausedFD)
11488 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11489 return true;
11490 };
11491
11492 for (const Attr *A : FD->attrs()) {
11493 switch (A->getKind()) {
11494 case attr::CPUDispatch:
11495 case attr::CPUSpecific:
11496 if (MVKind != MultiVersionKind::CPUDispatch &&
11497 MVKind != MultiVersionKind::CPUSpecific)
11498 return Diagnose(S, A);
11499 break;
11500 case attr::Target:
11501 if (MVKind != MultiVersionKind::Target)
11502 return Diagnose(S, A);
11503 break;
11504 case attr::TargetVersion:
11505 if (MVKind != MultiVersionKind::TargetVersion &&
11506 MVKind != MultiVersionKind::TargetClones)
11507 return Diagnose(S, A);
11508 break;
11509 case attr::TargetClones:
11510 if (MVKind != MultiVersionKind::TargetClones &&
11511 MVKind != MultiVersionKind::TargetVersion)
11512 return Diagnose(S, A);
11513 break;
11514 default:
11515 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11516 return Diagnose(S, A);
11517 break;
11518 }
11519 }
11520 return false;
11521}
11522
11523bool Sema::areMultiversionVariantFunctionsCompatible(
11524 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11525 const PartialDiagnostic &NoProtoDiagID,
11526 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11527 const PartialDiagnosticAt &NoSupportDiagIDAt,
11528 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11529 bool ConstexprSupported, bool CLinkageMayDiffer) {
11530 enum DoesntSupport {
11531 FuncTemplates = 0,
11532 VirtFuncs = 1,
11533 DeducedReturn = 2,
11534 Constructors = 3,
11535 Destructors = 4,
11536 DeletedFuncs = 5,
11537 DefaultedFuncs = 6,
11538 ConstexprFuncs = 7,
11539 ConstevalFuncs = 8,
11540 Lambda = 9,
11541 };
11542 enum Different {
11543 CallingConv = 0,
11544 ReturnType = 1,
11545 ConstexprSpec = 2,
11546 InlineSpec = 3,
11547 Linkage = 4,
11548 LanguageLinkage = 5,
11549 };
11550
11551 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11552 !OldFD->getType()->getAs<FunctionProtoType>()) {
11553 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11554 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11555 return true;
11556 }
11557
11558 if (NoProtoDiagID.getDiagID() != 0 &&
11559 !NewFD->getType()->getAs<FunctionProtoType>())
11560 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11561
11562 if (!TemplatesSupported &&
11563 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11564 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11565 << FuncTemplates;
11566
11567 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11568 if (NewCXXFD->isVirtual())
11569 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11570 << VirtFuncs;
11571
11572 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11573 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11574 << Constructors;
11575
11576 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11577 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11578 << Destructors;
11579 }
11580
11581 if (NewFD->isDeleted())
11582 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11583 << DeletedFuncs;
11584
11585 if (NewFD->isDefaulted())
11586 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11587 << DefaultedFuncs;
11588
11589 if (!ConstexprSupported && NewFD->isConstexpr())
11590 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11591 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11592
11593 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11594 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11595 QualType NewReturnType = NewType->getReturnType();
11596
11597 if (NewReturnType->isUndeducedType())
11598 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11599 << DeducedReturn;
11600
11601 // Ensure the return type is identical.
11602 if (OldFD) {
11603 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11604 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11605 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11606 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11607
11608 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11609 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11610
11611 bool ArmStreamingCCMismatched = false;
11612 if (OldFPT && NewFPT) {
11613 unsigned Diff =
11614 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11615 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11616 // cannot be mixed.
11617 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11618 FunctionType::SME_PStateSMCompatibleMask))
11619 ArmStreamingCCMismatched = true;
11620 }
11621
11622 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11623 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11624
11625 QualType OldReturnType = OldType->getReturnType();
11626
11627 if (OldReturnType != NewReturnType)
11628 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11629
11630 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11631 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11632
11633 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11634 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11635
11636 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11637 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11638
11639 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11640 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11641
11642 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11643 NewLoc: NewFD->getLocation()))
11644 return true;
11645 }
11646 return false;
11647}
11648
11649static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11650 const FunctionDecl *NewFD,
11651 bool CausesMV,
11652 MultiVersionKind MVKind) {
11653 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11654 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11655 if (OldFD)
11656 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11657 return true;
11658 }
11659
11660 bool IsCPUSpecificCPUDispatchMVKind =
11661 MVKind == MultiVersionKind::CPUDispatch ||
11662 MVKind == MultiVersionKind::CPUSpecific;
11663
11664 if (CausesMV && OldFD &&
11665 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11666 return true;
11667
11668 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11669 return true;
11670
11671 // Only allow transition to MultiVersion if it hasn't been used.
11672 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11673 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11674 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11675 return true;
11676 }
11677
11678 return S.areMultiversionVariantFunctionsCompatible(
11679 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11680 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11681 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11682 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11683 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11684 << static_cast<unsigned>(MVKind)),
11685 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11686 S.PDiag(DiagID: diag::err_multiversion_diff)),
11687 /*TemplatesSupported=*/false,
11688 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11689 /*CLinkageMayDiffer=*/false);
11690}
11691
11692/// Check the validity of a multiversion function declaration that is the
11693/// first of its kind. Also sets the multiversion'ness' of the function itself.
11694///
11695/// This sets NewFD->isInvalidDecl() to true if there was an error.
11696///
11697/// Returns true if there was an error, false otherwise.
11698static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11699 MultiVersionKind MVKind = FD->getMultiVersionKind();
11700 assert(MVKind != MultiVersionKind::None &&
11701 "Function lacks multiversion attribute");
11702 const auto *TA = FD->getAttr<TargetAttr>();
11703 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11704 // The target attribute only causes MV if this declaration is the default,
11705 // otherwise it is treated as a normal function.
11706 if (TA && !TA->isDefaultVersion())
11707 return false;
11708
11709 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11710 FD->setInvalidDecl();
11711 return true;
11712 }
11713
11714 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11715 FD->setInvalidDecl();
11716 return true;
11717 }
11718
11719 FD->setIsMultiVersion();
11720 return false;
11721}
11722
11723static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11724 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11725 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11726 return true;
11727 }
11728
11729 return false;
11730}
11731
11732static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11733 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11734 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11735 return;
11736
11737 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11738 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11739
11740 if (MVKindTo == MultiVersionKind::None &&
11741 (MVKindFrom == MultiVersionKind::TargetVersion ||
11742 MVKindFrom == MultiVersionKind::TargetClones))
11743 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11744 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11745}
11746
11747static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11748 FunctionDecl *NewFD,
11749 bool &Redeclaration,
11750 NamedDecl *&OldDecl,
11751 LookupResult &Previous) {
11752 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11753
11754 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11755 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11756 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11757 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11758
11759 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11760
11761 // The definitions should be allowed in any order. If we have discovered
11762 // a new target version and the preceeding was the default, then add the
11763 // corresponding attribute to it.
11764 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11765
11766 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11767 // to change, this is a simple redeclaration.
11768 if (NewTA && !NewTA->isDefaultVersion() &&
11769 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11770 return false;
11771
11772 // Otherwise, this decl causes MultiVersioning.
11773 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11774 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11775 : MultiVersionKind::Target)) {
11776 NewFD->setInvalidDecl();
11777 return true;
11778 }
11779
11780 if (CheckMultiVersionValue(S, FD: NewFD)) {
11781 NewFD->setInvalidDecl();
11782 return true;
11783 }
11784
11785 // If this is 'default', permit the forward declaration.
11786 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11787 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11788 Redeclaration = true;
11789 OldDecl = OldFD;
11790 OldFD->setIsMultiVersion();
11791 NewFD->setIsMultiVersion();
11792 return false;
11793 }
11794
11795 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11796 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11797 NewFD->setInvalidDecl();
11798 return true;
11799 }
11800
11801 if (NewTA) {
11802 ParsedTargetAttr OldParsed =
11803 S.getASTContext().getTargetInfo().parseTargetAttr(
11804 Str: OldTA->getFeaturesStr());
11805 llvm::sort(C&: OldParsed.Features);
11806 ParsedTargetAttr NewParsed =
11807 S.getASTContext().getTargetInfo().parseTargetAttr(
11808 Str: NewTA->getFeaturesStr());
11809 // Sort order doesn't matter, it just needs to be consistent.
11810 llvm::sort(C&: NewParsed.Features);
11811 if (OldParsed == NewParsed) {
11812 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11813 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11814 NewFD->setInvalidDecl();
11815 return true;
11816 }
11817 }
11818
11819 for (const auto *FD : OldFD->redecls()) {
11820 const auto *CurTA = FD->getAttr<TargetAttr>();
11821 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11822 // We allow forward declarations before ANY multiversioning attributes, but
11823 // nothing after the fact.
11824 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11825 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11826 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11827 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
11828 << (NewTA ? 0 : 2);
11829 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11830 NewFD->setInvalidDecl();
11831 return true;
11832 }
11833 }
11834
11835 OldFD->setIsMultiVersion();
11836 NewFD->setIsMultiVersion();
11837 Redeclaration = false;
11838 OldDecl = nullptr;
11839 Previous.clear();
11840 return false;
11841}
11842
11843static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11844 MultiVersionKind OldKind = Old->getMultiVersionKind();
11845 MultiVersionKind NewKind = New->getMultiVersionKind();
11846
11847 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11848 NewKind == MultiVersionKind::None)
11849 return true;
11850
11851 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11852 switch (OldKind) {
11853 case MultiVersionKind::TargetVersion:
11854 return NewKind == MultiVersionKind::TargetClones;
11855 case MultiVersionKind::TargetClones:
11856 return NewKind == MultiVersionKind::TargetVersion;
11857 default:
11858 return false;
11859 }
11860 } else {
11861 switch (OldKind) {
11862 case MultiVersionKind::CPUDispatch:
11863 return NewKind == MultiVersionKind::CPUSpecific;
11864 case MultiVersionKind::CPUSpecific:
11865 return NewKind == MultiVersionKind::CPUDispatch;
11866 default:
11867 return false;
11868 }
11869 }
11870}
11871
11872/// Check the validity of a new function declaration being added to an existing
11873/// multiversioned declaration collection.
11874static bool CheckMultiVersionAdditionalDecl(
11875 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11876 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11877 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11878 LookupResult &Previous) {
11879
11880 // Disallow mixing of multiversioning types.
11881 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
11882 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
11883 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11884 NewFD->setInvalidDecl();
11885 return true;
11886 }
11887
11888 // Add the default target_version attribute if it's missing.
11889 patchDefaultTargetVersion(From: OldFD, To: NewFD);
11890 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11891
11892 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11893 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11894 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11895 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11896
11897 ParsedTargetAttr NewParsed;
11898 if (NewTA) {
11899 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11900 Str: NewTA->getFeaturesStr());
11901 llvm::sort(C&: NewParsed.Features);
11902 }
11903 llvm::SmallVector<StringRef, 8> NewFeats;
11904 if (NewTVA) {
11905 NewTVA->getFeatures(Out&: NewFeats);
11906 llvm::sort(C&: NewFeats);
11907 }
11908
11909 bool UseMemberUsingDeclRules =
11910 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11911
11912 bool MayNeedOverloadableChecks =
11913 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
11914
11915 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11916 // of a previous member of the MultiVersion set.
11917 for (NamedDecl *ND : Previous) {
11918 FunctionDecl *CurFD = ND->getAsFunction();
11919 if (!CurFD || CurFD->isInvalidDecl())
11920 continue;
11921 if (MayNeedOverloadableChecks &&
11922 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
11923 continue;
11924
11925 switch (NewMVKind) {
11926 case MultiVersionKind::None:
11927 assert(OldMVKind == MultiVersionKind::TargetClones &&
11928 "Only target_clones can be omitted in subsequent declarations");
11929 break;
11930 case MultiVersionKind::Target: {
11931 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11932 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11933 NewFD->setIsMultiVersion();
11934 Redeclaration = true;
11935 OldDecl = ND;
11936 return false;
11937 }
11938
11939 ParsedTargetAttr CurParsed =
11940 S.getASTContext().getTargetInfo().parseTargetAttr(
11941 Str: CurTA->getFeaturesStr());
11942 llvm::sort(C&: CurParsed.Features);
11943 if (CurParsed == NewParsed) {
11944 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11945 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11946 NewFD->setInvalidDecl();
11947 return true;
11948 }
11949 break;
11950 }
11951 case MultiVersionKind::TargetVersion: {
11952 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11953 if (CurTVA->getName() == NewTVA->getName()) {
11954 NewFD->setIsMultiVersion();
11955 Redeclaration = true;
11956 OldDecl = ND;
11957 return false;
11958 }
11959 llvm::SmallVector<StringRef, 8> CurFeats;
11960 CurTVA->getFeatures(Out&: CurFeats);
11961 llvm::sort(C&: CurFeats);
11962
11963 if (CurFeats == NewFeats) {
11964 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11965 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11966 NewFD->setInvalidDecl();
11967 return true;
11968 }
11969 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11970 // Default
11971 if (NewFeats.empty())
11972 break;
11973
11974 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11975 llvm::SmallVector<StringRef, 8> CurFeats;
11976 CurClones->getFeatures(Out&: CurFeats, Index: I);
11977 llvm::sort(C&: CurFeats);
11978
11979 if (CurFeats == NewFeats) {
11980 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11981 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11982 NewFD->setInvalidDecl();
11983 return true;
11984 }
11985 }
11986 }
11987 break;
11988 }
11989 case MultiVersionKind::TargetClones: {
11990 assert(NewClones && "MultiVersionKind does not match attribute type");
11991 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11992 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11993 !std::equal(first1: CurClones->featuresStrs_begin(),
11994 last1: CurClones->featuresStrs_end(),
11995 first2: NewClones->featuresStrs_begin())) {
11996 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
11997 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11998 NewFD->setInvalidDecl();
11999 return true;
12000 }
12001 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12002 llvm::SmallVector<StringRef, 8> CurFeats;
12003 CurTVA->getFeatures(Out&: CurFeats);
12004 llvm::sort(C&: CurFeats);
12005
12006 // Default
12007 if (CurFeats.empty())
12008 break;
12009
12010 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12011 NewFeats.clear();
12012 NewClones->getFeatures(Out&: NewFeats, Index: I);
12013 llvm::sort(C&: NewFeats);
12014
12015 if (CurFeats == NewFeats) {
12016 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12017 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12018 NewFD->setInvalidDecl();
12019 return true;
12020 }
12021 }
12022 break;
12023 }
12024 Redeclaration = true;
12025 OldDecl = CurFD;
12026 NewFD->setIsMultiVersion();
12027 return false;
12028 }
12029 case MultiVersionKind::CPUSpecific:
12030 case MultiVersionKind::CPUDispatch: {
12031 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12032 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12033 // Handle CPUDispatch/CPUSpecific versions.
12034 // Only 1 CPUDispatch function is allowed, this will make it go through
12035 // the redeclaration errors.
12036 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12037 CurFD->hasAttr<CPUDispatchAttr>()) {
12038 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12039 std::equal(
12040 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
12041 first2: NewCPUDisp->cpus_begin(),
12042 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12043 return Cur->getName() == New->getName();
12044 })) {
12045 NewFD->setIsMultiVersion();
12046 Redeclaration = true;
12047 OldDecl = ND;
12048 return false;
12049 }
12050
12051 // If the declarations don't match, this is an error condition.
12052 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
12053 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12054 NewFD->setInvalidDecl();
12055 return true;
12056 }
12057 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12058 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12059 std::equal(
12060 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
12061 first2: NewCPUSpec->cpus_begin(),
12062 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12063 return Cur->getName() == New->getName();
12064 })) {
12065 NewFD->setIsMultiVersion();
12066 Redeclaration = true;
12067 OldDecl = ND;
12068 return false;
12069 }
12070
12071 // Only 1 version of CPUSpecific is allowed for each CPU.
12072 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12073 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12074 if (CurII == NewII) {
12075 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
12076 << NewII;
12077 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12078 NewFD->setInvalidDecl();
12079 return true;
12080 }
12081 }
12082 }
12083 }
12084 break;
12085 }
12086 }
12087 }
12088
12089 // Redeclarations of a target_clones function may omit the attribute, in which
12090 // case it will be inherited during declaration merging.
12091 if (NewMVKind == MultiVersionKind::None &&
12092 OldMVKind == MultiVersionKind::TargetClones) {
12093 NewFD->setIsMultiVersion();
12094 Redeclaration = true;
12095 OldDecl = OldFD;
12096 return false;
12097 }
12098
12099 // Else, this is simply a non-redecl case. Checking the 'value' is only
12100 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12101 // handled in the attribute adding step.
12102 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
12103 NewFD->setInvalidDecl();
12104 return true;
12105 }
12106
12107 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12108 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
12109 NewFD->setInvalidDecl();
12110 return true;
12111 }
12112
12113 // Permit forward declarations in the case where these two are compatible.
12114 if (!OldFD->isMultiVersion()) {
12115 OldFD->setIsMultiVersion();
12116 NewFD->setIsMultiVersion();
12117 Redeclaration = true;
12118 OldDecl = OldFD;
12119 return false;
12120 }
12121
12122 NewFD->setIsMultiVersion();
12123 Redeclaration = false;
12124 OldDecl = nullptr;
12125 Previous.clear();
12126 return false;
12127}
12128
12129/// Check the validity of a mulitversion function declaration.
12130/// Also sets the multiversion'ness' of the function itself.
12131///
12132/// This sets NewFD->isInvalidDecl() to true if there was an error.
12133///
12134/// Returns true if there was an error, false otherwise.
12135static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12136 bool &Redeclaration, NamedDecl *&OldDecl,
12137 LookupResult &Previous) {
12138 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12139
12140 // Check if FMV is disabled.
12141 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
12142 return false;
12143
12144 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12145 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12146 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12147 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12148 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12149 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12150
12151 // Main isn't allowed to become a multiversion function, however it IS
12152 // permitted to have 'main' be marked with the 'target' optimization hint,
12153 // for 'target_version' only default is allowed.
12154 if (NewFD->isMain()) {
12155 if (MVKind != MultiVersionKind::None &&
12156 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12157 !(MVKind == MultiVersionKind::TargetVersion &&
12158 NewTVA->isDefaultVersion())) {
12159 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
12160 NewFD->setInvalidDecl();
12161 return true;
12162 }
12163 return false;
12164 }
12165
12166 // Target attribute on AArch64 is not used for multiversioning
12167 if (NewTA && TI.getTriple().isAArch64())
12168 return false;
12169
12170 // Target attribute on RISCV is not used for multiversioning
12171 if (NewTA && TI.getTriple().isRISCV())
12172 return false;
12173
12174 if (!OldDecl || !OldDecl->getAsFunction() ||
12175 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12176 DC: NewFD->getDeclContext()->getRedeclContext())) {
12177 // If there's no previous declaration, AND this isn't attempting to cause
12178 // multiversioning, this isn't an error condition.
12179 if (MVKind == MultiVersionKind::None)
12180 return false;
12181 return CheckMultiVersionFirstFunction(S, FD: NewFD);
12182 }
12183
12184 FunctionDecl *OldFD = OldDecl->getAsFunction();
12185
12186 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12187 return false;
12188
12189 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12190 // for target_clones and target_version.
12191 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12192 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12193 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12194 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12195 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12196 NewFD->setInvalidDecl();
12197 return true;
12198 }
12199
12200 if (!OldFD->isMultiVersion()) {
12201 switch (MVKind) {
12202 case MultiVersionKind::Target:
12203 case MultiVersionKind::TargetVersion:
12204 return CheckDeclarationCausesMultiVersioning(
12205 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12206 case MultiVersionKind::TargetClones:
12207 if (OldFD->isUsed(CheckUsedAttr: false)) {
12208 NewFD->setInvalidDecl();
12209 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
12210 }
12211 OldFD->setIsMultiVersion();
12212 break;
12213
12214 case MultiVersionKind::CPUDispatch:
12215 case MultiVersionKind::CPUSpecific:
12216 case MultiVersionKind::None:
12217 break;
12218 }
12219 }
12220
12221 // At this point, we have a multiversion function decl (in OldFD) AND an
12222 // appropriate attribute in the current function decl (unless it's allowed to
12223 // omit the attribute). Resolve that these are still compatible with previous
12224 // declarations.
12225 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12226 NewCPUSpec, NewClones, Redeclaration,
12227 OldDecl, Previous);
12228}
12229
12230static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12231 bool IsPure = NewFD->hasAttr<PureAttr>();
12232 bool IsConst = NewFD->hasAttr<ConstAttr>();
12233
12234 // If there are no pure or const attributes, there's nothing to check.
12235 if (!IsPure && !IsConst)
12236 return;
12237
12238 // If the function is marked both pure and const, we retain the const
12239 // attribute because it makes stronger guarantees than the pure attribute, and
12240 // we drop the pure attribute explicitly to prevent later confusion about
12241 // semantics.
12242 if (IsPure && IsConst) {
12243 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12244 NewFD->dropAttrs<PureAttr>();
12245 }
12246
12247 // Constructors and destructors are functions which return void, so are
12248 // handled here as well.
12249 if (NewFD->getReturnType()->isVoidType()) {
12250 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12251 << IsConst;
12252 NewFD->dropAttrs<PureAttr, ConstAttr>();
12253 }
12254}
12255
12256bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12257 LookupResult &Previous,
12258 bool IsMemberSpecialization,
12259 bool DeclIsDefn) {
12260 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12261 "Variably modified return types are not handled here");
12262
12263 // Determine whether the type of this function should be merged with
12264 // a previous visible declaration. This never happens for functions in C++,
12265 // and always happens in C if the previous declaration was visible.
12266 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12267 !Previous.isShadowed();
12268
12269 bool Redeclaration = false;
12270 NamedDecl *OldDecl = nullptr;
12271 bool MayNeedOverloadableChecks = false;
12272
12273 inferLifetimeCaptureByAttribute(FD: NewFD);
12274 // Merge or overload the declaration with an existing declaration of
12275 // the same name, if appropriate.
12276 if (!Previous.empty()) {
12277 // Determine whether NewFD is an overload of PrevDecl or
12278 // a declaration that requires merging. If it's an overload,
12279 // there's no more work to do here; we'll just add the new
12280 // function to the scope.
12281 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12282 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12283 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12284 Redeclaration = true;
12285 OldDecl = Candidate;
12286 }
12287 } else {
12288 MayNeedOverloadableChecks = true;
12289 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12290 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12291 case OverloadKind::Match:
12292 Redeclaration = true;
12293 break;
12294
12295 case OverloadKind::NonFunction:
12296 Redeclaration = true;
12297 break;
12298
12299 case OverloadKind::Overload:
12300 Redeclaration = false;
12301 break;
12302 }
12303 }
12304 }
12305
12306 // Check for a previous extern "C" declaration with this name.
12307 if (!Redeclaration &&
12308 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12309 if (!Previous.empty()) {
12310 // This is an extern "C" declaration with the same name as a previous
12311 // declaration, and thus redeclares that entity...
12312 Redeclaration = true;
12313 OldDecl = Previous.getFoundDecl();
12314 MergeTypeWithPrevious = false;
12315
12316 // ... except in the presence of __attribute__((overloadable)).
12317 if (OldDecl->hasAttr<OverloadableAttr>() ||
12318 NewFD->hasAttr<OverloadableAttr>()) {
12319 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12320 MayNeedOverloadableChecks = true;
12321 Redeclaration = false;
12322 OldDecl = nullptr;
12323 }
12324 }
12325 }
12326 }
12327
12328 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12329 return Redeclaration;
12330
12331 // PPC MMA non-pointer types are not allowed as function return types.
12332 if (Context.getTargetInfo().getTriple().isPPC64() &&
12333 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12334 NewFD->setInvalidDecl();
12335 }
12336
12337 CheckConstPureAttributesUsage(S&: *this, NewFD);
12338
12339 // C++ [dcl.spec.auto.general]p12:
12340 // Return type deduction for a templated function with a placeholder in its
12341 // declared type occurs when the definition is instantiated even if the
12342 // function body contains a return statement with a non-type-dependent
12343 // operand.
12344 //
12345 // C++ [temp.dep.expr]p3:
12346 // An id-expression is type-dependent if it is a template-id that is not a
12347 // concept-id and is dependent; or if its terminal name is:
12348 // - [...]
12349 // - associated by name lookup with one or more declarations of member
12350 // functions of a class that is the current instantiation declared with a
12351 // return type that contains a placeholder type,
12352 // - [...]
12353 //
12354 // If this is a templated function with a placeholder in its return type,
12355 // make the placeholder type dependent since it won't be deduced until the
12356 // definition is instantiated. We do this here because it needs to happen
12357 // for implicitly instantiated member functions/member function templates.
12358 if (getLangOpts().CPlusPlus14 &&
12359 (NewFD->isDependentContext() &&
12360 NewFD->getReturnType()->isUndeducedType())) {
12361 const FunctionProtoType *FPT =
12362 NewFD->getType()->castAs<FunctionProtoType>();
12363 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12364 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12365 EPI: FPT->getExtProtoInfo()));
12366 }
12367
12368 // C++11 [dcl.constexpr]p8:
12369 // A constexpr specifier for a non-static member function that is not
12370 // a constructor declares that member function to be const.
12371 //
12372 // This needs to be delayed until we know whether this is an out-of-line
12373 // definition of a static member function.
12374 //
12375 // This rule is not present in C++1y, so we produce a backwards
12376 // compatibility warning whenever it happens in C++11.
12377 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12378 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12379 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12380 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12381 CXXMethodDecl *OldMD = nullptr;
12382 if (OldDecl)
12383 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12384 if (!OldMD || !OldMD->isStatic()) {
12385 const FunctionProtoType *FPT =
12386 MD->getType()->castAs<FunctionProtoType>();
12387 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12388 EPI.TypeQuals.addConst();
12389 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12390 Args: FPT->getParamTypes(), EPI));
12391
12392 // Warn that we did this, if we're not performing template instantiation.
12393 // In that case, we'll have warned already when the template was defined.
12394 if (!inTemplateInstantiation()) {
12395 SourceLocation AddConstLoc;
12396 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12397 .IgnoreParens().getAs<FunctionTypeLoc>())
12398 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12399
12400 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12401 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12402 }
12403 }
12404 }
12405
12406 if (Redeclaration) {
12407 // NewFD and OldDecl represent declarations that need to be
12408 // merged.
12409 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12410 NewDeclIsDefn: DeclIsDefn)) {
12411 NewFD->setInvalidDecl();
12412 return Redeclaration;
12413 }
12414
12415 Previous.clear();
12416 Previous.addDecl(D: OldDecl);
12417
12418 if (FunctionTemplateDecl *OldTemplateDecl =
12419 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12420 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12421 FunctionTemplateDecl *NewTemplateDecl
12422 = NewFD->getDescribedFunctionTemplate();
12423 assert(NewTemplateDecl && "Template/non-template mismatch");
12424
12425 // The call to MergeFunctionDecl above may have created some state in
12426 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12427 // can add it as a redeclaration.
12428 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12429
12430 NewFD->setPreviousDeclaration(OldFD);
12431 if (NewFD->isCXXClassMember()) {
12432 NewFD->setAccess(OldTemplateDecl->getAccess());
12433 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12434 }
12435
12436 // If this is an explicit specialization of a member that is a function
12437 // template, mark it as a member specialization.
12438 if (IsMemberSpecialization &&
12439 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12440 NewTemplateDecl->setMemberSpecialization();
12441 assert(OldTemplateDecl->isMemberSpecialization());
12442 // Explicit specializations of a member template do not inherit deleted
12443 // status from the parent member template that they are specializing.
12444 if (OldFD->isDeleted()) {
12445 // FIXME: This assert will not hold in the presence of modules.
12446 assert(OldFD->getCanonicalDecl() == OldFD);
12447 // FIXME: We need an update record for this AST mutation.
12448 OldFD->setDeletedAsWritten(D: false);
12449 }
12450 }
12451
12452 } else {
12453 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12454 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12455 // This needs to happen first so that 'inline' propagates.
12456 NewFD->setPreviousDeclaration(OldFD);
12457 if (NewFD->isCXXClassMember())
12458 NewFD->setAccess(OldFD->getAccess());
12459 }
12460 }
12461 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12462 !NewFD->getAttr<OverloadableAttr>()) {
12463 assert((Previous.empty() ||
12464 llvm::any_of(Previous,
12465 [](const NamedDecl *ND) {
12466 return ND->hasAttr<OverloadableAttr>();
12467 })) &&
12468 "Non-redecls shouldn't happen without overloadable present");
12469
12470 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12471 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12472 return FD && !FD->hasAttr<OverloadableAttr>();
12473 });
12474
12475 if (OtherUnmarkedIter != Previous.end()) {
12476 Diag(Loc: NewFD->getLocation(),
12477 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12478 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12479 DiagID: diag::note_attribute_overloadable_prev_overload)
12480 << false;
12481
12482 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12483 }
12484 }
12485
12486 if (LangOpts.OpenMP)
12487 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12488
12489 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12490 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12491
12492 if (NewFD->hasAttr<SYCLExternalAttr>())
12493 SYCL().CheckSYCLExternalFunctionDecl(FD: NewFD);
12494
12495 // Semantic checking for this function declaration (in isolation).
12496
12497 if (getLangOpts().CPlusPlus) {
12498 // C++-specific checks.
12499 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12500 CheckConstructor(Constructor);
12501 } else if (CXXDestructorDecl *Destructor =
12502 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12503 // We check here for invalid destructor names.
12504 // If we have a friend destructor declaration that is dependent, we can't
12505 // diagnose right away because cases like this are still valid:
12506 // template <class T> struct A { friend T::X::~Y(); };
12507 // struct B { struct Y { ~Y(); }; using X = Y; };
12508 // template struct A<B>;
12509 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12510 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12511 CanQualType ClassType =
12512 Context.getCanonicalTagType(TD: Destructor->getParent());
12513
12514 DeclarationName Name =
12515 Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
12516 if (NewFD->getDeclName() != Name) {
12517 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12518 NewFD->setInvalidDecl();
12519 return Redeclaration;
12520 }
12521 }
12522 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12523 if (auto *TD = Guide->getDescribedFunctionTemplate())
12524 CheckDeductionGuideTemplate(TD);
12525
12526 // A deduction guide is not on the list of entities that can be
12527 // explicitly specialized.
12528 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12529 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12530 << /*explicit specialization*/ 1;
12531 }
12532
12533 // Find any virtual functions that this function overrides.
12534 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12535 if (!Method->isFunctionTemplateSpecialization() &&
12536 !Method->getDescribedFunctionTemplate() &&
12537 Method->isCanonicalDecl()) {
12538 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12539 }
12540 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12541 // C++2a [class.virtual]p6
12542 // A virtual method shall not have a requires-clause.
12543 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12544 DiagID: diag::err_constrained_virtual_method);
12545
12546 if (Method->isStatic())
12547 checkThisInStaticMemberFunctionType(Method);
12548 }
12549
12550 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12551 ActOnConversionDeclarator(Conversion);
12552
12553 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12554 if (NewFD->isOverloadedOperator() &&
12555 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12556 NewFD->setInvalidDecl();
12557 return Redeclaration;
12558 }
12559
12560 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12561 if (NewFD->getLiteralIdentifier() &&
12562 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12563 NewFD->setInvalidDecl();
12564 return Redeclaration;
12565 }
12566
12567 // In C++, check default arguments now that we have merged decls. Unless
12568 // the lexical context is the class, because in this case this is done
12569 // during delayed parsing anyway.
12570 if (!CurContext->isRecord())
12571 CheckCXXDefaultArguments(FD: NewFD);
12572
12573 // If this function is declared as being extern "C", then check to see if
12574 // the function returns a UDT (class, struct, or union type) that is not C
12575 // compatible, and if it does, warn the user.
12576 // But, issue any diagnostic on the first declaration only.
12577 if (Previous.empty() && NewFD->isExternC()) {
12578 QualType R = NewFD->getReturnType();
12579 if (R->isIncompleteType() && !R->isVoidType())
12580 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12581 << NewFD << R;
12582 else if (!R.isPODType(Context) && !R->isVoidType() &&
12583 !R->isObjCObjectPointerType())
12584 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12585 }
12586
12587 // C++1z [dcl.fct]p6:
12588 // [...] whether the function has a non-throwing exception-specification
12589 // [is] part of the function type
12590 //
12591 // This results in an ABI break between C++14 and C++17 for functions whose
12592 // declared type includes an exception-specification in a parameter or
12593 // return type. (Exception specifications on the function itself are OK in
12594 // most cases, and exception specifications are not permitted in most other
12595 // contexts where they could make it into a mangling.)
12596 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12597 auto HasNoexcept = [&](QualType T) -> bool {
12598 // Strip off declarator chunks that could be between us and a function
12599 // type. We don't need to look far, exception specifications are very
12600 // restricted prior to C++17.
12601 if (auto *RT = T->getAs<ReferenceType>())
12602 T = RT->getPointeeType();
12603 else if (T->isAnyPointerType())
12604 T = T->getPointeeType();
12605 else if (auto *MPT = T->getAs<MemberPointerType>())
12606 T = MPT->getPointeeType();
12607 if (auto *FPT = T->getAs<FunctionProtoType>())
12608 if (FPT->isNothrow())
12609 return true;
12610 return false;
12611 };
12612
12613 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12614 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12615 for (QualType T : FPT->param_types())
12616 AnyNoexcept |= HasNoexcept(T);
12617 if (AnyNoexcept)
12618 Diag(Loc: NewFD->getLocation(),
12619 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12620 << NewFD;
12621 }
12622
12623 if (!Redeclaration && LangOpts.CUDA) {
12624 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12625 for (auto *Parm : NewFD->parameters()) {
12626 if (!Parm->getType()->isDependentType() &&
12627 Parm->hasAttr<CUDAGridConstantAttr>() &&
12628 !(IsKernel && Parm->getType().isConstQualified()))
12629 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12630 DiagID: diag::err_cuda_grid_constant_not_allowed);
12631 }
12632 CUDA().checkTargetOverload(NewFD, Previous);
12633 }
12634 }
12635
12636 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12637 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12638
12639 return Redeclaration;
12640}
12641
12642void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12643 // [basic.start.main]p3
12644 // The main function shall not be declared with C linkage-specification.
12645 if (FD->isExternCContext())
12646 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12647
12648 // C++11 [basic.start.main]p3:
12649 // A program that [...] declares main to be inline, static or
12650 // constexpr is ill-formed.
12651 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12652 // appear in a declaration of main.
12653 // static main is not an error under C99, but we should warn about it.
12654 // We accept _Noreturn main as an extension.
12655 if (FD->getStorageClass() == SC_Static)
12656 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12657 ? diag::err_static_main : diag::warn_static_main)
12658 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12659 if (FD->isInlineSpecified())
12660 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12661 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12662 if (DS.isNoreturnSpecified()) {
12663 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12664 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12665 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12666 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12667 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12668 }
12669 if (FD->isConstexpr()) {
12670 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12671 << FD->isConsteval()
12672 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12673 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12674 }
12675
12676 if (getLangOpts().OpenCL) {
12677 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12678 << FD->hasAttr<DeviceKernelAttr>();
12679 FD->setInvalidDecl();
12680 return;
12681 }
12682
12683 if (FD->hasAttr<SYCLExternalAttr>()) {
12684 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_external_invalid_main)
12685 << FD->getAttr<SYCLExternalAttr>();
12686 FD->setInvalidDecl();
12687 return;
12688 }
12689
12690 // Functions named main in hlsl are default entries, but don't have specific
12691 // signatures they are required to conform to.
12692 if (getLangOpts().HLSL)
12693 return;
12694
12695 QualType T = FD->getType();
12696 assert(T->isFunctionType() && "function decl is not of function type");
12697 const FunctionType* FT = T->castAs<FunctionType>();
12698
12699 // Set default calling convention for main()
12700 if (FT->getCallConv() != CC_C) {
12701 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12702 FD->setType(QualType(FT, 0));
12703 T = Context.getCanonicalType(T: FD->getType());
12704 }
12705
12706 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12707 // In C with GNU extensions we allow main() to have non-integer return
12708 // type, but we should warn about the extension, and we disable the
12709 // implicit-return-zero rule.
12710
12711 // GCC in C mode accepts qualified 'int'.
12712 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12713 FD->setHasImplicitReturnZero(true);
12714 else {
12715 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12716 SourceRange RTRange = FD->getReturnTypeSourceRange();
12717 if (RTRange.isValid())
12718 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12719 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12720 }
12721 } else {
12722 // In C and C++, main magically returns 0 if you fall off the end;
12723 // set the flag which tells us that.
12724 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12725
12726 // All the standards say that main() should return 'int'.
12727 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12728 FD->setHasImplicitReturnZero(true);
12729 else {
12730 // Otherwise, this is just a flat-out error.
12731 SourceRange RTRange = FD->getReturnTypeSourceRange();
12732 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12733 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12734 : FixItHint());
12735 FD->setInvalidDecl(true);
12736 }
12737
12738 // [basic.start.main]p3:
12739 // A program that declares a function main that belongs to the global scope
12740 // and is attached to a named module is ill-formed.
12741 if (FD->isInNamedModule()) {
12742 const SourceLocation start = FD->getTypeSpecStartLoc();
12743 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12744 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12745 }
12746 }
12747
12748 // Treat protoless main() as nullary.
12749 if (isa<FunctionNoProtoType>(Val: FT)) return;
12750
12751 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12752 unsigned nparams = FTP->getNumParams();
12753 assert(FD->getNumParams() == nparams);
12754
12755 bool HasExtraParameters = (nparams > 3);
12756
12757 if (FTP->isVariadic()) {
12758 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12759 // FIXME: if we had information about the location of the ellipsis, we
12760 // could add a FixIt hint to remove it as a parameter.
12761 }
12762
12763 // Darwin passes an undocumented fourth argument of type char**. If
12764 // other platforms start sprouting these, the logic below will start
12765 // getting shifty.
12766 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12767 HasExtraParameters = false;
12768
12769 if (HasExtraParameters) {
12770 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12771 FD->setInvalidDecl(true);
12772 nparams = 3;
12773 }
12774
12775 // FIXME: a lot of the following diagnostics would be improved
12776 // if we had some location information about types.
12777
12778 QualType CharPP =
12779 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12780 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12781
12782 for (unsigned i = 0; i < nparams; ++i) {
12783 QualType AT = FTP->getParamType(i);
12784
12785 bool mismatch = true;
12786
12787 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12788 mismatch = false;
12789 else if (Expected[i] == CharPP) {
12790 // As an extension, the following forms are okay:
12791 // char const **
12792 // char const * const *
12793 // char * const *
12794
12795 QualifierCollector qs;
12796 const PointerType* PT;
12797 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12798 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12799 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
12800 T2: Context.CharTy)) {
12801 qs.removeConst();
12802 mismatch = !qs.empty();
12803 }
12804 }
12805
12806 if (mismatch) {
12807 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
12808 // TODO: suggest replacing given type with expected type
12809 FD->setInvalidDecl(true);
12810 }
12811 }
12812
12813 if (nparams == 1 && !FD->isInvalidDecl()) {
12814 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
12815 }
12816
12817 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12818 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12819 FD->setInvalidDecl();
12820 }
12821}
12822
12823static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12824
12825 // Default calling convention for main and wmain is __cdecl
12826 if (FD->getName() == "main" || FD->getName() == "wmain")
12827 return false;
12828
12829 // Default calling convention for MinGW and Cygwin is __cdecl
12830 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12831 if (T.isOSCygMing())
12832 return false;
12833
12834 // Default calling convention for WinMain, wWinMain and DllMain
12835 // is __stdcall on 32 bit Windows
12836 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12837 return true;
12838
12839 return false;
12840}
12841
12842void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12843 QualType T = FD->getType();
12844 assert(T->isFunctionType() && "function decl is not of function type");
12845 const FunctionType *FT = T->castAs<FunctionType>();
12846
12847 // Set an implicit return of 'zero' if the function can return some integral,
12848 // enumeration, pointer or nullptr type.
12849 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12850 FT->getReturnType()->isAnyPointerType() ||
12851 FT->getReturnType()->isNullPtrType())
12852 // DllMain is exempt because a return value of zero means it failed.
12853 if (FD->getName() != "DllMain")
12854 FD->setHasImplicitReturnZero(true);
12855
12856 // Explicitly specified calling conventions are applied to MSVC entry points
12857 if (!hasExplicitCallingConv(T)) {
12858 if (isDefaultStdCall(FD, S&: *this)) {
12859 if (FT->getCallConv() != CC_X86StdCall) {
12860 FT = Context.adjustFunctionType(
12861 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12862 FD->setType(QualType(FT, 0));
12863 }
12864 } else if (FT->getCallConv() != CC_C) {
12865 FT = Context.adjustFunctionType(Fn: FT,
12866 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12867 FD->setType(QualType(FT, 0));
12868 }
12869 }
12870
12871 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12872 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12873 FD->setInvalidDecl();
12874 }
12875}
12876
12877bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12878 // FIXME: Need strict checking. In C89, we need to check for
12879 // any assignment, increment, decrement, function-calls, or
12880 // commas outside of a sizeof. In C99, it's the same list,
12881 // except that the aforementioned are allowed in unevaluated
12882 // expressions. Everything else falls under the
12883 // "may accept other forms of constant expressions" exception.
12884 //
12885 // Regular C++ code will not end up here (exceptions: language extensions,
12886 // OpenCL C++ etc), so the constant expression rules there don't matter.
12887 if (Init->isValueDependent()) {
12888 assert(Init->containsErrors() &&
12889 "Dependent code should only occur in error-recovery path.");
12890 return true;
12891 }
12892 const Expr *Culprit;
12893 if (Init->isConstantInitializer(Ctx&: Context, /*ForRef=*/false, Culprit: &Culprit))
12894 return false;
12895
12896 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
12897 if (getLangOpts().ObjCConstantLiterals && isa<ObjCObjectLiteral>(Val: Culprit)) {
12898
12899 // For collection literals iterate the elements to highlight which one is
12900 // the offender.
12901 if (auto ALE = dyn_cast<ObjCArrayLiteral>(Val: Init)) {
12902 for (auto *Elm : ALE->elements()) {
12903 if (!Elm->isConstantInitializer(Ctx&: Context)) {
12904 Diag(Loc: Elm->getExprLoc(),
12905 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12906 << ObjC().CheckLiteralKind(FromE: Init) << Elm->getSourceRange();
12907 return true;
12908 }
12909 }
12910 }
12911
12912 if (auto DLE = dyn_cast<ObjCDictionaryLiteral>(Val: Init)) {
12913 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
12914 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(Index: I);
12915
12916 // Check that the key is a string literal and is constant.
12917 if (!isa<ObjCStringLiteral>(Val: Elm.Key) ||
12918 !Elm.Key->isConstantInitializer(Ctx&: Context)) {
12919 Diag(Loc: Elm.Key->getExprLoc(),
12920 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12921 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Key->getSourceRange();
12922 return true;
12923 }
12924
12925 if (!Elm.Value->isConstantInitializer(Ctx&: Context)) {
12926 Diag(Loc: Elm.Value->getExprLoc(),
12927 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12928 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Value->getSourceRange();
12929 return true;
12930 }
12931 }
12932 }
12933
12934 Diag(Loc: Culprit->getExprLoc(),
12935 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
12936 << ObjC().CheckLiteralKind(FromE: Init) << Culprit->getSourceRange();
12937 return true;
12938 }
12939
12940 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12941 return true;
12942}
12943
12944namespace {
12945 // Visits an initialization expression to see if OrigDecl is evaluated in
12946 // its own initialization and throws a warning if it does.
12947 class SelfReferenceChecker
12948 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12949 Sema &S;
12950 Decl *OrigDecl;
12951 bool isRecordType;
12952 bool isPODType;
12953 bool isReferenceType;
12954 bool isInCXXOperatorCall;
12955
12956 bool isInitList;
12957 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12958
12959 public:
12960 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12961
12962 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12963 S(S), OrigDecl(OrigDecl) {
12964 isPODType = false;
12965 isRecordType = false;
12966 isReferenceType = false;
12967 isInCXXOperatorCall = false;
12968 isInitList = false;
12969 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
12970 isPODType = VD->getType().isPODType(Context: S.Context);
12971 isRecordType = VD->getType()->isRecordType();
12972 isReferenceType = VD->getType()->isReferenceType();
12973 }
12974 }
12975
12976 // For most expressions, just call the visitor. For initializer lists,
12977 // track the index of the field being initialized since fields are
12978 // initialized in order allowing use of previously initialized fields.
12979 void CheckExpr(Expr *E) {
12980 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
12981 if (!InitList) {
12982 Visit(S: E);
12983 return;
12984 }
12985
12986 // Track and increment the index here.
12987 isInitList = true;
12988 InitFieldIndex.push_back(Elt: 0);
12989 for (auto *Child : InitList->children()) {
12990 CheckExpr(E: cast<Expr>(Val: Child));
12991 ++InitFieldIndex.back();
12992 }
12993 InitFieldIndex.pop_back();
12994 }
12995
12996 // Returns true if MemberExpr is checked and no further checking is needed.
12997 // Returns false if additional checking is required.
12998 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12999 llvm::SmallVector<FieldDecl*, 4> Fields;
13000 Expr *Base = E;
13001 bool ReferenceField = false;
13002
13003 // Get the field members used.
13004 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13005 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
13006 if (!FD)
13007 return false;
13008 Fields.push_back(Elt: FD);
13009 if (FD->getType()->isReferenceType())
13010 ReferenceField = true;
13011 Base = ME->getBase()->IgnoreParenImpCasts();
13012 }
13013
13014 // Keep checking only if the base Decl is the same.
13015 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
13016 if (!DRE || DRE->getDecl() != OrigDecl)
13017 return false;
13018
13019 // A reference field can be bound to an unininitialized field.
13020 if (CheckReference && !ReferenceField)
13021 return true;
13022
13023 // Convert FieldDecls to their index number.
13024 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13025 for (const FieldDecl *I : llvm::reverse(C&: Fields))
13026 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
13027
13028 // See if a warning is needed by checking the first difference in index
13029 // numbers. If field being used has index less than the field being
13030 // initialized, then the use is safe.
13031 for (auto UsedIter = UsedFieldIndex.begin(),
13032 UsedEnd = UsedFieldIndex.end(),
13033 OrigIter = InitFieldIndex.begin(),
13034 OrigEnd = InitFieldIndex.end();
13035 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13036 if (*UsedIter < *OrigIter)
13037 return true;
13038 if (*UsedIter > *OrigIter)
13039 break;
13040 }
13041
13042 // TODO: Add a different warning which will print the field names.
13043 HandleDeclRefExpr(DRE);
13044 return true;
13045 }
13046
13047 // For most expressions, the cast is directly above the DeclRefExpr.
13048 // For conditional operators, the cast can be outside the conditional
13049 // operator if both expressions are DeclRefExpr's.
13050 void HandleValue(Expr *E) {
13051 E = E->IgnoreParens();
13052 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13053 HandleDeclRefExpr(DRE);
13054 return;
13055 }
13056
13057 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13058 Visit(S: CO->getCond());
13059 HandleValue(E: CO->getTrueExpr());
13060 HandleValue(E: CO->getFalseExpr());
13061 return;
13062 }
13063
13064 if (BinaryConditionalOperator *BCO =
13065 dyn_cast<BinaryConditionalOperator>(Val: E)) {
13066 Visit(S: BCO->getCond());
13067 HandleValue(E: BCO->getFalseExpr());
13068 return;
13069 }
13070
13071 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
13072 if (Expr *SE = OVE->getSourceExpr())
13073 HandleValue(E: SE);
13074 return;
13075 }
13076
13077 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13078 if (BO->getOpcode() == BO_Comma) {
13079 Visit(S: BO->getLHS());
13080 HandleValue(E: BO->getRHS());
13081 return;
13082 }
13083 }
13084
13085 if (isa<MemberExpr>(Val: E)) {
13086 if (isInitList) {
13087 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
13088 CheckReference: false /*CheckReference*/))
13089 return;
13090 }
13091
13092 Expr *Base = E->IgnoreParenImpCasts();
13093 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13094 // Check for static member variables and don't warn on them.
13095 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13096 return;
13097 Base = ME->getBase()->IgnoreParenImpCasts();
13098 }
13099 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
13100 HandleDeclRefExpr(DRE);
13101 return;
13102 }
13103
13104 Visit(S: E);
13105 }
13106
13107 // Reference types not handled in HandleValue are handled here since all
13108 // uses of references are bad, not just r-value uses.
13109 void VisitDeclRefExpr(DeclRefExpr *E) {
13110 if (isReferenceType)
13111 HandleDeclRefExpr(DRE: E);
13112 }
13113
13114 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13115 if (E->getCastKind() == CK_LValueToRValue) {
13116 HandleValue(E: E->getSubExpr());
13117 return;
13118 }
13119
13120 Inherited::VisitImplicitCastExpr(S: E);
13121 }
13122
13123 void VisitMemberExpr(MemberExpr *E) {
13124 if (isInitList) {
13125 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
13126 return;
13127 }
13128
13129 // Don't warn on arrays since they can be treated as pointers.
13130 if (E->getType()->canDecayToPointerType()) return;
13131
13132 // Warn when a non-static method call is followed by non-static member
13133 // field accesses, which is followed by a DeclRefExpr.
13134 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
13135 bool Warn = (MD && !MD->isStatic());
13136 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13137 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13138 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13139 Warn = false;
13140 Base = ME->getBase()->IgnoreParenImpCasts();
13141 }
13142
13143 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
13144 if (Warn)
13145 HandleDeclRefExpr(DRE);
13146 return;
13147 }
13148
13149 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13150 // Visit that expression.
13151 Visit(S: Base);
13152 }
13153
13154 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13155 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13156 Expr *Callee = E->getCallee();
13157
13158 if (isa<UnresolvedLookupExpr>(Val: Callee))
13159 return Inherited::VisitCXXOperatorCallExpr(S: E);
13160
13161 Visit(S: Callee);
13162 for (auto Arg: E->arguments())
13163 HandleValue(E: Arg->IgnoreParenImpCasts());
13164 }
13165
13166 void VisitLambdaExpr(LambdaExpr *E) {
13167 if (!isInCXXOperatorCall) {
13168 Inherited::VisitLambdaExpr(LE: E);
13169 return;
13170 }
13171
13172 for (Expr *Init : E->capture_inits())
13173 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
13174 HandleDeclRefExpr(DRE);
13175 else if (Init)
13176 Visit(S: Init);
13177 }
13178
13179 void VisitUnaryOperator(UnaryOperator *E) {
13180 // For POD record types, addresses of its own members are well-defined.
13181 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13182 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
13183 if (!isPODType)
13184 HandleValue(E: E->getSubExpr());
13185 return;
13186 }
13187
13188 if (E->isIncrementDecrementOp()) {
13189 HandleValue(E: E->getSubExpr());
13190 return;
13191 }
13192
13193 Inherited::VisitUnaryOperator(S: E);
13194 }
13195
13196 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13197
13198 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13199 if (E->getConstructor()->isCopyConstructor()) {
13200 Expr *ArgExpr = E->getArg(Arg: 0);
13201 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
13202 if (ILE->getNumInits() == 1)
13203 ArgExpr = ILE->getInit(Init: 0);
13204 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
13205 if (ICE->getCastKind() == CK_NoOp)
13206 ArgExpr = ICE->getSubExpr();
13207 HandleValue(E: ArgExpr);
13208 return;
13209 }
13210 Inherited::VisitCXXConstructExpr(S: E);
13211 }
13212
13213 void VisitCallExpr(CallExpr *E) {
13214 // Treat std::move as a use.
13215 if (E->isCallToStdMove()) {
13216 HandleValue(E: E->getArg(Arg: 0));
13217 return;
13218 }
13219
13220 Inherited::VisitCallExpr(CE: E);
13221 }
13222
13223 void VisitBinaryOperator(BinaryOperator *E) {
13224 if (E->isCompoundAssignmentOp()) {
13225 HandleValue(E: E->getLHS());
13226 Visit(S: E->getRHS());
13227 return;
13228 }
13229
13230 Inherited::VisitBinaryOperator(S: E);
13231 }
13232
13233 // A custom visitor for BinaryConditionalOperator is needed because the
13234 // regular visitor would check the condition and true expression separately
13235 // but both point to the same place giving duplicate diagnostics.
13236 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13237 Visit(S: E->getCond());
13238 Visit(S: E->getFalseExpr());
13239 }
13240
13241 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13242 Decl* ReferenceDecl = DRE->getDecl();
13243 if (OrigDecl != ReferenceDecl) return;
13244 unsigned diag;
13245 if (isReferenceType) {
13246 diag = diag::warn_uninit_self_reference_in_reference_init;
13247 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
13248 diag = diag::warn_static_self_reference_in_init;
13249 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
13250 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
13251 DRE->getDecl()->getType()->isRecordType()) {
13252 diag = diag::warn_uninit_self_reference_in_init;
13253 } else {
13254 // Local variables will be handled by the CFG analysis.
13255 return;
13256 }
13257
13258 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
13259 PD: S.PDiag(DiagID: diag)
13260 << DRE->getDecl() << OrigDecl->getLocation()
13261 << DRE->getSourceRange());
13262 }
13263 };
13264
13265 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13266 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13267 bool DirectInit) {
13268 // Parameters arguments are occassionially constructed with itself,
13269 // for instance, in recursive functions. Skip them.
13270 if (isa<ParmVarDecl>(Val: OrigDecl))
13271 return;
13272
13273 // Skip checking for file-scope constexpr variables - constant evaluation
13274 // will produce appropriate errors without needing runtime diagnostics.
13275 // Local constexpr should still emit runtime warnings.
13276 if (auto *VD = dyn_cast<VarDecl>(Val: OrigDecl);
13277 VD && VD->isConstexpr() && VD->isFileVarDecl())
13278 return;
13279
13280 E = E->IgnoreParens();
13281
13282 // Skip checking T a = a where T is not a record or reference type.
13283 // Doing so is a way to silence uninitialized warnings.
13284 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13285 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13286 if (ICE->getCastKind() == CK_LValueToRValue)
13287 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
13288 if (DRE->getDecl() == OrigDecl)
13289 return;
13290
13291 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13292 }
13293} // end anonymous namespace
13294
13295namespace {
13296 // Simple wrapper to add the name of a variable or (if no variable is
13297 // available) a DeclarationName into a diagnostic.
13298 struct VarDeclOrName {
13299 VarDecl *VDecl;
13300 DeclarationName Name;
13301
13302 friend const Sema::SemaDiagnosticBuilder &
13303 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13304 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13305 }
13306 };
13307} // end anonymous namespace
13308
13309QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13310 DeclarationName Name, QualType Type,
13311 TypeSourceInfo *TSI,
13312 SourceRange Range, bool DirectInit,
13313 Expr *Init) {
13314 bool IsInitCapture = !VDecl;
13315 assert((!VDecl || !VDecl->isInitCapture()) &&
13316 "init captures are expected to be deduced prior to initialization");
13317
13318 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13319
13320 DeducedType *Deduced = Type->getContainedDeducedType();
13321 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13322
13323 // Diagnose auto array declarations in C23, unless it's a supported extension.
13324 if (getLangOpts().C23 && Type->isArrayType() &&
13325 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13326 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13327 << (int)Deduced->getContainedAutoType()->getKeyword()
13328 << /*in array decl*/ 23 << Range;
13329 return QualType();
13330 }
13331
13332 // C++11 [dcl.spec.auto]p3
13333 if (!Init) {
13334 assert(VDecl && "no init for init capture deduction?");
13335
13336 // Except for class argument deduction, and then for an initializing
13337 // declaration only, i.e. no static at class scope or extern.
13338 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13339 VDecl->hasExternalStorage() ||
13340 VDecl->isStaticDataMember()) {
13341 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13342 << VDecl->getDeclName() << Type;
13343 return QualType();
13344 }
13345 }
13346
13347 ArrayRef<Expr*> DeduceInits;
13348 if (Init)
13349 DeduceInits = Init;
13350
13351 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13352 if (DirectInit && PL)
13353 DeduceInits = PL->exprs();
13354
13355 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13356 assert(VDecl && "non-auto type for init capture deduction?");
13357 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13358 InitializationKind Kind = InitializationKind::CreateForInit(
13359 Loc: VDecl->getLocation(), DirectInit, Init);
13360 // FIXME: Initialization should not be taking a mutable list of inits.
13361 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13362 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13363 Init: InitsCopy);
13364 }
13365
13366 if (DirectInit) {
13367 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13368 DeduceInits = IL->inits();
13369 }
13370
13371 // Deduction only works if we have exactly one source expression.
13372 if (DeduceInits.empty()) {
13373 // It isn't possible to write this directly, but it is possible to
13374 // end up in this situation with "auto x(some_pack...);"
13375 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13376 ? diag::err_init_capture_no_expression
13377 : diag::err_auto_var_init_no_expression)
13378 << VN << Type << Range;
13379 return QualType();
13380 }
13381
13382 if (DeduceInits.size() > 1) {
13383 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13384 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13385 : diag::err_auto_var_init_multiple_expressions)
13386 << VN << Type << Range;
13387 return QualType();
13388 }
13389
13390 Expr *DeduceInit = DeduceInits[0];
13391 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13392 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13393 ? diag::err_init_capture_paren_braces
13394 : diag::err_auto_var_init_paren_braces)
13395 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13396 return QualType();
13397 }
13398
13399 // Expressions default to 'id' when we're in a debugger.
13400 bool DefaultedAnyToId = false;
13401 if (getLangOpts().DebuggerCastResultToId &&
13402 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13403 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13404 if (Result.isInvalid()) {
13405 return QualType();
13406 }
13407 Init = Result.get();
13408 DefaultedAnyToId = true;
13409 }
13410
13411 // C++ [dcl.decomp]p1:
13412 // If the assignment-expression [...] has array type A and no ref-qualifier
13413 // is present, e has type cv A
13414 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13415 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13416 DeduceInit->getType()->isConstantArrayType())
13417 return Context.getQualifiedType(T: DeduceInit->getType(),
13418 Qs: Type.getQualifiers());
13419
13420 QualType DeducedType;
13421 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13422 TemplateDeductionResult Result =
13423 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13424 if (Result != TemplateDeductionResult::Success &&
13425 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13426 if (!IsInitCapture)
13427 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13428 else if (isa<InitListExpr>(Val: Init))
13429 Diag(Loc: Range.getBegin(),
13430 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13431 << VN
13432 << (DeduceInit->getType().isNull() ? TSI->getType()
13433 : DeduceInit->getType())
13434 << DeduceInit->getSourceRange();
13435 else
13436 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13437 << VN << TSI->getType()
13438 << (DeduceInit->getType().isNull() ? TSI->getType()
13439 : DeduceInit->getType())
13440 << DeduceInit->getSourceRange();
13441 }
13442
13443 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13444 // 'id' instead of a specific object type prevents most of our usual
13445 // checks.
13446 // We only want to warn outside of template instantiations, though:
13447 // inside a template, the 'id' could have come from a parameter.
13448 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13449 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13450 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13451 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13452 }
13453
13454 return DeducedType;
13455}
13456
13457bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13458 Expr *Init) {
13459 assert(!Init || !Init->containsErrors());
13460 QualType DeducedType = deduceVarTypeFromInitializer(
13461 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13462 Range: VDecl->getSourceRange(), DirectInit, Init);
13463 if (DeducedType.isNull()) {
13464 VDecl->setInvalidDecl();
13465 return true;
13466 }
13467
13468 VDecl->setType(DeducedType);
13469 assert(VDecl->isLinkageValid());
13470
13471 // In ARC, infer lifetime.
13472 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13473 VDecl->setInvalidDecl();
13474
13475 if (getLangOpts().OpenCL)
13476 deduceOpenCLAddressSpace(Var: VDecl);
13477
13478 if (getLangOpts().HLSL)
13479 HLSL().deduceAddressSpace(Decl: VDecl);
13480
13481 // If this is a redeclaration, check that the type we just deduced matches
13482 // the previously declared type.
13483 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13484 // We never need to merge the type, because we cannot form an incomplete
13485 // array of auto, nor deduce such a type.
13486 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13487 }
13488
13489 // Check the deduced type is valid for a variable declaration.
13490 CheckVariableDeclarationType(NewVD: VDecl);
13491 return VDecl->isInvalidDecl();
13492}
13493
13494void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13495 SourceLocation Loc) {
13496 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13497 Init = EWC->getSubExpr();
13498
13499 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13500 Init = CE->getSubExpr();
13501
13502 QualType InitType = Init->getType();
13503 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13504 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13505 "shouldn't be called if type doesn't have a non-trivial C struct");
13506 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13507 for (auto *I : ILE->inits()) {
13508 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13509 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13510 continue;
13511 SourceLocation SL = I->getExprLoc();
13512 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13513 }
13514 return;
13515 }
13516
13517 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13518 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13519 checkNonTrivialCUnion(QT: InitType, Loc,
13520 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13521 NonTrivialKind: NTCUK_Init);
13522 } else {
13523 // Assume all other explicit initializers involving copying some existing
13524 // object.
13525 // TODO: ignore any explicit initializers where we can guarantee
13526 // copy-elision.
13527 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13528 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13529 NonTrivialKind: NTCUK_Copy);
13530 }
13531}
13532
13533namespace {
13534
13535bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13536 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13537 // in the source code or implicitly by the compiler if it is in a union
13538 // defined in a system header and has non-trivial ObjC ownership
13539 // qualifications. We don't want those fields to participate in determining
13540 // whether the containing union is non-trivial.
13541 return FD->hasAttr<UnavailableAttr>();
13542}
13543
13544struct DiagNonTrivalCUnionDefaultInitializeVisitor
13545 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13546 void> {
13547 using Super =
13548 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13549 void>;
13550
13551 DiagNonTrivalCUnionDefaultInitializeVisitor(
13552 QualType OrigTy, SourceLocation OrigLoc,
13553 NonTrivialCUnionContext UseContext, Sema &S)
13554 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13555
13556 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13557 const FieldDecl *FD, bool InNonTrivialUnion) {
13558 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13559 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13560 Args&: InNonTrivialUnion);
13561 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13562 }
13563
13564 void visitARCStrong(QualType QT, const FieldDecl *FD,
13565 bool InNonTrivialUnion) {
13566 if (InNonTrivialUnion)
13567 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13568 << 1 << 0 << QT << FD->getName();
13569 }
13570
13571 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13572 if (InNonTrivialUnion)
13573 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13574 << 1 << 0 << QT << FD->getName();
13575 }
13576
13577 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13578 const auto *RD = QT->castAsRecordDecl();
13579 if (RD->isUnion()) {
13580 if (OrigLoc.isValid()) {
13581 bool IsUnion = false;
13582 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13583 IsUnion = OrigRD->isUnion();
13584 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13585 << 0 << OrigTy << IsUnion << UseContext;
13586 // Reset OrigLoc so that this diagnostic is emitted only once.
13587 OrigLoc = SourceLocation();
13588 }
13589 InNonTrivialUnion = true;
13590 }
13591
13592 if (InNonTrivialUnion)
13593 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13594 << 0 << 0 << QT.getUnqualifiedType() << "";
13595
13596 for (const FieldDecl *FD : RD->fields())
13597 if (!shouldIgnoreForRecordTriviality(FD))
13598 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13599 }
13600
13601 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13602
13603 // The non-trivial C union type or the struct/union type that contains a
13604 // non-trivial C union.
13605 QualType OrigTy;
13606 SourceLocation OrigLoc;
13607 NonTrivialCUnionContext UseContext;
13608 Sema &S;
13609};
13610
13611struct DiagNonTrivalCUnionDestructedTypeVisitor
13612 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13613 using Super =
13614 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13615
13616 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13617 SourceLocation OrigLoc,
13618 NonTrivialCUnionContext UseContext,
13619 Sema &S)
13620 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13621
13622 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13623 const FieldDecl *FD, bool InNonTrivialUnion) {
13624 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13625 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13626 Args&: InNonTrivialUnion);
13627 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13628 }
13629
13630 void visitARCStrong(QualType QT, const FieldDecl *FD,
13631 bool InNonTrivialUnion) {
13632 if (InNonTrivialUnion)
13633 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13634 << 1 << 1 << QT << FD->getName();
13635 }
13636
13637 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13638 if (InNonTrivialUnion)
13639 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13640 << 1 << 1 << QT << FD->getName();
13641 }
13642
13643 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13644 const auto *RD = QT->castAsRecordDecl();
13645 if (RD->isUnion()) {
13646 if (OrigLoc.isValid()) {
13647 bool IsUnion = false;
13648 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13649 IsUnion = OrigRD->isUnion();
13650 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13651 << 1 << OrigTy << IsUnion << UseContext;
13652 // Reset OrigLoc so that this diagnostic is emitted only once.
13653 OrigLoc = SourceLocation();
13654 }
13655 InNonTrivialUnion = true;
13656 }
13657
13658 if (InNonTrivialUnion)
13659 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13660 << 0 << 1 << QT.getUnqualifiedType() << "";
13661
13662 for (const FieldDecl *FD : RD->fields())
13663 if (!shouldIgnoreForRecordTriviality(FD))
13664 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13665 }
13666
13667 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13668 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13669 bool InNonTrivialUnion) {}
13670
13671 // The non-trivial C union type or the struct/union type that contains a
13672 // non-trivial C union.
13673 QualType OrigTy;
13674 SourceLocation OrigLoc;
13675 NonTrivialCUnionContext UseContext;
13676 Sema &S;
13677};
13678
13679struct DiagNonTrivalCUnionCopyVisitor
13680 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13681 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13682
13683 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13684 NonTrivialCUnionContext UseContext, Sema &S)
13685 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13686
13687 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13688 const FieldDecl *FD, bool InNonTrivialUnion) {
13689 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13690 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13691 Args&: InNonTrivialUnion);
13692 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13693 }
13694
13695 void visitARCStrong(QualType QT, const FieldDecl *FD,
13696 bool InNonTrivialUnion) {
13697 if (InNonTrivialUnion)
13698 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13699 << 1 << 2 << QT << FD->getName();
13700 }
13701
13702 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13703 if (InNonTrivialUnion)
13704 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13705 << 1 << 2 << QT << FD->getName();
13706 }
13707
13708 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13709 const auto *RD = QT->castAsRecordDecl();
13710 if (RD->isUnion()) {
13711 if (OrigLoc.isValid()) {
13712 bool IsUnion = false;
13713 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13714 IsUnion = OrigRD->isUnion();
13715 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13716 << 2 << OrigTy << IsUnion << UseContext;
13717 // Reset OrigLoc so that this diagnostic is emitted only once.
13718 OrigLoc = SourceLocation();
13719 }
13720 InNonTrivialUnion = true;
13721 }
13722
13723 if (InNonTrivialUnion)
13724 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13725 << 0 << 2 << QT.getUnqualifiedType() << "";
13726
13727 for (const FieldDecl *FD : RD->fields())
13728 if (!shouldIgnoreForRecordTriviality(FD))
13729 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13730 }
13731
13732 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13733 if (InNonTrivialUnion)
13734 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13735 << 1 << 2 << QT << FD->getName();
13736 }
13737
13738 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13739 const FieldDecl *FD, bool InNonTrivialUnion) {}
13740 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13741 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13742 bool InNonTrivialUnion) {}
13743
13744 // The non-trivial C union type or the struct/union type that contains a
13745 // non-trivial C union.
13746 QualType OrigTy;
13747 SourceLocation OrigLoc;
13748 NonTrivialCUnionContext UseContext;
13749 Sema &S;
13750};
13751
13752} // namespace
13753
13754void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13755 NonTrivialCUnionContext UseContext,
13756 unsigned NonTrivialKind) {
13757 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13758 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13759 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13760 "shouldn't be called if type doesn't have a non-trivial C union");
13761
13762 if ((NonTrivialKind & NTCUK_Init) &&
13763 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13764 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13765 .visit(FT: QT, Args: nullptr, Args: false);
13766 if ((NonTrivialKind & NTCUK_Destruct) &&
13767 QT.hasNonTrivialToPrimitiveDestructCUnion())
13768 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13769 .visit(FT: QT, Args: nullptr, Args: false);
13770 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13771 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13772 .visit(FT: QT, Args: nullptr, Args: false);
13773}
13774
13775bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13776 const VarDecl *Dcl) {
13777 if (!getLangOpts().CPlusPlus)
13778 return false;
13779
13780 // We only need to warn if the definition is in a header file, so wait to
13781 // diagnose until we've seen the definition.
13782 if (!Dcl->isThisDeclarationADefinition())
13783 return false;
13784
13785 // If an object is defined in a source file, its definition can't get
13786 // duplicated since it will never appear in more than one TU.
13787 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
13788 return false;
13789
13790 // If the variable we're looking at is a static local, then we actually care
13791 // about the properties of the function containing it.
13792 const ValueDecl *Target = Dcl;
13793 // VarDecls and FunctionDecls have different functions for checking
13794 // inline-ness, and whether they were originally templated, so we have to
13795 // call the appropriate functions manually.
13796 bool TargetIsInline = Dcl->isInline();
13797 bool TargetWasTemplated =
13798 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13799
13800 // Update the Target and TargetIsInline property if necessary
13801 if (Dcl->isStaticLocal()) {
13802 const DeclContext *Ctx = Dcl->getDeclContext();
13803 if (!Ctx)
13804 return false;
13805
13806 const FunctionDecl *FunDcl =
13807 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
13808 if (!FunDcl)
13809 return false;
13810
13811 Target = FunDcl;
13812 // IsInlined() checks for the C++ inline property
13813 TargetIsInline = FunDcl->isInlined();
13814 TargetWasTemplated =
13815 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
13816 }
13817
13818 // Non-inline functions/variables can only legally appear in one TU
13819 // unless they were part of a template. Unfortunately, making complex
13820 // template instantiations visible is infeasible in practice, since
13821 // everything the template depends on also has to be visible. To avoid
13822 // giving impractical-to-fix warnings, don't warn if we're inside
13823 // something that was templated, even on inline stuff.
13824 if (!TargetIsInline || TargetWasTemplated)
13825 return false;
13826
13827 // If the object isn't hidden, the dynamic linker will prevent duplication.
13828 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13829
13830 // The target is "hidden" (from the dynamic linker) if:
13831 // 1. On posix, it has hidden visibility, or
13832 // 2. On windows, it has no import/export annotation, and neither does the
13833 // class which directly contains it.
13834 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13835 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13836 return false;
13837
13838 // If the variable isn't directly annotated, check to see if it's a member
13839 // of an annotated class.
13840 const CXXRecordDecl *Ctx =
13841 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
13842 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13843 return false;
13844
13845 } else if (Lnk.getVisibility() != HiddenVisibility) {
13846 // Posix case
13847 return false;
13848 }
13849
13850 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13851 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
13852 return false;
13853
13854 return true;
13855}
13856
13857// Determine whether the object seems mutable for the purpose of diagnosing
13858// possible unique object duplication, i.e. non-const-qualified, and
13859// not an always-constant type like a function.
13860// Not perfect: doesn't account for mutable members, for example, or
13861// elements of container types.
13862// For nested pointers, any individual level being non-const is sufficient.
13863static bool looksMutable(QualType T, const ASTContext &Ctx) {
13864 T = T.getNonReferenceType();
13865 if (T->isFunctionType())
13866 return false;
13867 if (!T.isConstant(Ctx))
13868 return true;
13869 if (T->isPointerType())
13870 return looksMutable(T: T->getPointeeType(), Ctx);
13871 return false;
13872}
13873
13874void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
13875 // If this object has external linkage and hidden visibility, it might be
13876 // duplicated when built into a shared library, which causes problems if it's
13877 // mutable (since the copies won't be in sync) or its initialization has side
13878 // effects (since it will run once per copy instead of once globally).
13879
13880 // Don't diagnose if we're inside a template, because it's not practical to
13881 // fix the warning in most cases.
13882 if (!VD->isTemplated() &&
13883 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
13884
13885 QualType Type = VD->getType();
13886 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
13887 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
13888 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13889 }
13890
13891 // To keep false positives low, only warn if we're certain that the
13892 // initializer has side effects. Don't warn on operator new, since a mutable
13893 // pointer will trigger the previous warning, and an immutable pointer
13894 // getting duplicated just results in a little extra memory usage.
13895 const Expr *Init = VD->getAnyInitializer();
13896 if (Init &&
13897 Init->HasSideEffects(Ctx: VD->getASTContext(),
13898 /*IncludePossibleEffects=*/false) &&
13899 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
13900 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
13901 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13902 }
13903 }
13904}
13905
13906void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13907 llvm::scope_exit ResetDeclForInitializer([this]() {
13908 if (!this->ExprEvalContexts.empty())
13909 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13910 });
13911
13912 // If there is no declaration, there was an error parsing it. Just ignore
13913 // the initializer.
13914 if (!RealDecl) {
13915 return;
13916 }
13917
13918 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
13919 if (!Method->isInvalidDecl()) {
13920 // Pure-specifiers are handled in ActOnPureSpecifier.
13921 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
13922 << Method->getDeclName() << Init->getSourceRange();
13923 Method->setInvalidDecl();
13924 }
13925 return;
13926 }
13927
13928 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
13929 if (!VDecl) {
13930 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13931 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
13932 RealDecl->setInvalidDecl();
13933 return;
13934 }
13935
13936 if (VDecl->isInvalidDecl()) {
13937 ExprResult Recovery =
13938 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
13939 if (Expr *E = Recovery.get())
13940 VDecl->setInit(E);
13941 return;
13942 }
13943
13944 // __amdgpu_feature_predicate_t cannot be initialised
13945 if (VDecl->getType().getDesugaredType(Context) ==
13946 Context.AMDGPUFeaturePredicateTy) {
13947 Diag(Loc: VDecl->getLocation(),
13948 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
13949 << VDecl;
13950 VDecl->setInvalidDecl();
13951 return;
13952 }
13953
13954 // WebAssembly tables can't be used to initialise a variable.
13955 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13956 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
13957 VDecl->setInvalidDecl();
13958 return;
13959 }
13960
13961 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13962 if (VDecl->getType()->isUndeducedType()) {
13963 if (Init->containsErrors()) {
13964 // Invalidate the decl as we don't know the type for recovery-expr yet.
13965 RealDecl->setInvalidDecl();
13966 VDecl->setInit(Init);
13967 return;
13968 }
13969
13970 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
13971 assert(VDecl->isInvalidDecl() &&
13972 "decl should be invalidated when deduce fails");
13973 if (auto *RecoveryExpr =
13974 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init})
13975 .get())
13976 VDecl->setInit(RecoveryExpr);
13977 return;
13978 }
13979 }
13980
13981 this->CheckAttributesOnDeducedType(D: RealDecl);
13982
13983 // we don't initialize groupshared variables so warn and return
13984 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
13985 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_hlsl_groupshared_init);
13986 return;
13987 }
13988
13989 // dllimport cannot be used on variable definitions.
13990 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13991 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
13992 VDecl->setInvalidDecl();
13993 return;
13994 }
13995
13996 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13997 // the identifier has external or internal linkage, the declaration shall
13998 // have no initializer for the identifier.
13999 // C++14 [dcl.init]p5 is the same restriction for C++.
14000 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14001 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
14002 VDecl->setInvalidDecl();
14003 return;
14004 }
14005
14006 if (!VDecl->getType()->isDependentType()) {
14007 // A definition must end up with a complete type, which means it must be
14008 // complete with the restriction that an array type might be completed by
14009 // the initializer; note that later code assumes this restriction.
14010 QualType BaseDeclType = VDecl->getType();
14011 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
14012 BaseDeclType = Array->getElementType();
14013 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
14014 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14015 RealDecl->setInvalidDecl();
14016 return;
14017 }
14018
14019 // The variable can not have an abstract class type.
14020 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
14021 DiagID: diag::err_abstract_type_in_decl,
14022 Args: AbstractVariableType))
14023 VDecl->setInvalidDecl();
14024 }
14025
14026 // C++ [module.import/6]
14027 // ...
14028 // A header unit shall not contain a definition of a non-inline function or
14029 // variable whose name has external linkage.
14030 //
14031 // We choose to allow weak & selectany definitions, as they are common in
14032 // headers, and have semantics similar to inline definitions which are allowed
14033 // in header units.
14034 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14035 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14036 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14037 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
14038 !VDecl->getInstantiatedFromStaticDataMember() &&
14039 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14040 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
14041 VDecl->setInvalidDecl();
14042 }
14043
14044 // If adding the initializer will turn this declaration into a definition,
14045 // and we already have a definition for this variable, diagnose or otherwise
14046 // handle the situation.
14047 if (VarDecl *Def = VDecl->getDefinition())
14048 if (Def != VDecl &&
14049 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14050 !VDecl->isThisDeclarationADemotedDefinition() &&
14051 checkVarDeclRedefinition(Old: Def, New: VDecl))
14052 return;
14053
14054 if (getLangOpts().CPlusPlus) {
14055 // C++ [class.static.data]p4
14056 // If a static data member is of const integral or const
14057 // enumeration type, its declaration in the class definition can
14058 // specify a constant-initializer which shall be an integral
14059 // constant expression (5.19). In that case, the member can appear
14060 // in integral constant expressions. The member shall still be
14061 // defined in a namespace scope if it is used in the program and the
14062 // namespace scope definition shall not contain an initializer.
14063 //
14064 // We already performed a redefinition check above, but for static
14065 // data members we also need to check whether there was an in-class
14066 // declaration with an initializer.
14067 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14068 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
14069 << VDecl->getDeclName();
14070 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14071 DiagID: diag::note_previous_initializer)
14072 << 0;
14073 return;
14074 }
14075
14076 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
14077 VDecl->setInvalidDecl();
14078 return;
14079 }
14080 }
14081
14082 // If the variable has an initializer and local storage, check whether
14083 // anything jumps over the initialization.
14084 if (VDecl->hasLocalStorage())
14085 setFunctionHasBranchProtectedScope();
14086
14087 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14088 // a kernel function cannot be initialized."
14089 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14090 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
14091 VDecl->setInvalidDecl();
14092 return;
14093 }
14094
14095 // The LoaderUninitialized attribute acts as a definition (of undef).
14096 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14097 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
14098 VDecl->setInvalidDecl();
14099 return;
14100 }
14101
14102 if (getLangOpts().HLSL)
14103 if (!HLSL().handleInitialization(VDecl, Init))
14104 return;
14105
14106 // Get the decls type and save a reference for later, since
14107 // CheckInitializerTypes may change it.
14108 QualType DclT = VDecl->getType(), SavT = DclT;
14109
14110 // Expressions default to 'id' when we're in a debugger
14111 // and we are assigning it to a variable of Objective-C pointer type.
14112 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14113 Init->getType() == Context.UnknownAnyTy) {
14114 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
14115 if (!Result.isUsable()) {
14116 VDecl->setInvalidDecl();
14117 return;
14118 }
14119 Init = Result.get();
14120 }
14121
14122 // Perform the initialization.
14123 bool InitializedFromParenListExpr = false;
14124 bool IsParenListInit = false;
14125 if (!VDecl->isInvalidDecl()) {
14126 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
14127 InitializationKind Kind = InitializationKind::CreateForInit(
14128 Loc: VDecl->getLocation(), DirectInit, Init);
14129
14130 MultiExprArg Args = Init;
14131 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
14132 Args =
14133 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14134 InitializedFromParenListExpr = true;
14135 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
14136 Args = CXXDirectInit->getInitExprs();
14137 InitializedFromParenListExpr = true;
14138 }
14139
14140 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14141 /*TopLevelOfInitList=*/false,
14142 /*TreatUnavailableAsInvalid=*/false);
14143 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
14144 if (!Result.isUsable()) {
14145 // If the provided initializer fails to initialize the var decl,
14146 // we attach a recovery expr for better recovery.
14147 auto RecoveryExpr =
14148 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
14149 if (RecoveryExpr.get())
14150 VDecl->setInit(RecoveryExpr.get());
14151 // In general, for error recovery purposes, the initializer doesn't play
14152 // part in the valid bit of the declaration. There are a few exceptions:
14153 // 1) if the var decl has a deduced auto type, and the type cannot be
14154 // deduced by an invalid initializer;
14155 // 2) if the var decl is a decomposition decl with a non-deduced type,
14156 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14157 // Case 1) was already handled elsewhere.
14158 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
14159 VDecl->setInvalidDecl();
14160 return;
14161 }
14162
14163 Init = Result.getAs<Expr>();
14164 IsParenListInit = !InitSeq.steps().empty() &&
14165 InitSeq.step_begin()->Kind ==
14166 InitializationSequence::SK_ParenthesizedListInit;
14167 QualType VDeclType = VDecl->getType();
14168 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14169 !VDeclType->isDependentType() &&
14170 Context.getAsIncompleteArrayType(T: VDeclType) &&
14171 Context.getAsIncompleteArrayType(T: Init->getType())) {
14172 // Bail out if it is not possible to deduce array size from the
14173 // initializer.
14174 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
14175 << VDeclType;
14176 VDecl->setInvalidDecl();
14177 return;
14178 }
14179 }
14180
14181 // Check for self-references within variable initializers.
14182 // Variables declared within a function/method body (except for references)
14183 // are handled by a dataflow analysis.
14184 // This is undefined behavior in C++, but valid in C.
14185 if (getLangOpts().CPlusPlus)
14186 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14187 VDecl->getType()->isReferenceType())
14188 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
14189
14190 // If the type changed, it means we had an incomplete type that was
14191 // completed by the initializer. For example:
14192 // int ary[] = { 1, 3, 5 };
14193 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14194 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14195 VDecl->setType(DclT);
14196
14197 if (!VDecl->isInvalidDecl()) {
14198 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
14199
14200 if (VDecl->hasAttr<BlocksAttr>())
14201 ObjC().checkRetainCycles(Var: VDecl, Init);
14202
14203 // It is safe to assign a weak reference into a strong variable.
14204 // Although this code can still have problems:
14205 // id x = self.weakProp;
14206 // id y = self.weakProp;
14207 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14208 // paths through the function. This should be revisited if
14209 // -Wrepeated-use-of-weak is made flow-sensitive.
14210 if (FunctionScopeInfo *FSI = getCurFunction())
14211 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14212 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14213 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14214 Loc: Init->getBeginLoc()))
14215 FSI->markSafeWeakUse(E: Init);
14216 }
14217
14218 // The initialization is usually a full-expression.
14219 //
14220 // FIXME: If this is a braced initialization of an aggregate, it is not
14221 // an expression, and each individual field initializer is a separate
14222 // full-expression. For instance, in:
14223 //
14224 // struct Temp { ~Temp(); };
14225 // struct S { S(Temp); };
14226 // struct T { S a, b; } t = { Temp(), Temp() }
14227 //
14228 // we should destroy the first Temp before constructing the second.
14229
14230 // Set context flag for OverflowBehaviorType initialization analysis
14231 llvm::SaveAndRestore OBTAssignmentContext(InOverflowBehaviorAssignmentContext,
14232 true);
14233 ExprResult Result =
14234 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
14235 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
14236 if (!Result.isUsable()) {
14237 VDecl->setInvalidDecl();
14238 return;
14239 }
14240 Init = Result.get();
14241
14242 // Attach the initializer to the decl.
14243 VDecl->setInit(Init);
14244
14245 if (VDecl->isLocalVarDecl()) {
14246 // Don't check the initializer if the declaration is malformed.
14247 if (VDecl->isInvalidDecl()) {
14248 // do nothing
14249
14250 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14251 // This is true even in C++ for OpenCL.
14252 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14253 CheckForConstantInitializer(Init);
14254
14255 // Otherwise, C++ does not restrict the initializer.
14256 } else if (getLangOpts().CPlusPlus) {
14257 // do nothing
14258
14259 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14260 // static storage duration shall be constant expressions or string literals.
14261 } else if (VDecl->getStorageClass() == SC_Static) {
14262 // Avoid evaluating the initializer twice for constexpr variables. It will
14263 // be evaluated later.
14264 if (!VDecl->isConstexpr())
14265 CheckForConstantInitializer(Init);
14266
14267 // C89 is stricter than C99 for aggregate initializers.
14268 // C89 6.5.7p3: All the expressions [...] in an initializer list
14269 // for an object that has aggregate or union type shall be
14270 // constant expressions.
14271 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14272 isa<InitListExpr>(Val: Init)) {
14273 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
14274 }
14275
14276 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
14277 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
14278 if (VDecl->hasLocalStorage())
14279 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14280 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14281 VDecl->getLexicalDeclContext()->isRecord()) {
14282 // This is an in-class initialization for a static data member, e.g.,
14283 //
14284 // struct S {
14285 // static const int value = 17;
14286 // };
14287
14288 // C++ [class.mem]p4:
14289 // A member-declarator can contain a constant-initializer only
14290 // if it declares a static member (9.4) of const integral or
14291 // const enumeration type, see 9.4.2.
14292 //
14293 // C++11 [class.static.data]p3:
14294 // If a non-volatile non-inline const static data member is of integral
14295 // or enumeration type, its declaration in the class definition can
14296 // specify a brace-or-equal-initializer in which every initializer-clause
14297 // that is an assignment-expression is a constant expression. A static
14298 // data member of literal type can be declared in the class definition
14299 // with the constexpr specifier; if so, its declaration shall specify a
14300 // brace-or-equal-initializer in which every initializer-clause that is
14301 // an assignment-expression is a constant expression.
14302
14303 // Do nothing on dependent types.
14304 if (DclT->isDependentType()) {
14305
14306 // Allow any 'static constexpr' members, whether or not they are of literal
14307 // type. We separately check that every constexpr variable is of literal
14308 // type.
14309 } else if (VDecl->isConstexpr()) {
14310
14311 // Require constness.
14312 } else if (!DclT.isConstQualified()) {
14313 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
14314 << Init->getSourceRange();
14315 VDecl->setInvalidDecl();
14316
14317 // We allow integer constant expressions in all cases.
14318 } else if (DclT->isIntegralOrEnumerationType()) {
14319 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14320 // In C++11, a non-constexpr const static data member with an
14321 // in-class initializer cannot be volatile.
14322 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
14323
14324 // We allow foldable floating-point constants as an extension.
14325 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14326 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14327 // it anyway and provide a fixit to add the 'constexpr'.
14328 if (getLangOpts().CPlusPlus11) {
14329 Diag(Loc: VDecl->getLocation(),
14330 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
14331 << DclT << Init->getSourceRange();
14332 Diag(Loc: VDecl->getBeginLoc(),
14333 DiagID: diag::note_in_class_initializer_float_type_cxx11)
14334 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14335 } else {
14336 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14337 << DclT << Init->getSourceRange();
14338
14339 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14340 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14341 << Init->getSourceRange();
14342 VDecl->setInvalidDecl();
14343 }
14344 }
14345
14346 // Suggest adding 'constexpr' in C++11 for literal types.
14347 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14348 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14349 << DclT << Init->getSourceRange()
14350 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14351 VDecl->setConstexpr(true);
14352
14353 } else {
14354 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14355 << DclT << Init->getSourceRange();
14356 VDecl->setInvalidDecl();
14357 }
14358 } else if (VDecl->isFileVarDecl()) {
14359 // In C, extern is typically used to avoid tentative definitions when
14360 // declaring variables in headers, but adding an initializer makes it a
14361 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14362 // In C++, extern is often used to give implicitly static const variables
14363 // external linkage, so don't warn in that case. If selectany is present,
14364 // this might be header code intended for C and C++ inclusion, so apply the
14365 // C++ rules.
14366 if (VDecl->getStorageClass() == SC_Extern &&
14367 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14368 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14369 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14370 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14371 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14372
14373 // In Microsoft C++ mode, a const variable defined in namespace scope has
14374 // external linkage by default if the variable is declared with
14375 // __declspec(dllexport).
14376 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14377 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14378 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14379 VDecl->setStorageClass(SC_Extern);
14380
14381 // C99 6.7.8p4. All file scoped initializers need to be constant.
14382 // Avoid duplicate diagnostics for constexpr variables.
14383 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14384 !VDecl->isConstexpr())
14385 CheckForConstantInitializer(Init);
14386 }
14387
14388 QualType InitType = Init->getType();
14389 if (!InitType.isNull() &&
14390 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14391 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14392 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14393
14394 // We will represent direct-initialization similarly to copy-initialization:
14395 // int x(1); -as-> int x = 1;
14396 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14397 //
14398 // Clients that want to distinguish between the two forms, can check for
14399 // direct initializer using VarDecl::getInitStyle().
14400 // A major benefit is that clients that don't particularly care about which
14401 // exactly form was it (like the CodeGen) can handle both cases without
14402 // special case code.
14403
14404 // C++ 8.5p11:
14405 // The form of initialization (using parentheses or '=') matters
14406 // when the entity being initialized has class type.
14407 if (InitializedFromParenListExpr) {
14408 assert(DirectInit && "Call-style initializer must be direct init.");
14409 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14410 : VarDecl::CallInit);
14411 } else if (DirectInit) {
14412 // This must be list-initialization. No other way is direct-initialization.
14413 VDecl->setInitStyle(VarDecl::ListInit);
14414 }
14415
14416 if (LangOpts.OpenMP &&
14417 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14418 VDecl->isFileVarDecl())
14419 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14420 CheckCompleteVariableDeclaration(VD: VDecl);
14421
14422 if (LangOpts.OpenACC && !InitType.isNull())
14423 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14424}
14425
14426void Sema::ActOnInitializerError(Decl *D) {
14427 // Our main concern here is re-establishing invariants like "a
14428 // variable's type is either dependent or complete".
14429 if (!D || D->isInvalidDecl()) return;
14430
14431 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14432 if (!VD) return;
14433
14434 // Bindings are not usable if we can't make sense of the initializer.
14435 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14436 for (auto *BD : DD->bindings())
14437 BD->setInvalidDecl();
14438
14439 // Auto types are meaningless if we can't make sense of the initializer.
14440 if (VD->getType()->isUndeducedType()) {
14441 D->setInvalidDecl();
14442 return;
14443 }
14444
14445 QualType Ty = VD->getType();
14446 if (Ty->isDependentType()) return;
14447
14448 // Require a complete type.
14449 if (RequireCompleteType(Loc: VD->getLocation(),
14450 T: Context.getBaseElementType(QT: Ty),
14451 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14452 VD->setInvalidDecl();
14453 return;
14454 }
14455
14456 // Require a non-abstract type.
14457 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14458 DiagID: diag::err_abstract_type_in_decl,
14459 Args: AbstractVariableType)) {
14460 VD->setInvalidDecl();
14461 return;
14462 }
14463
14464 // Don't bother complaining about constructors or destructors,
14465 // though.
14466}
14467
14468void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14469 // If there is no declaration, there was an error parsing it. Just ignore it.
14470 if (!RealDecl)
14471 return;
14472
14473 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14474 QualType Type = Var->getType();
14475
14476 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14477 Diag(Loc: Var->getLocation(),
14478 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14479 << Var;
14480 Var->setInvalidDecl();
14481 return;
14482 }
14483 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14484 if (isa<DecompositionDecl>(Val: RealDecl)) {
14485 Diag(Loc: Var->getLocation(), DiagID: diag::err_decomp_decl_requires_init) << Var;
14486 Var->setInvalidDecl();
14487 return;
14488 }
14489
14490 if (Type->isUndeducedType() &&
14491 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14492 return;
14493
14494 this->CheckAttributesOnDeducedType(D: RealDecl);
14495
14496 // C++11 [class.static.data]p3: A static data member can be declared with
14497 // the constexpr specifier; if so, its declaration shall specify
14498 // a brace-or-equal-initializer.
14499 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14500 // the definition of a variable [...] or the declaration of a static data
14501 // member.
14502 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14503 !Var->isThisDeclarationADemotedDefinition()) {
14504 if (Var->isStaticDataMember()) {
14505 // C++1z removes the relevant rule; the in-class declaration is always
14506 // a definition there.
14507 if (!getLangOpts().CPlusPlus17 &&
14508 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14509 Diag(Loc: Var->getLocation(),
14510 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14511 << Var;
14512 Var->setInvalidDecl();
14513 return;
14514 }
14515 } else {
14516 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14517 Var->setInvalidDecl();
14518 return;
14519 }
14520 }
14521
14522 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14523 // be initialized.
14524 if (!Var->isInvalidDecl() &&
14525 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14526 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14527 bool HasConstExprDefaultConstructor = false;
14528 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14529 for (auto *Ctor : RD->ctors()) {
14530 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14531 Ctor->getMethodQualifiers().getAddressSpace() ==
14532 LangAS::opencl_constant) {
14533 HasConstExprDefaultConstructor = true;
14534 }
14535 }
14536 }
14537 if (!HasConstExprDefaultConstructor) {
14538 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14539 Var->setInvalidDecl();
14540 return;
14541 }
14542 }
14543
14544 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14545 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14546 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14547 Var->setInvalidDecl();
14548 return;
14549 }
14550
14551 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14552 if (Var->getStorageClass() == SC_Extern) {
14553 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14554 << Var;
14555 Var->setInvalidDecl();
14556 return;
14557 }
14558 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14559 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14560 Var->setInvalidDecl();
14561 return;
14562 }
14563 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14564 if (!RD->hasTrivialDefaultConstructor()) {
14565 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14566 Var->setInvalidDecl();
14567 return;
14568 }
14569 }
14570 // The declaration is uninitialized, no need for further checks.
14571 return;
14572 }
14573
14574 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14575 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14576 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14577 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14578 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14579 NonTrivialKind: NTCUK_Init);
14580
14581 switch (DefKind) {
14582 case VarDecl::Definition:
14583 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14584 break;
14585
14586 // We have an out-of-line definition of a static data member
14587 // that has an in-class initializer, so we type-check this like
14588 // a declaration.
14589 //
14590 [[fallthrough]];
14591
14592 case VarDecl::DeclarationOnly:
14593 // It's only a declaration.
14594
14595 // Block scope. C99 6.7p7: If an identifier for an object is
14596 // declared with no linkage (C99 6.2.2p6), the type for the
14597 // object shall be complete.
14598 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14599 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14600 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14601 DiagID: diag::err_typecheck_decl_incomplete_type))
14602 Var->setInvalidDecl();
14603
14604 // Make sure that the type is not abstract.
14605 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14606 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14607 DiagID: diag::err_abstract_type_in_decl,
14608 Args: AbstractVariableType))
14609 Var->setInvalidDecl();
14610 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14611 Var->getStorageClass() == SC_PrivateExtern) {
14612 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14613 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14614 }
14615
14616 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14617 !Var->isInvalidDecl())
14618 ExternalDeclarations.push_back(Elt: Var);
14619
14620 return;
14621
14622 case VarDecl::TentativeDefinition:
14623 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14624 // object that has file scope without an initializer, and without a
14625 // storage-class specifier or with the storage-class specifier "static",
14626 // constitutes a tentative definition. Note: A tentative definition with
14627 // external linkage is valid (C99 6.2.2p5).
14628 if (!Var->isInvalidDecl()) {
14629 if (const IncompleteArrayType *ArrayT
14630 = Context.getAsIncompleteArrayType(T: Type)) {
14631 if (RequireCompleteSizedType(
14632 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14633 DiagID: diag::err_array_incomplete_or_sizeless_type))
14634 Var->setInvalidDecl();
14635 }
14636 if (Var->getStorageClass() == SC_Static) {
14637 // C99 6.9.2p3: If the declaration of an identifier for an object is
14638 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14639 // declared type shall not be an incomplete type.
14640 // NOTE: code such as the following
14641 // static struct s;
14642 // struct s { int a; };
14643 // is accepted by gcc. Hence here we issue a warning instead of
14644 // an error and we do not invalidate the static declaration.
14645 // NOTE: to avoid multiple warnings, only check the first declaration.
14646 if (Var->isFirstDecl())
14647 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14648 DiagID: diag::ext_typecheck_decl_incomplete_type,
14649 Args: Type->isArrayType());
14650 }
14651 }
14652
14653 // Record the tentative definition; we're done.
14654 if (!Var->isInvalidDecl())
14655 TentativeDefinitions.push_back(LocalValue: Var);
14656 return;
14657 }
14658
14659 // Provide a specific diagnostic for uninitialized variable definitions
14660 // with incomplete array type, unless it is a global unbounded HLSL resource
14661 // array.
14662 if (Type->isIncompleteArrayType() &&
14663 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14664 Type->isHLSLResourceRecordArray())) {
14665 if (Var->isConstexpr())
14666 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14667 << Var;
14668 else
14669 Diag(Loc: Var->getLocation(),
14670 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14671 Var->setInvalidDecl();
14672 return;
14673 }
14674
14675 // Provide a specific diagnostic for uninitialized variable
14676 // definitions with reference type.
14677 if (Type->isReferenceType()) {
14678 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14679 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14680 return;
14681 }
14682
14683 // Do not attempt to type-check the default initializer for a
14684 // variable with dependent type.
14685 if (Type->isDependentType())
14686 return;
14687
14688 if (Var->isInvalidDecl())
14689 return;
14690
14691 if (!Var->hasAttr<AliasAttr>()) {
14692 if (RequireCompleteType(Loc: Var->getLocation(),
14693 T: Context.getBaseElementType(QT: Type),
14694 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14695 Var->setInvalidDecl();
14696 return;
14697 }
14698 } else {
14699 return;
14700 }
14701
14702 // The variable can not have an abstract class type.
14703 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14704 DiagID: diag::err_abstract_type_in_decl,
14705 Args: AbstractVariableType)) {
14706 Var->setInvalidDecl();
14707 return;
14708 }
14709
14710 // In C, if the definition is const-qualified and has no initializer, it
14711 // is left uninitialized unless it has static or thread storage duration.
14712 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14713 unsigned DiagID = diag::warn_default_init_const_unsafe;
14714 if (Var->getStorageDuration() == SD_Static ||
14715 Var->getStorageDuration() == SD_Thread)
14716 DiagID = diag::warn_default_init_const;
14717
14718 bool EmitCppCompat = !Diags.isIgnored(
14719 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14720 Loc: Var->getLocation());
14721
14722 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14723 }
14724
14725 // Check for jumps past the implicit initializer. C++0x
14726 // clarifies that this applies to a "variable with automatic
14727 // storage duration", not a "local variable".
14728 // C++11 [stmt.dcl]p3
14729 // A program that jumps from a point where a variable with automatic
14730 // storage duration is not in scope to a point where it is in scope is
14731 // ill-formed unless the variable has scalar type, class type with a
14732 // trivial default constructor and a trivial destructor, a cv-qualified
14733 // version of one of these types, or an array of one of the preceding
14734 // types and is declared without an initializer.
14735 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14736 if (const auto *CXXRecord =
14737 Context.getBaseElementType(QT: Type)->getAsCXXRecordDecl()) {
14738 // Mark the function (if we're in one) for further checking even if the
14739 // looser rules of C++11 do not require such checks, so that we can
14740 // diagnose incompatibilities with C++98.
14741 if (!CXXRecord->isPOD())
14742 setFunctionHasBranchProtectedScope();
14743 }
14744 }
14745 // In OpenCL, we can't initialize objects in the __local address space,
14746 // even implicitly, so don't synthesize an implicit initializer.
14747 if (getLangOpts().OpenCL &&
14748 Var->getType().getAddressSpace() == LangAS::opencl_local)
14749 return;
14750
14751 // Handle HLSL uninitialized decls
14752 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14753 return;
14754
14755 // HLSL input & push-constant variables are expected to be externally
14756 // initialized, even when marked `static`.
14757 if (getLangOpts().HLSL &&
14758 hlsl::isInitializedByPipeline(AS: Var->getType().getAddressSpace()))
14759 return;
14760
14761 // C++03 [dcl.init]p9:
14762 // If no initializer is specified for an object, and the
14763 // object is of (possibly cv-qualified) non-POD class type (or
14764 // array thereof), the object shall be default-initialized; if
14765 // the object is of const-qualified type, the underlying class
14766 // type shall have a user-declared default
14767 // constructor. Otherwise, if no initializer is specified for
14768 // a non- static object, the object and its subobjects, if
14769 // any, have an indeterminate initial value); if the object
14770 // or any of its subobjects are of const-qualified type, the
14771 // program is ill-formed.
14772 // C++0x [dcl.init]p11:
14773 // If no initializer is specified for an object, the object is
14774 // default-initialized; [...].
14775 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14776 InitializationKind Kind
14777 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14778
14779 InitializationSequence InitSeq(*this, Entity, Kind, {});
14780 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
14781
14782 if (Init.get()) {
14783 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14784 // This is important for template substitution.
14785 Var->setInitStyle(VarDecl::CallInit);
14786 } else if (Init.isInvalid()) {
14787 // If default-init fails, attach a recovery-expr initializer to track
14788 // that initialization was attempted and failed.
14789 auto RecoveryExpr =
14790 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14791 if (RecoveryExpr.get())
14792 Var->setInit(RecoveryExpr.get());
14793 }
14794
14795 CheckCompleteVariableDeclaration(VD: Var);
14796 }
14797}
14798
14799void Sema::ActOnCXXForRangeDecl(Decl *D) {
14800 // If there is no declaration, there was an error parsing it. Ignore it.
14801 if (!D)
14802 return;
14803
14804 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14805 if (!VD) {
14806 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var);
14807 D->setInvalidDecl();
14808 return;
14809 }
14810
14811 VD->setCXXForRangeDecl(true);
14812
14813 // for-range-declaration cannot be given a storage class specifier.
14814 int Error = -1;
14815 switch (VD->getStorageClass()) {
14816 case SC_None:
14817 break;
14818 case SC_Extern:
14819 Error = 0;
14820 break;
14821 case SC_Static:
14822 Error = 1;
14823 break;
14824 case SC_PrivateExtern:
14825 Error = 2;
14826 break;
14827 case SC_Auto:
14828 Error = 3;
14829 break;
14830 case SC_Register:
14831 Error = 4;
14832 break;
14833 }
14834
14835 // for-range-declaration cannot be given a storage class specifier con't.
14836 switch (VD->getTSCSpec()) {
14837 case TSCS_thread_local:
14838 Error = 6;
14839 break;
14840 case TSCS___thread:
14841 case TSCS__Thread_local:
14842 case TSCS_unspecified:
14843 break;
14844 }
14845
14846 if (Error != -1) {
14847 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
14848 << VD << Error;
14849 D->setInvalidDecl();
14850 }
14851}
14852
14853StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14854 IdentifierInfo *Ident,
14855 ParsedAttributes &Attrs) {
14856 // C++1y [stmt.iter]p1:
14857 // A range-based for statement of the form
14858 // for ( for-range-identifier : for-range-initializer ) statement
14859 // is equivalent to
14860 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14861 DeclSpec DS(Attrs.getPool().getFactory());
14862
14863 const char *PrevSpec;
14864 unsigned DiagID;
14865 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
14866 Policy: getPrintingPolicy());
14867
14868 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14869 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
14870 D.takeAttributesAppending(attrs&: Attrs);
14871
14872 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
14873 EndLoc: IdentLoc);
14874 Decl *Var = ActOnDeclarator(S, D);
14875 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
14876 FinalizeDeclaration(D: Var);
14877 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
14878 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14879 : IdentLoc);
14880}
14881
14882void Sema::addLifetimeBoundToImplicitThis(CXXMethodDecl *MD) {
14883 if (!MD || lifetimes::implicitObjectParamIsLifetimeBound(FD: MD))
14884 return;
14885 auto *Attr = LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: MD->getLocation());
14886 QualType MethodType = MD->getType();
14887 QualType AttributedType =
14888 Context.getAttributedType(attr: Attr, modifiedType: MethodType, equivalentType: MethodType);
14889 TypeLocBuilder TLB;
14890 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14891 TLB.pushFullCopy(L: TSI->getTypeLoc());
14892 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
14893 TyLoc.setAttr(Attr);
14894 MD->setType(AttributedType);
14895 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, T: AttributedType));
14896}
14897
14898void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14899 if (var->isInvalidDecl()) return;
14900
14901 CUDA().MaybeAddConstantAttr(VD: var);
14902
14903 if (getLangOpts().OpenCL) {
14904 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14905 // initialiser
14906 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14907 !var->hasInit()) {
14908 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
14909 << 1 /*Init*/;
14910 var->setInvalidDecl();
14911 return;
14912 }
14913 }
14914
14915 // In Objective-C, don't allow jumps past the implicit initialization of a
14916 // local retaining variable.
14917 if (getLangOpts().ObjC &&
14918 var->hasLocalStorage()) {
14919 switch (var->getType().getObjCLifetime()) {
14920 case Qualifiers::OCL_None:
14921 case Qualifiers::OCL_ExplicitNone:
14922 case Qualifiers::OCL_Autoreleasing:
14923 break;
14924
14925 case Qualifiers::OCL_Weak:
14926 case Qualifiers::OCL_Strong:
14927 setFunctionHasBranchProtectedScope();
14928 break;
14929 }
14930 }
14931
14932 if (var->hasLocalStorage() &&
14933 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14934 setFunctionHasBranchProtectedScope();
14935
14936 // Warn about externally-visible variables being defined without a
14937 // prior declaration. We only want to do this for global
14938 // declarations, but we also specifically need to avoid doing it for
14939 // class members because the linkage of an anonymous class can
14940 // change if it's later given a typedef name.
14941 if (var->isThisDeclarationADefinition() &&
14942 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14943 var->isExternallyVisible() && var->hasLinkage() &&
14944 !var->isInline() && !var->getDescribedVarTemplate() &&
14945 var->getStorageClass() != SC_Register &&
14946 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
14947 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
14948 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
14949 Loc: var->getLocation())) {
14950 // Find a previous declaration that's not a definition.
14951 VarDecl *prev = var->getPreviousDecl();
14952 while (prev && prev->isThisDeclarationADefinition())
14953 prev = prev->getPreviousDecl();
14954
14955 if (!prev) {
14956 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
14957 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
14958 << /* variable */ 0;
14959 }
14960 }
14961
14962 // Cache the result of checking for constant initialization.
14963 std::optional<bool> CacheHasConstInit;
14964 const Expr *CacheCulprit = nullptr;
14965 auto checkConstInit = [&]() mutable {
14966 const Expr *Init = var->getInit();
14967 if (Init->isInstantiationDependent())
14968 return true;
14969
14970 if (!CacheHasConstInit)
14971 CacheHasConstInit = var->getInit()->isConstantInitializer(
14972 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
14973 return *CacheHasConstInit;
14974 };
14975
14976 if (var->getTLSKind() == VarDecl::TLS_Static) {
14977 if (var->getType().isDestructedType()) {
14978 // GNU C++98 edits for __thread, [basic.start.term]p3:
14979 // The type of an object with thread storage duration shall not
14980 // have a non-trivial destructor.
14981 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
14982 if (getLangOpts().CPlusPlus11)
14983 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14984 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14985 if (!checkConstInit()) {
14986 // GNU C++98 edits for __thread, [basic.start.init]p4:
14987 // An object of thread storage duration shall not require dynamic
14988 // initialization.
14989 // FIXME: Need strict checking here.
14990 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
14991 << CacheCulprit->getSourceRange();
14992 if (getLangOpts().CPlusPlus11)
14993 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14994 }
14995 }
14996 }
14997
14998
14999 if (!var->getType()->isStructureType() && var->hasInit() &&
15000 isa<InitListExpr>(Val: var->getInit())) {
15001 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
15002 unsigned NumInits = ILE->getNumInits();
15003 if (NumInits > 2)
15004 for (unsigned I = 0; I < NumInits; ++I) {
15005 const auto *Init = ILE->getInit(Init: I);
15006 if (!Init)
15007 break;
15008 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15009 if (!SL)
15010 break;
15011
15012 unsigned NumConcat = SL->getNumConcatenated();
15013 // Diagnose missing comma in string array initialization.
15014 // Do not warn when all the elements in the initializer are concatenated
15015 // together. Do not warn for macros too.
15016 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15017 bool OnlyOneMissingComma = true;
15018 for (unsigned J = I + 1; J < NumInits; ++J) {
15019 const auto *Init = ILE->getInit(Init: J);
15020 if (!Init)
15021 break;
15022 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15023 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15024 OnlyOneMissingComma = false;
15025 break;
15026 }
15027 }
15028
15029 if (OnlyOneMissingComma) {
15030 SmallVector<FixItHint, 1> Hints;
15031 for (unsigned i = 0; i < NumConcat - 1; ++i)
15032 Hints.push_back(Elt: FixItHint::CreateInsertion(
15033 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
15034
15035 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
15036 DiagID: diag::warn_concatenated_literal_array_init)
15037 << Hints;
15038 Diag(Loc: SL->getBeginLoc(),
15039 DiagID: diag::note_concatenated_string_literal_silence);
15040 }
15041 // In any case, stop now.
15042 break;
15043 }
15044 }
15045 }
15046
15047
15048 QualType type = var->getType();
15049
15050 if (var->hasAttr<BlocksAttr>())
15051 getCurFunction()->addByrefBlockVar(VD: var);
15052
15053 Expr *Init = var->getInit();
15054 bool GlobalStorage = var->hasGlobalStorage();
15055 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15056 QualType baseType = Context.getBaseElementType(QT: type);
15057 bool HasConstInit = true;
15058
15059 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15060 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
15061 << var;
15062
15063 // Check whether the initializer is sufficiently constant.
15064 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15065 !type->isDependentType() && Init && !Init->isValueDependent() &&
15066 (GlobalStorage || var->isConstexpr() ||
15067 var->mightBeUsableInConstantExpressions(C: Context))) {
15068 // If this variable might have a constant initializer or might be usable in
15069 // constant expressions, check whether or not it actually is now. We can't
15070 // do this lazily, because the result might depend on things that change
15071 // later, such as which constexpr functions happen to be defined.
15072 SmallVector<PartialDiagnosticAt, 8> Notes;
15073 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15074 // Prior to C++11, in contexts where a constant initializer is required,
15075 // the set of valid constant initializers is described by syntactic rules
15076 // in [expr.const]p2-6.
15077 // FIXME: Stricter checking for these rules would be useful for constinit /
15078 // -Wglobal-constructors.
15079 HasConstInit = checkConstInit();
15080
15081 // Compute and cache the constant value, and remember that we have a
15082 // constant initializer.
15083 if (HasConstInit) {
15084 if (var->isStaticDataMember() && !var->isInline() &&
15085 var->getLexicalDeclContext()->isRecord() &&
15086 type->isIntegralOrEnumerationType()) {
15087 // In C++98, in-class initialization for a static data member must
15088 // be an integer constant expression.
15089 if (!Init->isIntegerConstantExpr(Ctx: Context)) {
15090 Diag(Loc: Init->getExprLoc(),
15091 DiagID: diag::ext_in_class_initializer_non_constant)
15092 << Init->getSourceRange();
15093 }
15094 }
15095 (void)var->checkForConstantInitialization(Notes);
15096 Notes.clear();
15097 } else if (CacheCulprit) {
15098 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
15099 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
15100 Notes.back().second << CacheCulprit->getSourceRange();
15101 }
15102 } else {
15103 // Evaluate the initializer to see if it's a constant initializer.
15104 HasConstInit = var->checkForConstantInitialization(Notes);
15105 }
15106
15107 if (HasConstInit) {
15108 // FIXME: Consider replacing the initializer with a ConstantExpr.
15109 } else if (var->isConstexpr()) {
15110 SourceLocation DiagLoc = var->getLocation();
15111 // If the note doesn't add any useful information other than a source
15112 // location, fold it into the primary diagnostic.
15113 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15114 diag::note_invalid_subexpr_in_const_expr) {
15115 DiagLoc = Notes[0].first;
15116 Notes.clear();
15117 }
15118 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
15119 << var << Init->getSourceRange();
15120 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15121 Diag(Loc: Notes[I].first, PD: Notes[I].second);
15122 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15123 auto *Attr = var->getAttr<ConstInitAttr>();
15124 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
15125 << Init->getSourceRange();
15126 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
15127 << Attr->getRange() << Attr->isConstinit();
15128 for (auto &it : Notes)
15129 Diag(Loc: it.first, PD: it.second);
15130 } else if (var->isStaticDataMember() && !var->isInline() &&
15131 var->getLexicalDeclContext()->isRecord()) {
15132 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
15133 << Init->getSourceRange();
15134 for (auto &it : Notes)
15135 Diag(Loc: it.first, PD: it.second);
15136 var->setInvalidDecl();
15137 } else if (IsGlobal &&
15138 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
15139 Loc: var->getLocation())) {
15140 // Warn about globals which don't have a constant initializer. Don't
15141 // warn about globals with a non-trivial destructor because we already
15142 // warned about them.
15143 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15144 if (!(RD && !RD->hasTrivialDestructor())) {
15145 // checkConstInit() here permits trivial default initialization even in
15146 // C++11 onwards, where such an initializer is not a constant initializer
15147 // but nonetheless doesn't require a global constructor.
15148 if (!checkConstInit())
15149 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
15150 << Init->getSourceRange();
15151 }
15152 }
15153 }
15154
15155 // Apply section attributes and pragmas to global variables.
15156 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15157 !inTemplateInstantiation()) {
15158 PragmaStack<StringLiteral *> *Stack = nullptr;
15159 int SectionFlags = ASTContext::PSF_Read;
15160 bool MSVCEnv =
15161 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15162 std::optional<QualType::NonConstantStorageReason> Reason;
15163 if (HasConstInit &&
15164 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
15165 Stack = &ConstSegStack;
15166 } else {
15167 SectionFlags |= ASTContext::PSF_Write;
15168 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15169 }
15170 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15171 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15172 SectionFlags |= ASTContext::PSF_Implicit;
15173 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
15174 } else if (Stack->CurrentValue) {
15175 if (Stack != &ConstSegStack && MSVCEnv &&
15176 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15177 var->getType().isConstQualified()) {
15178 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15179 NonConstNonReferenceType) &&
15180 "This case should've already been handled elsewhere");
15181 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
15182 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15183 ? QualType::NonConstantStorageReason::NonTrivialCtor
15184 : *Reason);
15185 }
15186 SectionFlags |= ASTContext::PSF_Implicit;
15187 auto SectionName = Stack->CurrentValue->getString();
15188 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
15189 Range: Stack->CurrentPragmaLocation,
15190 S: SectionAttr::Declspec_allocate));
15191 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
15192 var->dropAttr<SectionAttr>();
15193 }
15194
15195 // Apply the init_seg attribute if this has an initializer. If the
15196 // initializer turns out to not be dynamic, we'll end up ignoring this
15197 // attribute.
15198 if (CurInitSeg && var->getInit())
15199 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
15200 Range: CurInitSegLoc));
15201 }
15202
15203 // All the following checks are C++ only.
15204 if (!getLangOpts().CPlusPlus) {
15205 // If this variable must be emitted, add it as an initializer for the
15206 // current module.
15207 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15208 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15209 return;
15210 }
15211
15212 DiagnoseUniqueObjectDuplication(VD: var);
15213
15214 // Require the destructor.
15215 if (!type->isDependentType())
15216 if (auto *RD = baseType->getAsCXXRecordDecl())
15217 FinalizeVarWithDestructor(VD: var, DeclInit: RD);
15218
15219 // If this variable must be emitted, add it as an initializer for the current
15220 // module.
15221 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty() &&
15222 (ModuleScopes.back().Module->isHeaderLikeModule() ||
15223 // For named modules, we may only emit non discardable variables.
15224 !isDiscardableGVALinkage(L: Context.GetGVALinkageForVariable(VD: var))))
15225 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15226
15227 // Build the bindings if this is a structured binding declaration.
15228 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
15229 CheckCompleteDecompositionDeclaration(DD);
15230}
15231
15232void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15233 assert(VD->isStaticLocal());
15234
15235 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15236
15237 // Find outermost function when VD is in lambda function.
15238 while (FD && !getDLLAttr(D: FD) &&
15239 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15240 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15241 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
15242 }
15243
15244 if (!FD)
15245 return;
15246
15247 // Static locals inherit dll attributes from their function.
15248 if (Attr *A = getDLLAttr(D: FD)) {
15249 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
15250 NewAttr->setInherited(true);
15251 VD->addAttr(A: NewAttr);
15252 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15253 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15254 NewAttr->setInherited(true);
15255 VD->addAttr(A: NewAttr);
15256
15257 // Export this function to enforce exporting this static variable even
15258 // if it is not used in this compilation unit.
15259 if (!FD->hasAttr<DLLExportAttr>())
15260 FD->addAttr(A: NewAttr);
15261
15262 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15263 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15264 NewAttr->setInherited(true);
15265 VD->addAttr(A: NewAttr);
15266 }
15267}
15268
15269void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15270 assert(VD->getTLSKind());
15271
15272 // Perform TLS alignment check here after attributes attached to the variable
15273 // which may affect the alignment have been processed. Only perform the check
15274 // if the target has a maximum TLS alignment (zero means no constraints).
15275 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15276 // Protect the check so that it's not performed on dependent types and
15277 // dependent alignments (we can't determine the alignment in that case).
15278 if (!VD->hasDependentAlignment()) {
15279 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
15280 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
15281 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
15282 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
15283 << (unsigned)MaxAlignChars.getQuantity();
15284 }
15285 }
15286 }
15287}
15288
15289void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15290 // Note that we are no longer parsing the initializer for this declaration.
15291 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
15292
15293 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
15294 if (!VD)
15295 return;
15296
15297 // Emit any deferred warnings for the variable's initializer, even if the
15298 // variable is invalid
15299 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15300
15301 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15302 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15303 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15304 if (PragmaClangBSSSection.Valid)
15305 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
15306 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
15307 Range: PragmaClangBSSSection.PragmaLocation));
15308 if (PragmaClangDataSection.Valid)
15309 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
15310 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
15311 Range: PragmaClangDataSection.PragmaLocation));
15312 if (PragmaClangRodataSection.Valid)
15313 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
15314 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
15315 Range: PragmaClangRodataSection.PragmaLocation));
15316 if (PragmaClangRelroSection.Valid)
15317 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
15318 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
15319 Range: PragmaClangRelroSection.PragmaLocation));
15320 }
15321
15322 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
15323 for (auto *BD : DD->bindings()) {
15324 FinalizeDeclaration(ThisDecl: BD);
15325 }
15326 }
15327
15328 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
15329 K: BuiltinCountedByRefKind::Initializer);
15330
15331 checkAttributesAfterMerging(S&: *this, ND&: *VD);
15332
15333 if (VD->isStaticLocal())
15334 CheckStaticLocalForDllExport(VD);
15335
15336 if (VD->getTLSKind())
15337 CheckThreadLocalForLargeAlignment(VD);
15338
15339 // Perform check for initializers of device-side global variables.
15340 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15341 // 7.5). We must also apply the same checks to all __shared__
15342 // variables whether they are local or not. CUDA also allows
15343 // constant initializers for __constant__ and __device__ variables.
15344 if (getLangOpts().CUDA)
15345 CUDA().checkAllowedInitializer(VD);
15346
15347 // Grab the dllimport or dllexport attribute off of the VarDecl.
15348 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
15349
15350 // Imported static data members cannot be defined out-of-line.
15351 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
15352 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15353 VD->isThisDeclarationADefinition()) {
15354 // We allow definitions of dllimport class template static data members
15355 // with a warning.
15356 CXXRecordDecl *Context =
15357 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
15358 bool IsClassTemplateMember =
15359 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
15360 Context->getDescribedClassTemplate();
15361
15362 Diag(Loc: VD->getLocation(),
15363 DiagID: IsClassTemplateMember
15364 ? diag::warn_attribute_dllimport_static_field_definition
15365 : diag::err_attribute_dllimport_static_field_definition);
15366 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
15367 if (!IsClassTemplateMember)
15368 VD->setInvalidDecl();
15369 }
15370 }
15371
15372 // dllimport/dllexport variables cannot be thread local, their TLS index
15373 // isn't exported with the variable.
15374 if (DLLAttr && VD->getTLSKind()) {
15375 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15376 if (F && getDLLAttr(D: F)) {
15377 assert(VD->isStaticLocal());
15378 // But if this is a static local in a dlimport/dllexport function, the
15379 // function will never be inlined, which means the var would never be
15380 // imported, so having it marked import/export is safe.
15381 } else {
15382 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15383 << DLLAttr;
15384 VD->setInvalidDecl();
15385 }
15386 }
15387
15388 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15389 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15390 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15391 << Attr;
15392 VD->dropAttr<UsedAttr>();
15393 }
15394 }
15395 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15396 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15397 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15398 << Attr;
15399 VD->dropAttr<RetainAttr>();
15400 }
15401 }
15402
15403 const DeclContext *DC = VD->getDeclContext();
15404 // If there's a #pragma GCC visibility in scope, and this isn't a class
15405 // member, set the visibility of this variable.
15406 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15407 AddPushedVisibilityAttribute(RD: VD);
15408
15409 // FIXME: Warn on unused var template partial specializations.
15410 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15411 MarkUnusedFileScopedDecl(D: VD);
15412
15413 // Now we have parsed the initializer and can update the table of magic
15414 // tag values.
15415 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15416 !VD->getType()->isIntegralOrEnumerationType())
15417 return;
15418
15419 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15420 const Expr *MagicValueExpr = VD->getInit();
15421 if (!MagicValueExpr) {
15422 continue;
15423 }
15424 std::optional<llvm::APSInt> MagicValueInt;
15425 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15426 Diag(Loc: I->getRange().getBegin(),
15427 DiagID: diag::err_type_tag_for_datatype_not_ice)
15428 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15429 continue;
15430 }
15431 if (MagicValueInt->getActiveBits() > 64) {
15432 Diag(Loc: I->getRange().getBegin(),
15433 DiagID: diag::err_type_tag_for_datatype_too_large)
15434 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15435 continue;
15436 }
15437 uint64_t MagicValue = MagicValueInt->getZExtValue();
15438 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15439 MagicValue,
15440 Type: I->getMatchingCType(),
15441 LayoutCompatible: I->getLayoutCompatible(),
15442 MustBeNull: I->getMustBeNull());
15443 }
15444}
15445
15446static bool hasDeducedAuto(DeclaratorDecl *DD) {
15447 auto *VD = dyn_cast<VarDecl>(Val: DD);
15448 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15449}
15450
15451Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15452 ArrayRef<Decl *> Group) {
15453 SmallVector<Decl*, 8> Decls;
15454
15455 if (DS.isTypeSpecOwned())
15456 Decls.push_back(Elt: DS.getRepAsDecl());
15457
15458 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15459 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15460 bool DiagnosedMultipleDecomps = false;
15461 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15462 bool DiagnosedNonDeducedAuto = false;
15463
15464 for (Decl *D : Group) {
15465 if (!D)
15466 continue;
15467 // Check if the Decl has been declared in '#pragma omp declare target'
15468 // directive and has static storage duration.
15469 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15470 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15471 VD->hasGlobalStorage())
15472 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15473 // For declarators, there are some additional syntactic-ish checks we need
15474 // to perform.
15475 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15476 if (!FirstDeclaratorInGroup)
15477 FirstDeclaratorInGroup = DD;
15478 if (!FirstDecompDeclaratorInGroup)
15479 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15480 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15481 !hasDeducedAuto(DD))
15482 FirstNonDeducedAutoInGroup = DD;
15483
15484 if (FirstDeclaratorInGroup != DD) {
15485 // A decomposition declaration cannot be combined with any other
15486 // declaration in the same group.
15487 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15488 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15489 DiagID: diag::err_decomp_decl_not_alone)
15490 << FirstDeclaratorInGroup->getSourceRange()
15491 << DD->getSourceRange();
15492 DiagnosedMultipleDecomps = true;
15493 }
15494
15495 // A declarator that uses 'auto' in any way other than to declare a
15496 // variable with a deduced type cannot be combined with any other
15497 // declarator in the same group.
15498 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15499 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15500 DiagID: diag::err_auto_non_deduced_not_alone)
15501 << FirstNonDeducedAutoInGroup->getType()
15502 ->hasAutoForTrailingReturnType()
15503 << FirstDeclaratorInGroup->getSourceRange()
15504 << DD->getSourceRange();
15505 DiagnosedNonDeducedAuto = true;
15506 }
15507 }
15508 }
15509
15510 Decls.push_back(Elt: D);
15511 }
15512
15513 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15514 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15515 handleTagNumbering(Tag, TagScope: S);
15516 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15517 getLangOpts().CPlusPlus)
15518 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15519 }
15520 }
15521
15522 return BuildDeclaratorGroup(Group: Decls);
15523}
15524
15525Sema::DeclGroupPtrTy
15526Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15527 // C++14 [dcl.spec.auto]p7: (DR1347)
15528 // If the type that replaces the placeholder type is not the same in each
15529 // deduction, the program is ill-formed.
15530 if (Group.size() > 1) {
15531 QualType Deduced;
15532 VarDecl *DeducedDecl = nullptr;
15533 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15534 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15535 if (!D || D->isInvalidDecl())
15536 break;
15537 DeducedType *DT = D->getType()->getContainedDeducedType();
15538 if (!DT || DT->getDeducedType().isNull())
15539 continue;
15540 if (Deduced.isNull()) {
15541 Deduced = DT->getDeducedType();
15542 DeducedDecl = D;
15543 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15544 auto *AT = dyn_cast<AutoType>(Val: DT);
15545 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15546 DiagID: diag::err_auto_different_deductions)
15547 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15548 << DeducedDecl->getDeclName() << DT->getDeducedType()
15549 << D->getDeclName();
15550 if (DeducedDecl->hasInit())
15551 Dia << DeducedDecl->getInit()->getSourceRange();
15552 if (D->getInit())
15553 Dia << D->getInit()->getSourceRange();
15554 D->setInvalidDecl();
15555 break;
15556 }
15557 }
15558 }
15559
15560 ActOnDocumentableDecls(Group);
15561
15562 return DeclGroupPtrTy::make(
15563 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15564}
15565
15566void Sema::ActOnDocumentableDecl(Decl *D) {
15567 ActOnDocumentableDecls(Group: D);
15568}
15569
15570void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15571 // Don't parse the comment if Doxygen diagnostics are ignored.
15572 if (Group.empty() || !Group[0])
15573 return;
15574
15575 if (Diags.isIgnored(DiagID: diag::warn_doc_param_not_found,
15576 Loc: Group[0]->getLocation()) &&
15577 Diags.isIgnored(DiagID: diag::warn_unknown_comment_command_name,
15578 Loc: Group[0]->getLocation()))
15579 return;
15580
15581 if (Group.size() >= 2) {
15582 // This is a decl group. Normally it will contain only declarations
15583 // produced from declarator list. But in case we have any definitions or
15584 // additional declaration references:
15585 // 'typedef struct S {} S;'
15586 // 'typedef struct S *S;'
15587 // 'struct S *pS;'
15588 // FinalizeDeclaratorGroup adds these as separate declarations.
15589 Decl *MaybeTagDecl = Group[0];
15590 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15591 Group = Group.slice(N: 1);
15592 }
15593 }
15594
15595 // FIXME: We assume every Decl in the group is in the same file.
15596 // This is false when preprocessor constructs the group from decls in
15597 // different files (e. g. macros or #include).
15598 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15599}
15600
15601void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15602 // Check that there are no default arguments inside the type of this
15603 // parameter.
15604 if (getLangOpts().CPlusPlus)
15605 CheckExtraCXXDefaultArguments(D);
15606
15607 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15608 if (D.getCXXScopeSpec().isSet()) {
15609 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15610 << D.getCXXScopeSpec().getRange();
15611 }
15612
15613 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15614 // simple identifier except [...irrelevant cases...].
15615 switch (D.getName().getKind()) {
15616 case UnqualifiedIdKind::IK_Identifier:
15617 break;
15618
15619 case UnqualifiedIdKind::IK_OperatorFunctionId:
15620 case UnqualifiedIdKind::IK_ConversionFunctionId:
15621 case UnqualifiedIdKind::IK_LiteralOperatorId:
15622 case UnqualifiedIdKind::IK_ConstructorName:
15623 case UnqualifiedIdKind::IK_DestructorName:
15624 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15625 case UnqualifiedIdKind::IK_DeductionGuideName:
15626 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15627 << GetNameForDeclarator(D).getName();
15628 break;
15629
15630 case UnqualifiedIdKind::IK_TemplateId:
15631 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15632 // GetNameForDeclarator would not produce a useful name in this case.
15633 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15634 break;
15635 }
15636}
15637
15638void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15639 // This only matters in C.
15640 if (getLangOpts().CPlusPlus)
15641 return;
15642
15643 // This only matters if the declaration has a type.
15644 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15645 if (!VD)
15646 return;
15647
15648 // Get the type, this only matters for tag types.
15649 QualType QT = VD->getType();
15650 const auto *TD = QT->getAsTagDecl();
15651 if (!TD)
15652 return;
15653
15654 // Check if the tag declaration is lexically declared somewhere different
15655 // from the lexical declaration of the given object, then it will be hidden
15656 // in C++ and we should warn on it.
15657 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15658 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15659 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15660 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15661 }
15662}
15663
15664static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15665 SourceLocation ExplicitThisLoc) {
15666 if (!ExplicitThisLoc.isValid())
15667 return;
15668 assert(S.getLangOpts().CPlusPlus &&
15669 "explicit parameter in non-cplusplus mode");
15670 if (!S.getLangOpts().CPlusPlus23)
15671 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15672 << P->getSourceRange();
15673
15674 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15675 // parameter pack.
15676 if (P->isParameterPack()) {
15677 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15678 << P->getSourceRange();
15679 return;
15680 }
15681 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15682 if (LambdaScopeInfo *LSI = S.getCurLambda())
15683 LSI->ExplicitObjectParameter = P;
15684}
15685
15686Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15687 SourceLocation ExplicitThisLoc) {
15688 const DeclSpec &DS = D.getDeclSpec();
15689
15690 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15691 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15692 // except for the special case of a single unnamed parameter of type void
15693 // with no storage class specifier, no type qualifier, and no following
15694 // ellipsis terminator.
15695 // Clang applies the C2y rules for 'register void' in all C language modes,
15696 // same as GCC, because it's questionable what that could possibly mean.
15697
15698 // C++03 [dcl.stc]p2 also permits 'auto'.
15699 StorageClass SC = SC_None;
15700 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15701 SC = SC_Register;
15702 // In C++11, the 'register' storage class specifier is deprecated.
15703 // In C++17, it is not allowed, but we tolerate it as an extension.
15704 if (getLangOpts().CPlusPlus11) {
15705 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15706 ? diag::ext_register_storage_class
15707 : diag::warn_deprecated_register)
15708 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15709 } else if (!getLangOpts().CPlusPlus &&
15710 DS.getTypeSpecType() == DeclSpec::TST_void &&
15711 D.getNumTypeObjects() == 0) {
15712 Diag(Loc: DS.getStorageClassSpecLoc(),
15713 DiagID: diag::err_invalid_storage_class_in_func_decl)
15714 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15715 D.getMutableDeclSpec().ClearStorageClassSpecs();
15716 }
15717 } else if (getLangOpts().CPlusPlus &&
15718 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15719 SC = SC_Auto;
15720 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15721 Diag(Loc: DS.getStorageClassSpecLoc(),
15722 DiagID: diag::err_invalid_storage_class_in_func_decl);
15723 D.getMutableDeclSpec().ClearStorageClassSpecs();
15724 }
15725
15726 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15727 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15728 << DeclSpec::getSpecifierName(S: TSCS);
15729 if (DS.isInlineSpecified())
15730 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15731 << getLangOpts().CPlusPlus17;
15732 if (DS.hasConstexprSpecifier())
15733 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15734 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15735
15736 DiagnoseFunctionSpecifiers(DS);
15737
15738 CheckFunctionOrTemplateParamDeclarator(S, D);
15739
15740 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15741 QualType parmDeclType = TInfo->getType();
15742
15743 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15744 const IdentifierInfo *II = D.getIdentifier();
15745 if (II) {
15746 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15747 RedeclarationKind::ForVisibleRedeclaration);
15748 LookupName(R, S);
15749 if (!R.empty()) {
15750 NamedDecl *PrevDecl = *R.begin();
15751 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15752 // Maybe we will complain about the shadowed template parameter.
15753 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
15754 // Just pretend that we didn't see the previous declaration.
15755 PrevDecl = nullptr;
15756 }
15757 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
15758 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
15759 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
15760 // Recover by removing the name
15761 II = nullptr;
15762 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15763 D.setInvalidType(true);
15764 }
15765 }
15766 }
15767
15768 // Incomplete resource arrays are not allowed as function parameters in HLSL
15769 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15770 parmDeclType->isHLSLResourceRecordArray()) {
15771 Diag(Loc: D.getIdentifierLoc(),
15772 DiagID: diag::err_hlsl_incomplete_resource_array_in_function_param);
15773 D.setInvalidType(true);
15774 }
15775
15776 // Temporarily put parameter variables in the translation unit, not
15777 // the enclosing context. This prevents them from accidentally
15778 // looking like class members in C++.
15779 ParmVarDecl *New =
15780 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
15781 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
15782
15783 if (D.isInvalidType())
15784 New->setInvalidDecl();
15785
15786 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15787
15788 assert(S->isFunctionPrototypeScope());
15789 assert(S->getFunctionPrototypeDepth() >= 1);
15790 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15791 parameterIndex: S->getNextFunctionPrototypeIndex());
15792
15793 warnOnCTypeHiddenInCPlusPlus(D: New);
15794
15795 // Add the parameter declaration into this scope.
15796 S->AddDecl(D: New);
15797 if (II)
15798 IdResolver.AddDecl(D: New);
15799
15800 ProcessDeclAttributes(S, D: New, PD: D);
15801
15802 if (D.getDeclSpec().isModulePrivateSpecified())
15803 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
15804 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15805 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
15806
15807 if (New->hasAttr<BlocksAttr>()) {
15808 Diag(Loc: New->getLocation(), DiagID: diag::err_block_on_nonlocal);
15809 }
15810
15811 if (getLangOpts().OpenCL)
15812 deduceOpenCLAddressSpace(Var: New);
15813
15814 return New;
15815}
15816
15817ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15818 SourceLocation Loc,
15819 QualType T) {
15820 /* FIXME: setting StartLoc == Loc.
15821 Would it be worth to modify callers so as to provide proper source
15822 location for the unnamed parameters, embedding the parameter's type? */
15823 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15824 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15825 S: SC_None, DefArg: nullptr);
15826 Param->setImplicit();
15827 return Param;
15828}
15829
15830void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15831 // Don't diagnose unused-parameter errors in template instantiations; we
15832 // will already have done so in the template itself.
15833 if (inTemplateInstantiation())
15834 return;
15835
15836 for (const ParmVarDecl *Parameter : Parameters) {
15837 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15838 !Parameter->hasAttr<UnusedAttr>() &&
15839 !Parameter->getIdentifier()->isPlaceholder()) {
15840 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
15841 << Parameter->getDeclName();
15842 }
15843 }
15844}
15845
15846void Sema::DiagnoseSizeOfParametersAndReturnValue(
15847 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15848 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15849 return;
15850
15851 // Warn if the return value is pass-by-value and larger than the specified
15852 // threshold.
15853 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15854 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
15855 if (Size > LangOpts.NumLargeByValueCopy)
15856 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
15857 }
15858
15859 // Warn if any parameter is pass-by-value and larger than the specified
15860 // threshold.
15861 for (const ParmVarDecl *Parameter : Parameters) {
15862 QualType T = Parameter->getType();
15863 if (T->isDependentType() || !T.isPODType(Context))
15864 continue;
15865 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15866 if (Size > LangOpts.NumLargeByValueCopy)
15867 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
15868 << Parameter << Size;
15869 }
15870}
15871
15872ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15873 SourceLocation NameLoc,
15874 const IdentifierInfo *Name, QualType T,
15875 TypeSourceInfo *TSInfo, StorageClass SC) {
15876 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15877 if (getLangOpts().ObjCAutoRefCount &&
15878 T.getObjCLifetime() == Qualifiers::OCL_None &&
15879 T->isObjCLifetimeType()) {
15880
15881 Qualifiers::ObjCLifetime lifetime;
15882
15883 // Special cases for arrays:
15884 // - if it's const, use __unsafe_unretained
15885 // - otherwise, it's an error
15886 if (T->isArrayType()) {
15887 if (!T.isConstQualified()) {
15888 if (DelayedDiagnostics.shouldDelayDiagnostics())
15889 DelayedDiagnostics.add(
15890 diag: sema::DelayedDiagnostic::makeForbiddenType(
15891 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
15892 else
15893 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
15894 << TSInfo->getTypeLoc().getSourceRange();
15895 }
15896 lifetime = Qualifiers::OCL_ExplicitNone;
15897 } else {
15898 lifetime = T->getObjCARCImplicitLifetime();
15899 }
15900 T = Context.getLifetimeQualifiedType(type: T, lifetime);
15901 }
15902
15903 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
15904 T: Context.getAdjustedParameterType(T),
15905 TInfo: TSInfo, S: SC, DefArg: nullptr);
15906
15907 // Make a note if we created a new pack in the scope of a lambda, so that
15908 // we know that references to that pack must also be expanded within the
15909 // lambda scope.
15910 if (New->isParameterPack())
15911 if (auto *CSI = getEnclosingLambdaOrBlock())
15912 CSI->LocalPacks.push_back(Elt: New);
15913
15914 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15915 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15916 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
15917 UseContext: NonTrivialCUnionContext::FunctionParam,
15918 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
15919
15920 // Parameter declarators cannot be interface types. All ObjC objects are
15921 // passed by reference.
15922 if (T->isObjCObjectType()) {
15923 SourceLocation TypeEndLoc =
15924 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
15925 Diag(Loc: NameLoc,
15926 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15927 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
15928 T = Context.getObjCObjectPointerType(OIT: T);
15929 New->setType(T);
15930 }
15931
15932 // __ptrauth is forbidden on parameters.
15933 if (T.getPointerAuth()) {
15934 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
15935 New->setInvalidDecl();
15936 }
15937
15938 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15939 // duration shall not be qualified by an address-space qualifier."
15940 // Since all parameters have automatic store duration, they can not have
15941 // an address space.
15942 if (T.getAddressSpace() != LangAS::Default &&
15943 // OpenCL allows function arguments declared to be an array of a type
15944 // to be qualified with an address space.
15945 !(getLangOpts().OpenCL &&
15946 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15947 // WebAssembly allows reference types as parameters. Funcref in particular
15948 // lives in a different address space.
15949 !(T->isFunctionPointerType() &&
15950 T.getAddressSpace() == LangAS::wasm_funcref) &&
15951 // HLSL allows function arguments to be qualified with an address space
15952 // if the groupshared annotation is used.
15953 !(getLangOpts().HLSL &&
15954 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
15955 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
15956 New->setInvalidDecl();
15957 }
15958
15959 // PPC MMA non-pointer types are not allowed as function argument types.
15960 if (Context.getTargetInfo().getTriple().isPPC64() &&
15961 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
15962 New->setInvalidDecl();
15963 }
15964
15965 return New;
15966}
15967
15968void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15969 SourceLocation LocAfterDecls) {
15970 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15971
15972 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15973 // in the declaration list shall have at least one declarator, those
15974 // declarators shall only declare identifiers from the identifier list, and
15975 // every identifier in the identifier list shall be declared.
15976 //
15977 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15978 // identifiers it names shall be declared in the declaration list."
15979 //
15980 // This is why we only diagnose in C99 and later. Note, the other conditions
15981 // listed are checked elsewhere.
15982 if (!FTI.hasPrototype) {
15983 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15984 --i;
15985 if (FTI.Params[i].Param == nullptr) {
15986 if (getLangOpts().C99) {
15987 SmallString<256> Code;
15988 llvm::raw_svector_ostream(Code)
15989 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15990 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
15991 << FTI.Params[i].Ident
15992 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
15993 }
15994
15995 // Implicitly declare the argument as type 'int' for lack of a better
15996 // type.
15997 AttributeFactory attrs;
15998 DeclSpec DS(attrs);
15999 const char* PrevSpec; // unused
16000 unsigned DiagID; // unused
16001 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
16002 DiagID, Policy: Context.getPrintingPolicy());
16003 // Use the identifier location for the type source range.
16004 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16005 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16006 Declarator ParamD(DS, ParsedAttributesView::none(),
16007 DeclaratorContext::KNRTypeList);
16008 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
16009 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
16010 }
16011 }
16012 }
16013}
16014
16015Decl *
16016Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
16017 MultiTemplateParamsArg TemplateParameterLists,
16018 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16019 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16020 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16021 Scope *ParentScope = FnBodyScope->getParent();
16022
16023 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16024 // we define a non-templated function definition, we will create a declaration
16025 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16026 // The base function declaration will have the equivalent of an `omp declare
16027 // variant` annotation which specifies the mangled definition as a
16028 // specialization function under the OpenMP context defined as part of the
16029 // `omp begin declare variant`.
16030 SmallVector<FunctionDecl *, 4> Bases;
16031 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16032 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
16033 S: ParentScope, D, TemplateParameterLists, Bases);
16034
16035 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
16036 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
16037 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
16038
16039 if (!Bases.empty())
16040 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
16041 Bases);
16042
16043 return Dcl;
16044}
16045
16046void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
16047 Consumer.HandleInlineFunctionDefinition(D);
16048}
16049
16050static bool FindPossiblePrototype(const FunctionDecl *FD,
16051 const FunctionDecl *&PossiblePrototype) {
16052 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16053 Prev = Prev->getPreviousDecl()) {
16054 // Ignore any declarations that occur in function or method
16055 // scope, because they aren't visible from the header.
16056 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16057 continue;
16058
16059 PossiblePrototype = Prev;
16060 return Prev->getType()->isFunctionProtoType();
16061 }
16062 return false;
16063}
16064
16065static bool
16066ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
16067 const FunctionDecl *&PossiblePrototype) {
16068 // Don't warn about invalid declarations.
16069 if (FD->isInvalidDecl())
16070 return false;
16071
16072 // Or declarations that aren't global.
16073 if (!FD->isGlobal())
16074 return false;
16075
16076 // Don't warn about C++ member functions.
16077 if (isa<CXXMethodDecl>(Val: FD))
16078 return false;
16079
16080 // Don't warn about 'main'.
16081 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
16082 if (IdentifierInfo *II = FD->getIdentifier())
16083 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
16084 return false;
16085
16086 if (FD->isMSVCRTEntryPoint())
16087 return false;
16088
16089 // Don't warn about inline functions.
16090 if (FD->isInlined())
16091 return false;
16092
16093 // Don't warn about function templates.
16094 if (FD->getDescribedFunctionTemplate())
16095 return false;
16096
16097 // Don't warn about function template specializations.
16098 if (FD->isFunctionTemplateSpecialization())
16099 return false;
16100
16101 // Don't warn for OpenCL kernels.
16102 if (FD->hasAttr<DeviceKernelAttr>())
16103 return false;
16104
16105 // Don't warn on explicitly deleted functions.
16106 if (FD->isDeleted())
16107 return false;
16108
16109 // Don't warn on implicitly local functions (such as having local-typed
16110 // parameters).
16111 if (!FD->isExternallyVisible())
16112 return false;
16113
16114 // If we were able to find a potential prototype, don't warn.
16115 if (FindPossiblePrototype(FD, PossiblePrototype))
16116 return false;
16117
16118 return true;
16119}
16120
16121void
16122Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
16123 const FunctionDecl *EffectiveDefinition,
16124 SkipBodyInfo *SkipBody) {
16125 const FunctionDecl *Definition = EffectiveDefinition;
16126 if (!Definition &&
16127 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16128 return;
16129
16130 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16131 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16132 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16133 // A merged copy of the same function, instantiated as a member of
16134 // the same class, is OK.
16135 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
16136 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
16137 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
16138 return;
16139 }
16140 }
16141 }
16142
16143 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
16144 return;
16145
16146 // Don't emit an error when this is redefinition of a typo-corrected
16147 // definition.
16148 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
16149 return;
16150
16151 bool DefinitionVisible = false;
16152 if (SkipBody && isRedefinitionAllowedFor(D: Definition, Visible&: DefinitionVisible) &&
16153 (Definition->getFormalLinkage() == Linkage::Internal ||
16154 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16155 Definition->getNumTemplateParameterLists())) {
16156 SkipBody->ShouldSkip = true;
16157 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16158 if (!DefinitionVisible) {
16159 if (auto *TD = Definition->getDescribedFunctionTemplate())
16160 makeMergedDefinitionVisible(ND: TD);
16161 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl *>(Definition));
16162 }
16163 return;
16164 }
16165
16166 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16167 Definition->getStorageClass() == SC_Extern)
16168 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
16169 << FD << getLangOpts().CPlusPlus;
16170 else
16171 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
16172
16173 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
16174 FD->setInvalidDecl();
16175}
16176
16177LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16178 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16179
16180 LambdaScopeInfo *LSI = PushLambdaScope();
16181 LSI->CallOperator = CallOperator;
16182 LSI->Lambda = LambdaClass;
16183 LSI->ReturnType = CallOperator->getReturnType();
16184 // When this function is called in situation where the context of the call
16185 // operator is not entered, we set AfterParameterList to false, so that
16186 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16187 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16188 // where we would set the CurContext to the lambda operator before
16189 // substituting into it. In this case the flag needs to be true such that
16190 // tryCaptureVariable can correctly handle potential captures thereof.
16191 LSI->AfterParameterList = CurContext == CallOperator;
16192
16193 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16194 // used at the point of dealing with potential captures.
16195 //
16196 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16197 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16198 // associated. (Technically, we could recover that list from their
16199 // instantiation patterns, but for now, the GLTemplateParameterList seems
16200 // unnecessary in these cases.)
16201 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16202 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16203 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16204
16205 if (LCD == LCD_None)
16206 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16207 else if (LCD == LCD_ByCopy)
16208 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16209 else if (LCD == LCD_ByRef)
16210 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16211 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16212
16213 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16214 LSI->Mutable = !CallOperator->isConst();
16215 if (CallOperator->isExplicitObjectMemberFunction())
16216 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
16217
16218 // Add the captures to the LSI so they can be noted as already
16219 // captured within tryCaptureVar.
16220 auto I = LambdaClass->field_begin();
16221 for (const auto &C : LambdaClass->captures()) {
16222 if (C.capturesVariable()) {
16223 ValueDecl *VD = C.getCapturedVar();
16224 if (VD->isInitCapture())
16225 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
16226 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16227 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
16228 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
16229 /*EllipsisLoc*/C.isPackExpansion()
16230 ? C.getEllipsisLoc() : SourceLocation(),
16231 CaptureType: I->getType(), /*Invalid*/false);
16232
16233 } else if (C.capturesThis()) {
16234 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
16235 ByCopy: C.getCaptureKind() == LCK_StarThis);
16236 } else {
16237 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
16238 CaptureType: I->getType());
16239 }
16240 ++I;
16241 }
16242 return LSI;
16243}
16244
16245Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16246 SkipBodyInfo *SkipBody,
16247 FnBodyKind BodyKind) {
16248 if (!D) {
16249 // Parsing the function declaration failed in some way. Push on a fake scope
16250 // anyway so we can try to parse the function body.
16251 PushFunctionScope();
16252 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16253 return D;
16254 }
16255
16256 FunctionDecl *FD = nullptr;
16257
16258 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
16259 FD = FunTmpl->getTemplatedDecl();
16260 else
16261 FD = cast<FunctionDecl>(Val: D);
16262
16263 // Do not push if it is a lambda because one is already pushed when building
16264 // the lambda in ActOnStartOfLambdaDefinition().
16265 if (!isLambdaCallOperator(DC: FD))
16266 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
16267 FD);
16268
16269 // Check for defining attributes before the check for redefinition.
16270 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16271 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
16272 FD->dropAttr<AliasAttr>();
16273 FD->setInvalidDecl();
16274 }
16275 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16276 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
16277 FD->dropAttr<IFuncAttr>();
16278 FD->setInvalidDecl();
16279 }
16280 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16281 if (Context.getTargetInfo().getTriple().isAArch64() &&
16282 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
16283 !Attr->isDefaultVersion()) {
16284 // If function multi versioning disabled skip parsing function body
16285 // defined with non-default target_version attribute
16286 if (SkipBody)
16287 SkipBody->ShouldSkip = true;
16288 return nullptr;
16289 }
16290 }
16291
16292 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
16293 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16294 Ctor->isDefaultConstructor() &&
16295 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16296 // If this is an MS ABI dllexport default constructor, instantiate any
16297 // default arguments.
16298 InstantiateDefaultCtorDefaultArgs(Ctor);
16299 }
16300 }
16301
16302 // See if this is a redefinition. If 'will have body' (or similar) is already
16303 // set, then these checks were already performed when it was set.
16304 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16305 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16306 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
16307
16308 // If we're skipping the body, we're done. Don't enter the scope.
16309 if (SkipBody && SkipBody->ShouldSkip)
16310 return D;
16311 }
16312
16313 // Mark this function as "will have a body eventually". This lets users to
16314 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16315 // this function.
16316 FD->setWillHaveBody();
16317
16318 // If we are instantiating a generic lambda call operator, push
16319 // a LambdaScopeInfo onto the function stack. But use the information
16320 // that's already been calculated (ActOnLambdaExpr) to prime the current
16321 // LambdaScopeInfo.
16322 // When the template operator is being specialized, the LambdaScopeInfo,
16323 // has to be properly restored so that tryCaptureVariable doesn't try
16324 // and capture any new variables. In addition when calculating potential
16325 // captures during transformation of nested lambdas, it is necessary to
16326 // have the LSI properly restored.
16327 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
16328 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16329 // instantiated, explicitly specialized.
16330 if (FD->getTemplateSpecializationInfo()
16331 ->isExplicitInstantiationOrSpecialization()) {
16332 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_spec);
16333 FD->setInvalidDecl();
16334 PushFunctionScope();
16335 } else {
16336 assert(inTemplateInstantiation() &&
16337 "There should be an active template instantiation on the stack "
16338 "when instantiating a generic lambda!");
16339 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
16340 }
16341 } else {
16342 // Enter a new function scope
16343 PushFunctionScope();
16344 }
16345
16346 // Builtin functions cannot be defined.
16347 if (unsigned BuiltinID = FD->getBuiltinID()) {
16348 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
16349 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
16350 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
16351 FD->setInvalidDecl();
16352 }
16353 }
16354
16355 // The return type of a function definition must be complete (C99 6.9.1p3).
16356 // C++23 [dcl.fct.def.general]/p2
16357 // The type of [...] the return for a function definition
16358 // shall not be a (possibly cv-qualified) class type that is incomplete
16359 // or abstract within the function body unless the function is deleted.
16360 QualType ResultType = FD->getReturnType();
16361 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16362 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16363 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
16364 DiagID: diag::err_func_def_incomplete_result) ||
16365 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
16366 DiagID: diag::err_abstract_type_in_decl,
16367 Args: AbstractReturnType)))
16368 FD->setInvalidDecl();
16369
16370 if (FnBodyScope)
16371 PushDeclContext(S: FnBodyScope, DC: FD);
16372
16373 // Check the validity of our function parameters
16374 if (BodyKind != FnBodyKind::Delete)
16375 CheckParmsForFunctionDef(Parameters: FD->parameters(),
16376 /*CheckParameterNames=*/true);
16377
16378 // Add non-parameter declarations already in the function to the current
16379 // scope.
16380 if (FnBodyScope) {
16381 for (Decl *NPD : FD->decls()) {
16382 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16383 if (!NonParmDecl)
16384 continue;
16385 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16386 "parameters should not be in newly created FD yet");
16387
16388 // If the decl has a name, make it accessible in the current scope.
16389 if (NonParmDecl->getDeclName())
16390 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16391
16392 // Similarly, dive into enums and fish their constants out, making them
16393 // accessible in this scope.
16394 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16395 for (auto *EI : ED->enumerators())
16396 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16397 }
16398 }
16399 }
16400
16401 // Introduce our parameters into the function scope
16402 for (auto *Param : FD->parameters()) {
16403 Param->setOwningFunction(FD);
16404
16405 // If this has an identifier, add it to the scope stack.
16406 if (Param->getIdentifier() && FnBodyScope) {
16407 CheckShadow(S: FnBodyScope, D: Param);
16408
16409 PushOnScopeChains(D: Param, S: FnBodyScope);
16410 }
16411 }
16412
16413 // C++ [module.import/6]
16414 // ...
16415 // A header unit shall not contain a definition of a non-inline function or
16416 // variable whose name has external linkage.
16417 //
16418 // Deleted and Defaulted functions are implicitly inline (but the
16419 // inline state is not set at this point, so check the BodyKind explicitly).
16420 // We choose to allow weak & selectany definitions, as they are common in
16421 // headers, and have semantics similar to inline definitions which are allowed
16422 // in header units.
16423 // FIXME: Consider an alternate location for the test where the inlined()
16424 // state is complete.
16425 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16426 !FD->isInvalidDecl() && !FD->isInlined() &&
16427 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16428 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16429 !FD->isTemplateInstantiation() &&
16430 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16431 assert(FD->isThisDeclarationADefinition());
16432 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16433 FD->setInvalidDecl();
16434 }
16435
16436 // Ensure that the function's exception specification is instantiated.
16437 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16438 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16439
16440 // dllimport cannot be applied to non-inline function definitions.
16441 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16442 !FD->isTemplateInstantiation()) {
16443 assert(!FD->hasAttr<DLLExportAttr>());
16444 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16445 FD->setInvalidDecl();
16446 return D;
16447 }
16448
16449 // Some function attributes (like OptimizeNoneAttr) need actions before
16450 // parsing body started.
16451 applyFunctionAttributesBeforeParsingBody(FD: D);
16452
16453 // We want to attach documentation to original Decl (which might be
16454 // a function template).
16455 ActOnDocumentableDecl(D);
16456 if (getCurLexicalContext()->isObjCContainer() &&
16457 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16458 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16459 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16460
16461 maybeAddDeclWithEffects(D: FD);
16462
16463 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16464 FnBodyScope) {
16465 // An implicit call expression is synthesized for functions declared with
16466 // the sycl_kernel_entry_point attribute. The call may resolve to a
16467 // function template, a member function template, or a call operator
16468 // of a variable template depending on the results of unqualified lookup
16469 // for 'sycl_kernel_launch' from the beginning of the function body.
16470 // Performing that lookup requires the stack of parsing scopes active
16471 // when the definition is parsed and is thus done here; the result is
16472 // cached in FunctionScopeInfo and used to synthesize the (possibly
16473 // unresolved) call expression after the function body has been parsed.
16474 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16475 if (!SKEPAttr->isInvalidAttr()) {
16476 ExprResult LaunchIdExpr =
16477 SYCL().BuildSYCLKernelLaunchIdExpr(FD, KernelName: SKEPAttr->getKernelName());
16478 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16479 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16480 // treated as an error in the definition of 'FD'; treating it as an error
16481 // of the declaration would affect overload resolution which would
16482 // potentially result in additional errors. If construction of
16483 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16484 // a null pointer value below; that is expected.
16485 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16486 }
16487 }
16488
16489 return D;
16490}
16491
16492void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16493 if (!FD || FD->isInvalidDecl())
16494 return;
16495 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16496 FD = TD->getTemplatedDecl();
16497 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16498 FPOptionsOverride FPO;
16499 FPO.setDisallowOptimizations();
16500 CurFPFeatures.applyChanges(FPO);
16501 FpPragmaStack.CurrentValue =
16502 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16503 }
16504}
16505
16506void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16507 ReturnStmt **Returns = Scope->Returns.data();
16508
16509 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16510 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16511 if (!NRVOCandidate->isNRVOVariable()) {
16512 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16513 DiagID: diag::warn_not_eliding_copy_on_return);
16514 Returns[I]->setNRVOCandidate(nullptr);
16515 }
16516 }
16517 }
16518}
16519
16520bool Sema::canDelayFunctionBody(const Declarator &D) {
16521 // We can't delay parsing the body of a constexpr function template (yet).
16522 if (D.getDeclSpec().hasConstexprSpecifier())
16523 return false;
16524
16525 // We can't delay parsing the body of a function template with a deduced
16526 // return type (yet).
16527 if (D.getDeclSpec().hasAutoTypeSpec()) {
16528 // If the placeholder introduces a non-deduced trailing return type,
16529 // we can still delay parsing it.
16530 if (D.getNumTypeObjects()) {
16531 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16532 if (Outer.Kind == DeclaratorChunk::Function &&
16533 Outer.Fun.hasTrailingReturnType()) {
16534 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16535 return Ty.isNull() || !Ty->isUndeducedType();
16536 }
16537 }
16538 return false;
16539 }
16540
16541 return true;
16542}
16543
16544bool Sema::canSkipFunctionBody(Decl *D) {
16545 // We cannot skip the body of a function (or function template) which is
16546 // constexpr, since we may need to evaluate its body in order to parse the
16547 // rest of the file.
16548 // We cannot skip the body of a function with an undeduced return type,
16549 // because any callers of that function need to know the type.
16550 if (const FunctionDecl *FD = D->getAsFunction()) {
16551 if (FD->isConstexpr())
16552 return false;
16553 // We can't simply call Type::isUndeducedType here, because inside template
16554 // auto can be deduced to a dependent type, which is not considered
16555 // "undeduced".
16556 if (FD->getReturnType()->getContainedDeducedType())
16557 return false;
16558 }
16559 return Consumer.shouldSkipFunctionBody(D);
16560}
16561
16562Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16563 if (!Decl)
16564 return nullptr;
16565 if (FunctionDecl *FD = Decl->getAsFunction())
16566 FD->setHasSkippedBody();
16567 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16568 MD->setHasSkippedBody();
16569 return Decl;
16570}
16571
16572/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16573/// body.
16574class ExitFunctionBodyRAII {
16575public:
16576 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16577 ~ExitFunctionBodyRAII() {
16578 if (!IsLambda)
16579 S.PopExpressionEvaluationContext();
16580 }
16581
16582private:
16583 Sema &S;
16584 bool IsLambda = false;
16585};
16586
16587static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16588 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16589
16590 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16591 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16592 if (!Inserted)
16593 return It->second;
16594
16595 bool R = false;
16596 const BlockDecl *CurBD = BD;
16597
16598 do {
16599 R = !CurBD->doesNotEscape();
16600 if (R)
16601 break;
16602 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16603 } while (CurBD);
16604
16605 return It->second = R;
16606 };
16607
16608 // If the location where 'self' is implicitly retained is inside a escaping
16609 // block, emit a diagnostic.
16610 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16611 S.ImplicitlyRetainedSelfLocs)
16612 if (IsOrNestedInEscapingBlock(P.second))
16613 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16614 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16615}
16616
16617static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16618 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16619 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16620}
16621
16622bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16623 return methodHasName(FD, Name: "get_return_object");
16624}
16625
16626bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16627 return FD->isStatic() &&
16628 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16629}
16630
16631void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16632 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16633 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16634 return;
16635 // Allow some_promise_type::get_return_object().
16636 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16637 return;
16638 if (!FD->hasAttr<CoroWrapperAttr>())
16639 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16640}
16641
16642Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16643 bool RetainFunctionScopeInfo) {
16644 FunctionScopeInfo *FSI = getCurFunction();
16645 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16646
16647 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16648 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16649
16650 SourceLocation AnalysisLoc;
16651 if (Body)
16652 AnalysisLoc = Body->getEndLoc();
16653 else if (FD)
16654 AnalysisLoc = FD->getEndLoc();
16655 sema::AnalysisBasedWarnings::Policy WP =
16656 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16657 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16658
16659 // If we skip function body, we can't tell if a function is a coroutine.
16660 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16661 if (FSI->isCoroutine())
16662 CheckCompletedCoroutineBody(FD, Body);
16663 else
16664 CheckCoroutineWrapper(FD);
16665 }
16666
16667 // Diagnose invalid SYCL kernel entry point function declarations
16668 // and build SYCLKernelCallStmts for valid ones.
16669 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16670 SYCLKernelEntryPointAttr *SKEPAttr =
16671 FD->getAttr<SYCLKernelEntryPointAttr>();
16672 if (FD->isDefaulted()) {
16673 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16674 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16675 SKEPAttr->setInvalidAttr();
16676 } else if (FD->isDeleted()) {
16677 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16678 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16679 SKEPAttr->setInvalidAttr();
16680 } else if (FSI->isCoroutine()) {
16681 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16682 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16683 SKEPAttr->setInvalidAttr();
16684 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16685 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16686 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16687 SKEPAttr->setInvalidAttr();
16688 }
16689
16690 // Build an unresolved SYCL kernel call statement for a function template,
16691 // validate that a SYCL kernel call statement was instantiated for an
16692 // (implicit or explicit) instantiation of a function template, or otherwise
16693 // build a (resolved) SYCL kernel call statement for a non-templated
16694 // function or an explicit specialization.
16695 if (Body && !SKEPAttr->isInvalidAttr()) {
16696 StmtResult SR;
16697 if (FD->isTemplateInstantiation()) {
16698 // The function body should already be a SYCLKernelCallStmt in this
16699 // case, but might not be if there were previous errors.
16700 SR = Body;
16701 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16702 // If name lookup for a template named sycl_kernel_launch failed
16703 // earlier, don't try to build a SYCL kernel call statement as that
16704 // would cause additional errors to be issued; just proceed with the
16705 // original function body.
16706 SR = Body;
16707 } else if (FD->isTemplated()) {
16708 SR = SYCL().BuildUnresolvedSYCLKernelCallStmt(
16709 Body: cast<CompoundStmt>(Val: Body), LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16710 } else {
16711 SR = SYCL().BuildSYCLKernelCallStmt(
16712 FD, Body: cast<CompoundStmt>(Val: Body),
16713 LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16714 }
16715 // If construction of the replacement body fails, just continue with the
16716 // original function body. An early error return here is not valid; the
16717 // current declaration context and function scopes must be popped before
16718 // returning.
16719 if (SR.isUsable())
16720 Body = SR.get();
16721 }
16722 }
16723
16724 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16725 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16726 if (FD->isDeletedAsWritten())
16727 Diag(Loc: SEAttr->getLocation(),
16728 DiagID: diag::err_sycl_external_invalid_deleted_function)
16729 << SEAttr;
16730 }
16731
16732 {
16733 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16734 // one is already popped when finishing the lambda in BuildLambdaExpr().
16735 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16736 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
16737 if (FD) {
16738 // The function body and the DefaultedOrDeletedInfo, if present, use
16739 // the same storage; don't overwrite the latter if the former is null
16740 // (the body is initialised to null anyway, so even if the latter isn't
16741 // present, this would still be a no-op).
16742 if (Body)
16743 FD->setBody(Body);
16744 FD->setWillHaveBody(false);
16745
16746 if (getLangOpts().CPlusPlus14) {
16747 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16748 FD->getReturnType()->isUndeducedType()) {
16749 // For a function with a deduced result type to return void,
16750 // the result type as written must be 'auto' or 'decltype(auto)',
16751 // possibly cv-qualified or constrained, but not ref-qualified.
16752 if (!FD->getReturnType()->getAs<AutoType>()) {
16753 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
16754 << FD->getReturnType();
16755 FD->setInvalidDecl();
16756 } else {
16757 // Falling off the end of the function is the same as 'return;'.
16758 Expr *Dummy = nullptr;
16759 if (DeduceFunctionTypeFromReturnExpr(
16760 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16761 AT: FD->getReturnType()->getAs<AutoType>()))
16762 FD->setInvalidDecl();
16763 }
16764 }
16765 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
16766 // In C++11, we don't use 'auto' deduction rules for lambda call
16767 // operators because we don't support return type deduction.
16768 auto *LSI = getCurLambda();
16769 if (LSI->HasImplicitReturnType) {
16770 deduceClosureReturnType(CSI&: *LSI);
16771
16772 // C++11 [expr.prim.lambda]p4:
16773 // [...] if there are no return statements in the compound-statement
16774 // [the deduced type is] the type void
16775 QualType RetType =
16776 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16777
16778 // Update the return type to the deduced type.
16779 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16780 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16781 EPI: Proto->getExtProtoInfo()));
16782 }
16783 }
16784
16785 // If the function implicitly returns zero (like 'main') or is naked,
16786 // don't complain about missing return statements.
16787 // Clang implicitly returns 0 in C89 mode, but that's considered an
16788 // extension. The check is necessary to ensure the expected extension
16789 // warning is emitted in C89 mode.
16790 if ((FD->hasImplicitReturnZero() &&
16791 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16792 FD->hasAttr<NakedAttr>())
16793 WP.disableCheckFallThrough();
16794
16795 // MSVC permits the use of pure specifier (=0) on function definition,
16796 // defined at class scope, warn about this non-standard construct.
16797 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16798 !FD->isOutOfLine())
16799 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
16800
16801 if (!FD->isInvalidDecl()) {
16802 // Don't diagnose unused parameters of defaulted, deleted or naked
16803 // functions.
16804 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16805 !FD->hasAttr<NakedAttr>())
16806 DiagnoseUnusedParameters(Parameters: FD->parameters());
16807 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
16808 ReturnTy: FD->getReturnType(), D: FD);
16809
16810 // If this is a structor, we need a vtable.
16811 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
16812 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
16813 else if (CXXDestructorDecl *Destructor =
16814 dyn_cast<CXXDestructorDecl>(Val: FD))
16815 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
16816
16817 // Try to apply the named return value optimization. We have to check
16818 // if we can do this here because lambdas keep return statements around
16819 // to deduce an implicit return type.
16820 if (FD->getReturnType()->isRecordType() &&
16821 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16822 computeNRVO(Body, Scope: FSI);
16823 }
16824
16825 // GNU warning -Wmissing-prototypes:
16826 // Warn if a global function is defined without a previous
16827 // prototype declaration. This warning is issued even if the
16828 // definition itself provides a prototype. The aim is to detect
16829 // global functions that fail to be declared in header files.
16830 const FunctionDecl *PossiblePrototype = nullptr;
16831 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16832 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
16833
16834 if (PossiblePrototype) {
16835 // We found a declaration that is not a prototype,
16836 // but that could be a zero-parameter prototype
16837 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16838 TypeLoc TL = TI->getTypeLoc();
16839 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16840 Diag(Loc: PossiblePrototype->getLocation(),
16841 DiagID: diag::note_declaration_not_a_prototype)
16842 << (FD->getNumParams() != 0)
16843 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16844 InsertionLoc: FTL.getRParenLoc(), Code: "void")
16845 : FixItHint{});
16846 }
16847 } else {
16848 // Returns true if the token beginning at this Loc is `const`.
16849 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16850 const LangOptions &LangOpts) {
16851 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16852 if (LocInfo.first.isInvalid())
16853 return false;
16854
16855 bool Invalid = false;
16856 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
16857 if (Invalid)
16858 return false;
16859
16860 if (LocInfo.second > Buffer.size())
16861 return false;
16862
16863 const char *LexStart = Buffer.data() + LocInfo.second;
16864 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16865
16866 return StartTok.consume_front(Prefix: "const") &&
16867 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
16868 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
16869 };
16870
16871 auto findBeginLoc = [&]() {
16872 // If the return type has `const` qualifier, we want to insert
16873 // `static` before `const` (and not before the typename).
16874 if ((FD->getReturnType()->isAnyPointerType() &&
16875 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16876 FD->getReturnType().isConstQualified()) {
16877 // But only do this if we can determine where the `const` is.
16878
16879 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16880 getLangOpts()))
16881
16882 return FD->getBeginLoc();
16883 }
16884 return FD->getTypeSpecStartLoc();
16885 };
16886 Diag(Loc: FD->getTypeSpecStartLoc(),
16887 DiagID: diag::note_static_for_internal_linkage)
16888 << /* function */ 1
16889 << (FD->getStorageClass() == SC_None
16890 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
16891 : FixItHint{});
16892 }
16893 }
16894
16895 // We might not have found a prototype because we didn't wish to warn on
16896 // the lack of a missing prototype. Try again without the checks for
16897 // whether we want to warn on the missing prototype.
16898 if (!PossiblePrototype)
16899 (void)FindPossiblePrototype(FD, PossiblePrototype);
16900
16901 // If the function being defined does not have a prototype, then we may
16902 // need to diagnose it as changing behavior in C23 because we now know
16903 // whether the function accepts arguments or not. This only handles the
16904 // case where the definition has no prototype but does have parameters
16905 // and either there is no previous potential prototype, or the previous
16906 // potential prototype also has no actual prototype. This handles cases
16907 // like:
16908 // void f(); void f(a) int a; {}
16909 // void g(a) int a; {}
16910 // See MergeFunctionDecl() for other cases of the behavior change
16911 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16912 // type without a prototype.
16913 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16914 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16915 !PossiblePrototype->isImplicit()))) {
16916 // The function definition has parameters, so this will change behavior
16917 // in C23. If there is a possible prototype, it comes before the
16918 // function definition.
16919 // FIXME: The declaration may have already been diagnosed as being
16920 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16921 // there's no way to test for the "changes behavior" condition in
16922 // SemaType.cpp when forming the declaration's function type. So, we do
16923 // this awkward dance instead.
16924 //
16925 // If we have a possible prototype and it declares a function with a
16926 // prototype, we don't want to diagnose it; if we have a possible
16927 // prototype and it has no prototype, it may have already been
16928 // diagnosed in SemaType.cpp as deprecated depending on whether
16929 // -Wstrict-prototypes is enabled. If we already warned about it being
16930 // deprecated, add a note that it also changes behavior. If we didn't
16931 // warn about it being deprecated (because the diagnostic is not
16932 // enabled), warn now that it is deprecated and changes behavior.
16933
16934 // This K&R C function definition definitely changes behavior in C23,
16935 // so diagnose it.
16936 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
16937 << /*definition*/ 1 << /* not supported in C23 */ 0;
16938
16939 // If we have a possible prototype for the function which is a user-
16940 // visible declaration, we already tested that it has no prototype.
16941 // This will change behavior in C23. This gets a warning rather than a
16942 // note because it's the same behavior-changing problem as with the
16943 // definition.
16944 if (PossiblePrototype)
16945 Diag(Loc: PossiblePrototype->getLocation(),
16946 DiagID: diag::warn_non_prototype_changes_behavior)
16947 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16948 << /*definition*/ 1;
16949 }
16950
16951 // Warn on CPUDispatch with an actual body.
16952 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16953 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
16954 if (!CmpndBody->body_empty())
16955 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
16956 DiagID: diag::warn_dispatch_body_ignored);
16957
16958 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
16959 const CXXMethodDecl *KeyFunction;
16960 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16961 MD->isVirtual() &&
16962 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
16963 MD == KeyFunction->getCanonicalDecl()) {
16964 // Update the key-function state if necessary for this ABI.
16965 if (FD->isInlined() &&
16966 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16967 Context.setNonKeyFunction(MD);
16968
16969 // If the newly-chosen key function is already defined, then we
16970 // need to mark the vtable as used retroactively.
16971 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
16972 const FunctionDecl *Definition;
16973 if (KeyFunction && KeyFunction->isDefined(Definition))
16974 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16975 } else {
16976 // We just defined they key function; mark the vtable as used.
16977 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16978 }
16979 }
16980 }
16981
16982 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16983 "Function parsing confused");
16984 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
16985 assert(MD == getCurMethodDecl() && "Method parsing confused");
16986 MD->setBody(Body);
16987 if (!MD->isInvalidDecl()) {
16988 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
16989 ReturnTy: MD->getReturnType(), D: MD);
16990
16991 if (Body)
16992 computeNRVO(Body, Scope: FSI);
16993 }
16994 if (FSI->ObjCShouldCallSuper) {
16995 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
16996 << MD->getSelector().getAsString();
16997 FSI->ObjCShouldCallSuper = false;
16998 }
16999 if (FSI->ObjCWarnForNoDesignatedInitChain) {
17000 const ObjCMethodDecl *InitMethod = nullptr;
17001 bool isDesignated =
17002 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
17003 assert(isDesignated && InitMethod);
17004 (void)isDesignated;
17005
17006 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17007 auto IFace = MD->getClassInterface();
17008 if (!IFace)
17009 return false;
17010 auto SuperD = IFace->getSuperClass();
17011 if (!SuperD)
17012 return false;
17013 return SuperD->getIdentifier() ==
17014 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
17015 };
17016 // Don't issue this warning for unavailable inits or direct subclasses
17017 // of NSObject.
17018 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17019 Diag(Loc: MD->getLocation(),
17020 DiagID: diag::warn_objc_designated_init_missing_super_call);
17021 Diag(Loc: InitMethod->getLocation(),
17022 DiagID: diag::note_objc_designated_init_marked_here);
17023 }
17024 FSI->ObjCWarnForNoDesignatedInitChain = false;
17025 }
17026 if (FSI->ObjCWarnForNoInitDelegation) {
17027 // Don't issue this warning for unavailable inits.
17028 if (!MD->isUnavailable())
17029 Diag(Loc: MD->getLocation(),
17030 DiagID: diag::warn_objc_secondary_init_missing_init_call);
17031 FSI->ObjCWarnForNoInitDelegation = false;
17032 }
17033
17034 diagnoseImplicitlyRetainedSelf(S&: *this);
17035 } else {
17036 // Parsing the function declaration failed in some way. Pop the fake scope
17037 // we pushed on.
17038 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17039 return nullptr;
17040 }
17041
17042 if (Body) {
17043 if (FSI->HasPotentialAvailabilityViolations)
17044 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
17045 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17046 AMDGPU().DiagnoseUnguardedBuiltinUsage(FD);
17047 }
17048
17049 assert(!FSI->ObjCShouldCallSuper &&
17050 "This should only be set for ObjC methods, which should have been "
17051 "handled in the block above.");
17052
17053 // Verify and clean out per-function state.
17054 if (Body && (!FD || !FD->isDefaulted())) {
17055 // C++ constructors that have function-try-blocks can't have return
17056 // statements in the handlers of that block. (C++ [except.handle]p14)
17057 // Verify this.
17058 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
17059 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
17060
17061 // Verify that gotos and switch cases don't jump into scopes illegally.
17062 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17063 DiagnoseInvalidJumps(Body);
17064
17065 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
17066 if (!Destructor->getParent()->isDependentType())
17067 CheckDestructor(Destructor);
17068
17069 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
17070 Record: Destructor->getParent());
17071 }
17072
17073 // If any errors have occurred, clear out any temporaries that may have
17074 // been leftover. This ensures that these temporaries won't be picked up
17075 // for deletion in some later function.
17076 if (hasUncompilableErrorOccurred() ||
17077 hasAnyUnrecoverableErrorsInThisFunction() ||
17078 getDiagnostics().getSuppressAllDiagnostics()) {
17079 DiscardCleanupsInEvaluationContext();
17080 }
17081 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
17082 // Since the body is valid, issue any analysis-based warnings that are
17083 // enabled.
17084 ActivePolicy = &WP;
17085 }
17086
17087 if (!IsInstantiation && FD &&
17088 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17089 !FD->isInvalidDecl() &&
17090 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
17091 FD->setInvalidDecl();
17092
17093 if (FD && FD->hasAttr<NakedAttr>()) {
17094 for (const Stmt *S : Body->children()) {
17095 // Allow local register variables without initializer as they don't
17096 // require prologue.
17097 bool RegisterVariables = false;
17098 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
17099 for (const auto *Decl : DS->decls()) {
17100 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
17101 RegisterVariables =
17102 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17103 if (!RegisterVariables)
17104 break;
17105 }
17106 }
17107 }
17108 if (RegisterVariables)
17109 continue;
17110 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
17111 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
17112 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
17113 FD->setInvalidDecl();
17114 break;
17115 }
17116 }
17117 }
17118
17119 assert(ExprCleanupObjects.size() ==
17120 ExprEvalContexts.back().NumCleanupObjects &&
17121 "Leftover temporaries in function");
17122 assert(!Cleanup.exprNeedsCleanups() &&
17123 "Unaccounted cleanups in function");
17124 assert(MaybeODRUseExprs.empty() &&
17125 "Leftover expressions for odr-use checking");
17126 }
17127 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17128 // the declaration context below. Otherwise, we're unable to transform
17129 // 'this' expressions when transforming immediate context functions.
17130
17131 if (FD)
17132 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
17133
17134 if (!IsInstantiation)
17135 PopDeclContext();
17136
17137 if (!RetainFunctionScopeInfo)
17138 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17139 // If any errors have occurred, clear out any temporaries that may have
17140 // been leftover. This ensures that these temporaries won't be picked up for
17141 // deletion in some later function.
17142 if (hasUncompilableErrorOccurred()) {
17143 DiscardCleanupsInEvaluationContext();
17144 }
17145
17146 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17147 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17148 auto ES = getEmissionStatus(Decl: FD);
17149 if (ES == Sema::FunctionEmissionStatus::Emitted ||
17150 ES == Sema::FunctionEmissionStatus::Unknown)
17151 DeclsToCheckForDeferredDiags.insert(X: FD);
17152 }
17153
17154 if (FD && !FD->isDeleted())
17155 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
17156
17157 return dcl;
17158}
17159
17160/// When we finish delayed parsing of an attribute, we must attach it to the
17161/// relevant Decl.
17162void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
17163 ParsedAttributes &Attrs) {
17164 // Always attach attributes to the underlying decl.
17165 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
17166 D = TD->getTemplatedDecl();
17167 ProcessDeclAttributeList(S, D, AttrList: Attrs);
17168 ProcessAPINotes(D);
17169
17170 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
17171 if (Method->isStatic())
17172 checkThisInStaticMemberFunctionAttributes(Method);
17173}
17174
17175NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
17176 IdentifierInfo &II, Scope *S) {
17177 // It is not valid to implicitly define a function in C23.
17178 assert(LangOpts.implicitFunctionsAllowed() &&
17179 "Implicit function declarations aren't allowed in this language mode");
17180
17181 // Find the scope in which the identifier is injected and the corresponding
17182 // DeclContext.
17183 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17184 // In that case, we inject the declaration into the translation unit scope
17185 // instead.
17186 Scope *BlockScope = S;
17187 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17188 BlockScope = BlockScope->getParent();
17189
17190 // Loop until we find a DeclContext that is either a function/method or the
17191 // translation unit, which are the only two valid places to implicitly define
17192 // a function. This avoids accidentally defining the function within a tag
17193 // declaration, for example.
17194 Scope *ContextScope = BlockScope;
17195 while (!ContextScope->getEntity() ||
17196 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17197 !ContextScope->getEntity()->isTranslationUnit()))
17198 ContextScope = ContextScope->getParent();
17199 ContextRAII SavedContext(*this, ContextScope->getEntity());
17200
17201 // Before we produce a declaration for an implicitly defined
17202 // function, see whether there was a locally-scoped declaration of
17203 // this name as a function or variable. If so, use that
17204 // (non-visible) declaration, and complain about it.
17205 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
17206 if (ExternCPrev) {
17207 // We still need to inject the function into the enclosing block scope so
17208 // that later (non-call) uses can see it.
17209 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
17210
17211 // C89 footnote 38:
17212 // If in fact it is not defined as having type "function returning int",
17213 // the behavior is undefined.
17214 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
17215 !Context.typesAreCompatible(
17216 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
17217 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
17218 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
17219 << ExternCPrev << !getLangOpts().C99;
17220 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
17221 return ExternCPrev;
17222 }
17223 }
17224
17225 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17226 unsigned diag_id;
17227 if (II.getName().starts_with(Prefix: "__builtin_"))
17228 diag_id = diag::warn_builtin_unknown;
17229 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17230 else if (getLangOpts().C99)
17231 diag_id = diag::ext_implicit_function_decl_c99;
17232 else
17233 diag_id = diag::warn_implicit_function_decl;
17234
17235 TypoCorrection Corrected;
17236 // Because typo correction is expensive, only do it if the implicit
17237 // function declaration is going to be treated as an error.
17238 //
17239 // Perform the correction before issuing the main diagnostic, as some
17240 // consumers use typo-correction callbacks to enhance the main diagnostic.
17241 if (S && !ExternCPrev &&
17242 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
17243 DeclFilterCCC<FunctionDecl> CCC{};
17244 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
17245 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
17246 }
17247
17248 Diag(Loc, DiagID: diag_id) << &II;
17249 if (Corrected) {
17250 // If the correction is going to suggest an implicitly defined function,
17251 // skip the correction as not being a particularly good idea.
17252 bool Diagnose = true;
17253 if (const auto *D = Corrected.getCorrectionDecl())
17254 Diagnose = !D->isImplicit();
17255 if (Diagnose)
17256 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
17257 /*ErrorRecovery*/ false);
17258 }
17259
17260 // If we found a prior declaration of this function, don't bother building
17261 // another one. We've already pushed that one into scope, so there's nothing
17262 // more to do.
17263 if (ExternCPrev)
17264 return ExternCPrev;
17265
17266 // Set a Declarator for the implicit definition: int foo();
17267 const char *Dummy;
17268 AttributeFactory attrFactory;
17269 DeclSpec DS(attrFactory);
17270 unsigned DiagID;
17271 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
17272 Policy: Context.getPrintingPolicy());
17273 (void)Error; // Silence warning.
17274 assert(!Error && "Error setting up implicit decl!");
17275 SourceLocation NoLoc;
17276 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17277 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
17278 /*IsAmbiguous=*/false,
17279 /*LParenLoc=*/NoLoc,
17280 /*Params=*/nullptr,
17281 /*NumParams=*/0,
17282 /*EllipsisLoc=*/NoLoc,
17283 /*RParenLoc=*/NoLoc,
17284 /*RefQualifierIsLvalueRef=*/true,
17285 /*RefQualifierLoc=*/NoLoc,
17286 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
17287 /*ESpecRange=*/SourceRange(),
17288 /*Exceptions=*/nullptr,
17289 /*ExceptionRanges=*/nullptr,
17290 /*NumExceptions=*/0,
17291 /*NoexceptExpr=*/nullptr,
17292 /*ExceptionSpecTokens=*/nullptr,
17293 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
17294 TheDeclarator&: D),
17295 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
17296 D.SetIdentifier(Id: &II, IdLoc: Loc);
17297
17298 // Insert this function into the enclosing block scope.
17299 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
17300 FD->setImplicit();
17301
17302 AddKnownFunctionAttributes(FD);
17303
17304 return FD;
17305}
17306
17307void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17308 FunctionDecl *FD) {
17309 if (FD->isInvalidDecl())
17310 return;
17311
17312 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17313 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17314 return;
17315
17316 UnsignedOrNone AlignmentParam = std::nullopt;
17317 bool IsNothrow = false;
17318 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
17319 return;
17320
17321 // C++2a [basic.stc.dynamic.allocation]p4:
17322 // An allocation function that has a non-throwing exception specification
17323 // indicates failure by returning a null pointer value. Any other allocation
17324 // function never returns a null pointer value and indicates failure only by
17325 // throwing an exception [...]
17326 //
17327 // However, -fcheck-new invalidates this possible assumption, so don't add
17328 // NonNull when that is enabled.
17329 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17330 !getLangOpts().CheckNew)
17331 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17332
17333 // C++2a [basic.stc.dynamic.allocation]p2:
17334 // An allocation function attempts to allocate the requested amount of
17335 // storage. [...] If the request succeeds, the value returned by a
17336 // replaceable allocation function is a [...] pointer value p0 different
17337 // from any previously returned value p1 [...]
17338 //
17339 // However, this particular information is being added in codegen,
17340 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17341
17342 // C++2a [basic.stc.dynamic.allocation]p2:
17343 // An allocation function attempts to allocate the requested amount of
17344 // storage. If it is successful, it returns the address of the start of a
17345 // block of storage whose length in bytes is at least as large as the
17346 // requested size.
17347 if (!FD->hasAttr<AllocSizeAttr>()) {
17348 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17349 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17350 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
17351 }
17352
17353 // C++2a [basic.stc.dynamic.allocation]p3:
17354 // For an allocation function [...], the pointer returned on a successful
17355 // call shall represent the address of storage that is aligned as follows:
17356 // (3.1) If the allocation function takes an argument of type
17357 // std​::​align_­val_­t, the storage will have the alignment
17358 // specified by the value of this argument.
17359 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17360 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
17361 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
17362 }
17363
17364 // FIXME:
17365 // C++2a [basic.stc.dynamic.allocation]p3:
17366 // For an allocation function [...], the pointer returned on a successful
17367 // call shall represent the address of storage that is aligned as follows:
17368 // (3.2) Otherwise, if the allocation function is named operator new[],
17369 // the storage is aligned for any object that does not have
17370 // new-extended alignment ([basic.align]) and is no larger than the
17371 // requested size.
17372 // (3.3) Otherwise, the storage is aligned for any object that does not
17373 // have new-extended alignment and is of the requested size.
17374}
17375
17376void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17377 if (FD->isInvalidDecl())
17378 return;
17379
17380 // If this is a built-in function, map its builtin attributes to
17381 // actual attributes.
17382 if (unsigned BuiltinID = FD->getBuiltinID()) {
17383 // Handle printf-formatting attributes.
17384 unsigned FormatIdx;
17385 bool HasVAListArg;
17386 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17387 if (!FD->hasAttr<FormatAttr>()) {
17388 const char *fmt = "printf";
17389 unsigned int NumParams = FD->getNumParams();
17390 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17391 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
17392 fmt = "NSString";
17393 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17394 Type: &Context.Idents.get(Name: fmt),
17395 FormatIdx: FormatIdx+1,
17396 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17397 Range: FD->getLocation()));
17398 }
17399 }
17400 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
17401 HasVAListArg)) {
17402 if (!FD->hasAttr<FormatAttr>())
17403 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17404 Type: &Context.Idents.get(Name: "scanf"),
17405 FormatIdx: FormatIdx+1,
17406 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17407 Range: FD->getLocation()));
17408 }
17409
17410 // Handle automatically recognized callbacks.
17411 SmallVector<int, 4> Encoding;
17412 if (!FD->hasAttr<CallbackAttr>() &&
17413 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
17414 FD->addAttr(A: CallbackAttr::CreateImplicit(
17415 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
17416
17417 // Mark const if we don't care about errno and/or floating point exceptions
17418 // that are the only thing preventing the function from being const. This
17419 // allows IRgen to use LLVM intrinsics for such functions.
17420 bool NoExceptions =
17421 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17422 bool ConstWithoutErrnoAndExceptions =
17423 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
17424 bool ConstWithoutExceptions =
17425 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
17426 if (!FD->hasAttr<ConstAttr>() &&
17427 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17428 (!ConstWithoutErrnoAndExceptions ||
17429 (!getLangOpts().MathErrno && NoExceptions)) &&
17430 (!ConstWithoutExceptions || NoExceptions))
17431 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17432
17433 // We make "fma" on GNU or Windows const because we know it does not set
17434 // errno in those environments even though it could set errno based on the
17435 // C standard.
17436 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17437 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17438 !FD->hasAttr<ConstAttr>()) {
17439 switch (BuiltinID) {
17440 case Builtin::BI__builtin_fma:
17441 case Builtin::BI__builtin_fmaf:
17442 case Builtin::BI__builtin_fmal:
17443 case Builtin::BIfma:
17444 case Builtin::BIfmaf:
17445 case Builtin::BIfmal:
17446 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17447 break;
17448 default:
17449 break;
17450 }
17451 }
17452
17453 SmallVector<int, 4> Indxs;
17454 Builtin::Info::NonNullMode OptMode;
17455 if (Context.BuiltinInfo.isNonNull(ID: BuiltinID, Indxs, Mode&: OptMode) &&
17456 !FD->hasAttr<NonNullAttr>()) {
17457 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17458 for (int I : Indxs) {
17459 ParmVarDecl *PVD = FD->getParamDecl(i: I);
17460 QualType T = PVD->getType();
17461 T = Context.getAttributedType(attrKind: attr::TypeNonNull, modifiedType: T, equivalentType: T);
17462 PVD->setType(T);
17463 }
17464 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17465 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17466 for (int I : Indxs)
17467 ParamIndxs.push_back(Elt: ParamIdx(I + 1, FD));
17468 FD->addAttr(A: NonNullAttr::CreateImplicit(Ctx&: Context, Args: ParamIndxs.data(),
17469 ArgsSize: ParamIndxs.size()));
17470 }
17471 }
17472 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17473 !FD->hasAttr<ReturnsTwiceAttr>())
17474 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17475 Range: FD->getLocation()));
17476 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17477 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17478 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17479 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17480 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17481 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17482 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17483 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17484 // Add the appropriate attribute, depending on the CUDA compilation mode
17485 // and which target the builtin belongs to. For example, during host
17486 // compilation, aux builtins are __device__, while the rest are __host__.
17487 if (getLangOpts().CUDAIsDevice !=
17488 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17489 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17490 else
17491 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17492 }
17493
17494 // Add known guaranteed alignment for allocation functions.
17495 switch (BuiltinID) {
17496 case Builtin::BImemalign:
17497 case Builtin::BIaligned_alloc:
17498 if (!FD->hasAttr<AllocAlignAttr>())
17499 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17500 Range: FD->getLocation()));
17501 break;
17502 default:
17503 break;
17504 }
17505
17506 // Add allocsize attribute for allocation functions.
17507 switch (BuiltinID) {
17508 case Builtin::BIcalloc:
17509 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17510 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17511 break;
17512 case Builtin::BImemalign:
17513 case Builtin::BIaligned_alloc:
17514 case Builtin::BIrealloc:
17515 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17516 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17517 break;
17518 case Builtin::BImalloc:
17519 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17520 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17521 break;
17522 default:
17523 break;
17524 }
17525 }
17526
17527 LazyProcessLifetimeCaptureByParams(FD);
17528 inferLifetimeBoundAttribute(FD);
17529 inferLifetimeCaptureByAttribute(FD);
17530 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17531
17532 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17533 // throw, add an implicit nothrow attribute to any extern "C" function we come
17534 // across.
17535 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17536 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17537 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17538 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17539 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17540 }
17541
17542 IdentifierInfo *Name = FD->getIdentifier();
17543 if (!Name)
17544 return;
17545 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17546 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17547 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17548 LinkageSpecLanguageIDs::C)) {
17549 // Okay: this could be a libc/libm/Objective-C function we know
17550 // about.
17551 } else
17552 return;
17553
17554 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17555 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17556 // target-specific builtins, perhaps?
17557 if (!FD->hasAttr<FormatAttr>())
17558 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17559 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17560 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17561 Range: FD->getLocation()));
17562 }
17563
17564 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17565 // We already have a __builtin___CFStringMakeConstantString,
17566 // but builds that use -fno-constant-cfstrings don't go through that.
17567 if (!FD->hasAttr<FormatArgAttr>())
17568 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17569 Range: FD->getLocation()));
17570 }
17571}
17572
17573TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17574 TypeSourceInfo *TInfo) {
17575 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17576 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17577
17578 if (!TInfo) {
17579 assert(D.isInvalidType() && "no declarator info for valid type");
17580 TInfo = Context.getTrivialTypeSourceInfo(T);
17581 }
17582
17583 // Scope manipulation handled by caller.
17584 TypedefDecl *NewTD =
17585 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17586 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17587
17588 // Bail out immediately if we have an invalid declaration.
17589 if (D.isInvalidType()) {
17590 NewTD->setInvalidDecl();
17591 return NewTD;
17592 }
17593
17594 if (D.getDeclSpec().isModulePrivateSpecified()) {
17595 if (CurContext->isFunctionOrMethod())
17596 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17597 << 2 << NewTD
17598 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17599 << FixItHint::CreateRemoval(
17600 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17601 else
17602 NewTD->setModulePrivate();
17603 }
17604
17605 // C++ [dcl.typedef]p8:
17606 // If the typedef declaration defines an unnamed class (or
17607 // enum), the first typedef-name declared by the declaration
17608 // to be that class type (or enum type) is used to denote the
17609 // class type (or enum type) for linkage purposes only.
17610 // We need to check whether the type was declared in the declaration.
17611 switch (D.getDeclSpec().getTypeSpecType()) {
17612 case TST_enum:
17613 case TST_struct:
17614 case TST_interface:
17615 case TST_union:
17616 case TST_class: {
17617 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17618 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17619 break;
17620 }
17621
17622 default:
17623 break;
17624 }
17625
17626 return NewTD;
17627}
17628
17629bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17630 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17631 QualType T = TI->getType();
17632
17633 if (T->isDependentType())
17634 return false;
17635
17636 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17637 // integral type; any cv-qualification is ignored.
17638 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17639 // non-atomic version of the type specified by the type specifiers in the
17640 // specifier qualifier list.
17641 // Because of how odd C's rule is, we'll let the user know that operations
17642 // involving the enumeration type will be non-atomic.
17643 if (T->isAtomicType())
17644 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17645
17646 Qualifiers Q = T.getQualifiers();
17647 std::optional<unsigned> QualSelect;
17648 if (Q.hasConst() && Q.hasVolatile())
17649 QualSelect = diag::CVQualList::Both;
17650 else if (Q.hasConst())
17651 QualSelect = diag::CVQualList::Const;
17652 else if (Q.hasVolatile())
17653 QualSelect = diag::CVQualList::Volatile;
17654
17655 if (QualSelect)
17656 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17657
17658 T = T.getAtomicUnqualifiedType();
17659
17660 // This doesn't use 'isIntegralType' despite the error message mentioning
17661 // integral type because isIntegralType would also allow enum types in C.
17662 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17663 if (BT->isInteger())
17664 return false;
17665
17666 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17667 << T << T->isBitIntType();
17668}
17669
17670bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17671 QualType EnumUnderlyingTy, bool IsFixed,
17672 const EnumDecl *Prev) {
17673 if (IsScoped != Prev->isScoped()) {
17674 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17675 << Prev->isScoped();
17676 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17677 return true;
17678 }
17679
17680 if (IsFixed && Prev->isFixed()) {
17681 if (!EnumUnderlyingTy->isDependentType() &&
17682 !Prev->getIntegerType()->isDependentType() &&
17683 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17684 T2: Prev->getIntegerType())) {
17685 // TODO: Highlight the underlying type of the redeclaration.
17686 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17687 << EnumUnderlyingTy << Prev->getIntegerType();
17688 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17689 << Prev->getIntegerTypeRange();
17690 return true;
17691 }
17692 } else if (IsFixed != Prev->isFixed()) {
17693 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17694 << Prev->isFixed();
17695 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17696 return true;
17697 }
17698
17699 return false;
17700}
17701
17702/// Get diagnostic %select index for tag kind for
17703/// redeclaration diagnostic message.
17704/// WARNING: Indexes apply to particular diagnostics only!
17705///
17706/// \returns diagnostic %select index.
17707static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17708 switch (Tag) {
17709 case TagTypeKind::Struct:
17710 return 0;
17711 case TagTypeKind::Interface:
17712 return 1;
17713 case TagTypeKind::Class:
17714 return 2;
17715 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17716 }
17717}
17718
17719/// Determine if tag kind is a class-key compatible with
17720/// class for redeclaration (class, struct, or __interface).
17721///
17722/// \returns true iff the tag kind is compatible.
17723static bool isClassCompatTagKind(TagTypeKind Tag)
17724{
17725 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17726 Tag == TagTypeKind::Interface;
17727}
17728
17729NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17730 if (isa<TypedefDecl>(Val: PrevDecl))
17731 return NonTagKind::Typedef;
17732 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17733 return NonTagKind::TypeAlias;
17734 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17735 return NonTagKind::Template;
17736 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17737 return NonTagKind::TypeAliasTemplate;
17738 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17739 return NonTagKind::TemplateTemplateArgument;
17740 switch (TTK) {
17741 case TagTypeKind::Struct:
17742 case TagTypeKind::Interface:
17743 case TagTypeKind::Class:
17744 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17745 : NonTagKind::NonStruct;
17746 case TagTypeKind::Union:
17747 return NonTagKind::NonUnion;
17748 case TagTypeKind::Enum:
17749 return NonTagKind::NonEnum;
17750 }
17751 llvm_unreachable("invalid TTK");
17752}
17753
17754bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17755 TagTypeKind NewTag, bool isDefinition,
17756 SourceLocation NewTagLoc,
17757 const IdentifierInfo *Name) {
17758 // C++ [dcl.type.elab]p3:
17759 // The class-key or enum keyword present in the
17760 // elaborated-type-specifier shall agree in kind with the
17761 // declaration to which the name in the elaborated-type-specifier
17762 // refers. This rule also applies to the form of
17763 // elaborated-type-specifier that declares a class-name or
17764 // friend class since it can be construed as referring to the
17765 // definition of the class. Thus, in any
17766 // elaborated-type-specifier, the enum keyword shall be used to
17767 // refer to an enumeration (7.2), the union class-key shall be
17768 // used to refer to a union (clause 9), and either the class or
17769 // struct class-key shall be used to refer to a class (clause 9)
17770 // declared using the class or struct class-key.
17771 TagTypeKind OldTag = Previous->getTagKind();
17772 if (OldTag != NewTag &&
17773 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17774 return false;
17775
17776 // Tags are compatible, but we might still want to warn on mismatched tags.
17777 // Non-class tags can't be mismatched at this point.
17778 if (!isClassCompatTagKind(Tag: NewTag))
17779 return true;
17780
17781 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17782 // by our warning analysis. We don't want to warn about mismatches with (eg)
17783 // declarations in system headers that are designed to be specialized, but if
17784 // a user asks us to warn, we should warn if their code contains mismatched
17785 // declarations.
17786 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17787 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
17788 Loc);
17789 };
17790 if (IsIgnoredLoc(NewTagLoc))
17791 return true;
17792
17793 auto IsIgnored = [&](const TagDecl *Tag) {
17794 return IsIgnoredLoc(Tag->getLocation());
17795 };
17796 while (IsIgnored(Previous)) {
17797 Previous = Previous->getPreviousDecl();
17798 if (!Previous)
17799 return true;
17800 OldTag = Previous->getTagKind();
17801 }
17802
17803 bool isTemplate = false;
17804 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17805 isTemplate = Record->getDescribedClassTemplate();
17806
17807 if (inTemplateInstantiation()) {
17808 if (OldTag != NewTag) {
17809 // In a template instantiation, do not offer fix-its for tag mismatches
17810 // since they usually mess up the template instead of fixing the problem.
17811 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17812 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17813 << getRedeclDiagFromTagKind(Tag: OldTag);
17814 // FIXME: Note previous location?
17815 }
17816 return true;
17817 }
17818
17819 if (isDefinition) {
17820 // On definitions, check all previous tags and issue a fix-it for each
17821 // one that doesn't match the current tag.
17822 if (Previous->getDefinition()) {
17823 // Don't suggest fix-its for redefinitions.
17824 return true;
17825 }
17826
17827 bool previousMismatch = false;
17828 for (const TagDecl *I : Previous->redecls()) {
17829 if (I->getTagKind() != NewTag) {
17830 // Ignore previous declarations for which the warning was disabled.
17831 if (IsIgnored(I))
17832 continue;
17833
17834 if (!previousMismatch) {
17835 previousMismatch = true;
17836 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
17837 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17838 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
17839 }
17840 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
17841 << getRedeclDiagFromTagKind(Tag: NewTag)
17842 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
17843 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
17844 }
17845 }
17846 return true;
17847 }
17848
17849 // Identify the prevailing tag kind: this is the kind of the definition (if
17850 // there is a non-ignored definition), or otherwise the kind of the prior
17851 // (non-ignored) declaration.
17852 const TagDecl *PrevDef = Previous->getDefinition();
17853 if (PrevDef && IsIgnored(PrevDef))
17854 PrevDef = nullptr;
17855 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17856 if (Redecl->getTagKind() != NewTag) {
17857 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17858 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17859 << getRedeclDiagFromTagKind(Tag: OldTag);
17860 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
17861
17862 // If there is a previous definition, suggest a fix-it.
17863 if (PrevDef) {
17864 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
17865 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
17866 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
17867 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
17868 }
17869 }
17870
17871 return true;
17872}
17873
17874/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17875/// from an outer enclosing namespace or file scope inside a friend declaration.
17876/// This should provide the commented out code in the following snippet:
17877/// namespace N {
17878/// struct X;
17879/// namespace M {
17880/// struct Y { friend struct /*N::*/ X; };
17881/// }
17882/// }
17883static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17884 SourceLocation NameLoc) {
17885 // While the decl is in a namespace, do repeated lookup of that name and see
17886 // if we get the same namespace back. If we do not, continue until
17887 // translation unit scope, at which point we have a fully qualified NNS.
17888 SmallVector<IdentifierInfo *, 4> Namespaces;
17889 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17890 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17891 // This tag should be declared in a namespace, which can only be enclosed by
17892 // other namespaces. Bail if there's an anonymous namespace in the chain.
17893 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
17894 if (!Namespace || Namespace->isAnonymousNamespace())
17895 return FixItHint();
17896 IdentifierInfo *II = Namespace->getIdentifier();
17897 Namespaces.push_back(Elt: II);
17898 NamedDecl *Lookup = SemaRef.LookupSingleName(
17899 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
17900 if (Lookup == Namespace)
17901 break;
17902 }
17903
17904 // Once we have all the namespaces, reverse them to go outermost first, and
17905 // build an NNS.
17906 SmallString<64> Insertion;
17907 llvm::raw_svector_ostream OS(Insertion);
17908 if (DC->isTranslationUnit())
17909 OS << "::";
17910 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
17911 for (auto *II : Namespaces)
17912 OS << II->getName() << "::";
17913 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
17914}
17915
17916/// Determine whether a tag originally declared in context \p OldDC can
17917/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17918/// found a declaration in \p OldDC as a previous decl, perhaps through a
17919/// using-declaration).
17920static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17921 DeclContext *NewDC) {
17922 OldDC = OldDC->getRedeclContext();
17923 NewDC = NewDC->getRedeclContext();
17924
17925 if (OldDC->Equals(DC: NewDC))
17926 return true;
17927
17928 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17929 // encloses the other).
17930 if (S.getLangOpts().MSVCCompat &&
17931 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
17932 return true;
17933
17934 return false;
17935}
17936
17937DeclResult
17938Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17939 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17940 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17941 SourceLocation ModulePrivateLoc,
17942 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17943 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17944 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17945 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17946 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17947 // If this is not a definition, it must have a name.
17948 IdentifierInfo *OrigName = Name;
17949 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17950 "Nameless record must be a definition!");
17951 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17952
17953 OwnedDecl = false;
17954 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17955 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17956
17957 // FIXME: Check member specializations more carefully.
17958 bool isMemberSpecialization = false;
17959 bool IsInjectedClassName = false;
17960 bool Invalid = false;
17961
17962 // We only need to do this matching if we have template parameters
17963 // or a scope specifier, which also conveniently avoids this work
17964 // for non-C++ cases.
17965 if (TemplateParameterLists.size() > 0 ||
17966 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17967 TemplateParameterList *TemplateParams =
17968 MatchTemplateParametersToScopeSpecifier(
17969 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
17970 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
17971
17972 // C++23 [dcl.type.elab] p2:
17973 // If an elaborated-type-specifier is the sole constituent of a
17974 // declaration, the declaration is ill-formed unless it is an explicit
17975 // specialization, an explicit instantiation or it has one of the
17976 // following forms: [...]
17977 // C++23 [dcl.enum] p1:
17978 // If the enum-head-name of an opaque-enum-declaration contains a
17979 // nested-name-specifier, the declaration shall be an explicit
17980 // specialization.
17981 //
17982 // FIXME: Class template partial specializations can be forward declared
17983 // per CWG2213, but the resolution failed to allow qualified forward
17984 // declarations. This is almost certainly unintentional, so we allow them.
17985 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17986 !isMemberSpecialization)
17987 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
17988 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17989
17990 if (TemplateParams) {
17991 if (Kind == TagTypeKind::Enum) {
17992 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
17993 return true;
17994 }
17995
17996 if (TemplateParams->size() > 0) {
17997 // This is a declaration or definition of a class template (which may
17998 // be a member of another template).
17999
18000 if (Invalid)
18001 return true;
18002
18003 OwnedDecl = false;
18004 DeclResult Result = CheckClassTemplate(
18005 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
18006 AS, ModulePrivateLoc,
18007 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
18008 OuterTemplateParamLists: TemplateParameterLists.data(), SkipBody);
18009 return Result.get();
18010 } else {
18011 // The "template<>" header is extraneous.
18012 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18013 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18014 isMemberSpecialization = true;
18015 }
18016 }
18017
18018 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18019 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
18020 return true;
18021 }
18022
18023 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18024 // C++23 [dcl.type.elab]p4:
18025 // If an elaborated-type-specifier appears with the friend specifier as
18026 // an entire member-declaration, the member-declaration shall have one
18027 // of the following forms:
18028 // friend class-key nested-name-specifier(opt) identifier ;
18029 // friend class-key simple-template-id ;
18030 // friend class-key nested-name-specifier template(opt)
18031 // simple-template-id ;
18032 //
18033 // Since enum is not a class-key, so declarations like "friend enum E;"
18034 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18035 // invalid, most implementations accept so we issue a pedantic warning.
18036 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
18037 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18038 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18039 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
18040 << (ScopedEnum + ScopedEnumUsesClassTag);
18041 }
18042
18043 // Figure out the underlying type if this a enum declaration. We need to do
18044 // this early, because it's needed to detect if this is an incompatible
18045 // redeclaration.
18046 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18047 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18048
18049 if (Kind == TagTypeKind::Enum) {
18050 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
18051 // No underlying type explicitly specified, or we failed to parse the
18052 // type, default to int.
18053 EnumUnderlying = Context.IntTy.getTypePtr();
18054 } else if (UnderlyingType.get()) {
18055 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18056 // integral type; any cv-qualification is ignored.
18057 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18058 // unqualified, non-atomic version of the type specified by the type
18059 // specifiers in the specifier qualifier list.
18060 TypeSourceInfo *TI = nullptr;
18061 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
18062 EnumUnderlying = TI;
18063
18064 if (CheckEnumUnderlyingType(TI))
18065 // Recover by falling back to int.
18066 EnumUnderlying = Context.IntTy.getTypePtr();
18067
18068 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
18069 UPPC: UPPC_FixedUnderlyingType))
18070 EnumUnderlying = Context.IntTy.getTypePtr();
18071
18072 // If the underlying type is atomic, we need to adjust the type before
18073 // continuing. This only happens in the case we stored a TypeSourceInfo
18074 // into EnumUnderlying because the other cases are error recovery up to
18075 // this point. But because it's not possible to gin up a TypeSourceInfo
18076 // for a non-atomic type from an atomic one, we'll store into the Type
18077 // field instead. FIXME: it would be nice to have an easy way to get a
18078 // derived TypeSourceInfo which strips qualifiers including the weird
18079 // ones like _Atomic where it forms a different type.
18080 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
18081 TI && TI->getType()->isAtomicType())
18082 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18083
18084 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18085 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18086 // of 'int'. However, if this is an unfixed forward declaration, don't set
18087 // the underlying type unless the user enables -fms-compatibility. This
18088 // makes unfixed forward declared enums incomplete and is more conforming.
18089 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18090 EnumUnderlying = Context.IntTy.getTypePtr();
18091 }
18092 }
18093
18094 DeclContext *SearchDC = CurContext;
18095 DeclContext *DC = CurContext;
18096 bool isStdBadAlloc = false;
18097 bool isStdAlignValT = false;
18098
18099 RedeclarationKind Redecl = forRedeclarationInCurContext();
18100 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18101 Redecl = RedeclarationKind::NotForRedeclaration;
18102
18103 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18104 /// implemented asks for structural equivalence checking, the returned decl
18105 /// here is passed back to the parser, allowing the tag body to be parsed.
18106 auto createTagFromNewDecl = [&]() -> TagDecl * {
18107 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18108 // If there is an identifier, use the location of the identifier as the
18109 // location of the decl, otherwise use the location of the struct/union
18110 // keyword.
18111 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18112 TagDecl *New = nullptr;
18113
18114 if (Kind == TagTypeKind::Enum) {
18115 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
18116 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18117 // If this is an undefined enum, bail.
18118 if (TUK != TagUseKind::Definition && !Invalid)
18119 return nullptr;
18120 if (EnumUnderlying) {
18121 EnumDecl *ED = cast<EnumDecl>(Val: New);
18122 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18123 ED->setIntegerTypeSourceInfo(TI);
18124 else
18125 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18126 QualType EnumTy = ED->getIntegerType();
18127 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18128 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18129 : EnumTy);
18130 }
18131 } else { // struct/union
18132 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18133 PrevDecl: nullptr);
18134 }
18135
18136 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18137 // Add alignment attributes if necessary; these attributes are checked
18138 // when the ASTContext lays out the structure.
18139 //
18140 // It is important for implementing the correct semantics that this
18141 // happen here (in ActOnTag). The #pragma pack stack is
18142 // maintained as a result of parser callbacks which can occur at
18143 // many points during the parsing of a struct declaration (because
18144 // the #pragma tokens are effectively skipped over during the
18145 // parsing of the struct).
18146 if (TUK == TagUseKind::Definition &&
18147 (!SkipBody || !SkipBody->ShouldSkip)) {
18148 if (LangOpts.HLSL)
18149 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18150 AddAlignmentAttributesForRecord(RD);
18151 AddMsStructLayoutForRecord(RD);
18152 }
18153 }
18154 New->setLexicalDeclContext(CurContext);
18155 return New;
18156 };
18157
18158 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18159 if (Name && SS.isNotEmpty()) {
18160 // We have a nested-name tag ('struct foo::bar').
18161
18162 // Check for invalid 'foo::'.
18163 if (SS.isInvalid()) {
18164 Name = nullptr;
18165 goto CreateNewDecl;
18166 }
18167
18168 // If this is a friend or a reference to a class in a dependent
18169 // context, don't try to make a decl for it.
18170 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18171 DC = computeDeclContext(SS, EnteringContext: false);
18172 if (!DC) {
18173 IsDependent = true;
18174 return true;
18175 }
18176 } else {
18177 DC = computeDeclContext(SS, EnteringContext: true);
18178 if (!DC) {
18179 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
18180 << SS.getRange();
18181 return true;
18182 }
18183 }
18184
18185 if (RequireCompleteDeclContext(SS, DC))
18186 return true;
18187
18188 SearchDC = DC;
18189 // Look-up name inside 'foo::'.
18190 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18191
18192 if (Previous.isAmbiguous())
18193 return true;
18194
18195 if (Previous.empty()) {
18196 // Name lookup did not find anything. However, if the
18197 // nested-name-specifier refers to the current instantiation,
18198 // and that current instantiation has any dependent base
18199 // classes, we might find something at instantiation time: treat
18200 // this as a dependent elaborated-type-specifier.
18201 // But this only makes any sense for reference-like lookups.
18202 if (Previous.wasNotFoundInCurrentInstantiation() &&
18203 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18204 IsDependent = true;
18205 return true;
18206 }
18207
18208 // A tag 'foo::bar' must already exist.
18209 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
18210 << Kind << Name << DC << SS.getRange();
18211 Name = nullptr;
18212 Invalid = true;
18213 goto CreateNewDecl;
18214 }
18215 } else if (Name) {
18216 // C++14 [class.mem]p14:
18217 // If T is the name of a class, then each of the following shall have a
18218 // name different from T:
18219 // -- every member of class T that is itself a type
18220 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18221 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
18222 return true;
18223
18224 // If this is a named struct, check to see if there was a previous forward
18225 // declaration or definition.
18226 // FIXME: We're looking into outer scopes here, even when we
18227 // shouldn't be. Doing so can result in ambiguities that we
18228 // shouldn't be diagnosing.
18229 LookupName(R&: Previous, S);
18230
18231 // When declaring or defining a tag, ignore ambiguities introduced
18232 // by types using'ed into this scope.
18233 if (Previous.isAmbiguous() &&
18234 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18235 LookupResult::Filter F = Previous.makeFilter();
18236 while (F.hasNext()) {
18237 NamedDecl *ND = F.next();
18238 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18239 DC: SearchDC->getRedeclContext()))
18240 F.erase();
18241 }
18242 F.done();
18243 }
18244
18245 // C++11 [namespace.memdef]p3:
18246 // If the name in a friend declaration is neither qualified nor
18247 // a template-id and the declaration is a function or an
18248 // elaborated-type-specifier, the lookup to determine whether
18249 // the entity has been previously declared shall not consider
18250 // any scopes outside the innermost enclosing namespace.
18251 //
18252 // MSVC doesn't implement the above rule for types, so a friend tag
18253 // declaration may be a redeclaration of a type declared in an enclosing
18254 // scope. They do implement this rule for friend functions.
18255 //
18256 // Does it matter that this should be by scope instead of by
18257 // semantic context?
18258 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18259 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18260 LookupResult::Filter F = Previous.makeFilter();
18261 bool FriendSawTagOutsideEnclosingNamespace = false;
18262 while (F.hasNext()) {
18263 NamedDecl *ND = F.next();
18264 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18265 if (DC->isFileContext() &&
18266 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
18267 if (getLangOpts().MSVCCompat)
18268 FriendSawTagOutsideEnclosingNamespace = true;
18269 else
18270 F.erase();
18271 }
18272 }
18273 F.done();
18274
18275 // Diagnose this MSVC extension in the easy case where lookup would have
18276 // unambiguously found something outside the enclosing namespace.
18277 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18278 NamedDecl *ND = Previous.getFoundDecl();
18279 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
18280 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
18281 }
18282 }
18283
18284 // Note: there used to be some attempt at recovery here.
18285 if (Previous.isAmbiguous())
18286 return true;
18287
18288 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18289 // FIXME: This makes sure that we ignore the contexts associated
18290 // with C structs, unions, and enums when looking for a matching
18291 // tag declaration or definition. See the similar lookup tweak
18292 // in Sema::LookupName; is there a better way to deal with this?
18293 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
18294 SearchDC = SearchDC->getParent();
18295 } else if (getLangOpts().CPlusPlus) {
18296 // Inside ObjCContainer want to keep it as a lexical decl context but go
18297 // past it (most often to TranslationUnit) to find the semantic decl
18298 // context.
18299 while (isa<ObjCContainerDecl>(Val: SearchDC))
18300 SearchDC = SearchDC->getParent();
18301 }
18302 } else if (getLangOpts().CPlusPlus) {
18303 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18304 // TagDecl the same way as we skip it for named TagDecl.
18305 while (isa<ObjCContainerDecl>(Val: SearchDC))
18306 SearchDC = SearchDC->getParent();
18307 }
18308
18309 if (Previous.isSingleResult() &&
18310 Previous.getFoundDecl()->isTemplateParameter()) {
18311 // Maybe we will complain about the shadowed template parameter.
18312 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
18313 // Just pretend that we didn't see the previous declaration.
18314 Previous.clear();
18315 }
18316
18317 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18318 DC->Equals(DC: getStdNamespace())) {
18319 if (Name->isStr(Str: "bad_alloc")) {
18320 // This is a declaration of or a reference to "std::bad_alloc".
18321 isStdBadAlloc = true;
18322
18323 // If std::bad_alloc has been implicitly declared (but made invisible to
18324 // name lookup), fill in this implicit declaration as the previous
18325 // declaration, so that the declarations get chained appropriately.
18326 if (Previous.empty() && StdBadAlloc)
18327 Previous.addDecl(D: getStdBadAlloc());
18328 } else if (Name->isStr(Str: "align_val_t")) {
18329 isStdAlignValT = true;
18330 if (Previous.empty() && StdAlignValT)
18331 Previous.addDecl(D: getStdAlignValT());
18332 }
18333 }
18334
18335 // If we didn't find a previous declaration, and this is a reference
18336 // (or friend reference), move to the correct scope. In C++, we
18337 // also need to do a redeclaration lookup there, just in case
18338 // there's a shadow friend decl.
18339 if (Name && Previous.empty() &&
18340 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18341 IsTemplateParamOrArg)) {
18342 if (Invalid) goto CreateNewDecl;
18343 assert(SS.isEmpty());
18344
18345 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18346 // C++ [basic.scope.pdecl]p5:
18347 // -- for an elaborated-type-specifier of the form
18348 //
18349 // class-key identifier
18350 //
18351 // if the elaborated-type-specifier is used in the
18352 // decl-specifier-seq or parameter-declaration-clause of a
18353 // function defined in namespace scope, the identifier is
18354 // declared as a class-name in the namespace that contains
18355 // the declaration; otherwise, except as a friend
18356 // declaration, the identifier is declared in the smallest
18357 // non-class, non-function-prototype scope that contains the
18358 // declaration.
18359 //
18360 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18361 // C structs and unions.
18362 //
18363 // It is an error in C++ to declare (rather than define) an enum
18364 // type, including via an elaborated type specifier. We'll
18365 // diagnose that later; for now, declare the enum in the same
18366 // scope as we would have picked for any other tag type.
18367 //
18368 // GNU C also supports this behavior as part of its incomplete
18369 // enum types extension, while GNU C++ does not.
18370 //
18371 // Find the context where we'll be declaring the tag.
18372 // FIXME: We would like to maintain the current DeclContext as the
18373 // lexical context,
18374 SearchDC = getTagInjectionContext(DC: SearchDC);
18375
18376 // Find the scope where we'll be declaring the tag.
18377 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18378 } else {
18379 assert(TUK == TagUseKind::Friend);
18380 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
18381
18382 // C++ [namespace.memdef]p3:
18383 // If a friend declaration in a non-local class first declares a
18384 // class or function, the friend class or function is a member of
18385 // the innermost enclosing namespace.
18386 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18387 : SearchDC->getEnclosingNamespaceContext();
18388 }
18389
18390 // In C++, we need to do a redeclaration lookup to properly
18391 // diagnose some problems.
18392 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18393 // hidden declaration so that we don't get ambiguity errors when using a
18394 // type declared by an elaborated-type-specifier. In C that is not correct
18395 // and we should instead merge compatible types found by lookup.
18396 if (getLangOpts().CPlusPlus) {
18397 // FIXME: This can perform qualified lookups into function contexts,
18398 // which are meaningless.
18399 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18400 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
18401 } else {
18402 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18403 LookupName(R&: Previous, S);
18404 }
18405 }
18406
18407 // If we have a known previous declaration to use, then use it.
18408 if (Previous.empty() && SkipBody && SkipBody->Previous)
18409 Previous.addDecl(D: SkipBody->Previous);
18410
18411 if (!Previous.empty()) {
18412 NamedDecl *PrevDecl = Previous.getFoundDecl();
18413 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18414
18415 // It's okay to have a tag decl in the same scope as a typedef
18416 // which hides a tag decl in the same scope. Finding this
18417 // with a redeclaration lookup can only actually happen in C++.
18418 //
18419 // This is also okay for elaborated-type-specifiers, which is
18420 // technically forbidden by the current standard but which is
18421 // okay according to the likely resolution of an open issue;
18422 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18423 if (getLangOpts().CPlusPlus) {
18424 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18425 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18426 if (Tag->getDeclName() == Name &&
18427 Tag->getDeclContext()->getRedeclContext()
18428 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
18429 PrevDecl = Tag;
18430 Previous.clear();
18431 Previous.addDecl(D: Tag);
18432 Previous.resolveKind();
18433 }
18434 }
18435 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: PrevDecl);
18436 TUK == TagUseKind::Reference && RD &&
18437 RD->isInjectedClassName()) {
18438 // If lookup found the injected class name, the previous declaration is
18439 // the class being injected into.
18440 PrevDecl = cast<TagDecl>(Val: RD->getDeclContext());
18441 Previous.clear();
18442 Previous.addDecl(D: PrevDecl);
18443 Previous.resolveKind();
18444 IsInjectedClassName = true;
18445 }
18446 }
18447
18448 // If this is a redeclaration of a using shadow declaration, it must
18449 // declare a tag in the same context. In MSVC mode, we allow a
18450 // redefinition if either context is within the other.
18451 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
18452 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
18453 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18454 TUK != TagUseKind::Friend &&
18455 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
18456 !(OldTag && isAcceptableTagRedeclContext(
18457 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
18458 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
18459 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
18460 DiagID: diag::note_using_decl_target);
18461 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
18462 << 0;
18463 // Recover by ignoring the old declaration.
18464 Previous.clear();
18465 goto CreateNewDecl;
18466 }
18467 }
18468
18469 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
18470 // If this is a use of a previous tag, or if the tag is already declared
18471 // in the same scope (so that the definition/declaration completes or
18472 // rementions the tag), reuse the decl.
18473 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18474 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18475 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18476 // Make sure that this wasn't declared as an enum and now used as a
18477 // struct or something similar.
18478 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
18479 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18480 Name)) {
18481 bool SafeToContinue =
18482 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18483 Kind != TagTypeKind::Enum);
18484 if (SafeToContinue)
18485 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18486 << Name
18487 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18488 Code: PrevTagDecl->getKindName());
18489 else
18490 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18491 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18492
18493 if (SafeToContinue)
18494 Kind = PrevTagDecl->getTagKind();
18495 else {
18496 // Recover by making this an anonymous redefinition.
18497 Name = nullptr;
18498 Previous.clear();
18499 Invalid = true;
18500 }
18501 }
18502
18503 if (Kind == TagTypeKind::Enum &&
18504 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18505 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18506 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18507 return PrevTagDecl;
18508
18509 QualType EnumUnderlyingTy;
18510 if (TypeSourceInfo *TI =
18511 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18512 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18513 else if (const Type *T =
18514 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18515 EnumUnderlyingTy = QualType(T, 0);
18516
18517 // All conflicts with previous declarations are recovered by
18518 // returning the previous declaration, unless this is a definition,
18519 // in which case we want the caller to bail out.
18520 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18521 IsScoped: ScopedEnum, EnumUnderlyingTy,
18522 IsFixed, Prev: PrevEnum))
18523 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18524 }
18525
18526 // C++11 [class.mem]p1:
18527 // A member shall not be declared twice in the member-specification,
18528 // except that a nested class or member class template can be declared
18529 // and then later defined.
18530 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18531 S->isDeclScope(D: PrevDecl)) {
18532 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18533 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18534 }
18535
18536 if (!Invalid) {
18537 // If this is a use, just return the declaration we found, unless
18538 // we have attributes.
18539 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18540 if (!Attrs.empty()) {
18541 // FIXME: Diagnose these attributes. For now, we create a new
18542 // declaration to hold them.
18543 } else if (TUK == TagUseKind::Reference &&
18544 (PrevTagDecl->getFriendObjectKind() ==
18545 Decl::FOK_Undeclared ||
18546 PrevDecl->getOwningModule() != getCurrentModule()) &&
18547 SS.isEmpty()) {
18548 // This declaration is a reference to an existing entity, but
18549 // has different visibility from that entity: it either makes
18550 // a friend visible or it makes a type visible in a new module.
18551 // In either case, create a new declaration. We only do this if
18552 // the declaration would have meant the same thing if no prior
18553 // declaration were found, that is, if it was found in the same
18554 // scope where we would have injected a declaration.
18555 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18556 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18557 return PrevTagDecl;
18558 // This is in the injected scope, create a new declaration in
18559 // that scope.
18560 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18561 } else {
18562 return PrevTagDecl;
18563 }
18564 }
18565
18566 // Diagnose attempts to redefine a tag.
18567 if (TUK == TagUseKind::Definition) {
18568 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18569 // If the type is currently being defined, complain
18570 // about a nested redefinition.
18571 if (Def->isBeingDefined()) {
18572 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18573 Diag(Loc: PrevTagDecl->getLocation(),
18574 DiagID: diag::note_previous_definition);
18575 Name = nullptr;
18576 Previous.clear();
18577 Invalid = true;
18578 } else {
18579 // If we're defining a specialization and the previous
18580 // definition is from an implicit instantiation, don't emit an
18581 // error here; we'll catch this in the general case below.
18582 bool IsExplicitSpecializationAfterInstantiation = false;
18583 if (isMemberSpecialization) {
18584 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18585 IsExplicitSpecializationAfterInstantiation =
18586 RD->getTemplateSpecializationKind() !=
18587 TSK_ExplicitSpecialization;
18588 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18589 IsExplicitSpecializationAfterInstantiation =
18590 ED->getTemplateSpecializationKind() !=
18591 TSK_ExplicitSpecialization;
18592 }
18593
18594 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18595 // do not keep more that one definition around (merge them).
18596 // However, ensure the decl passes the structural compatibility
18597 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18598 NamedDecl *Hidden = nullptr;
18599 bool HiddenDefVisible = false;
18600 if (SkipBody &&
18601 (isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible) ||
18602 getLangOpts().C23)) {
18603 // There is a definition of this tag, but it is not visible.
18604 // We explicitly make use of C++'s one definition rule here,
18605 // and assume that this definition is identical to the hidden
18606 // one we already have. Make the existing definition visible
18607 // and use it in place of this one.
18608 if (!getLangOpts().CPlusPlus) {
18609 // Postpone making the old definition visible until after we
18610 // complete parsing the new one and do the structural
18611 // comparison.
18612 SkipBody->CheckSameAsPrevious = true;
18613 SkipBody->New = createTagFromNewDecl();
18614 SkipBody->Previous = Def;
18615
18616 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18617 return Def;
18618 }
18619
18620 SkipBody->ShouldSkip = true;
18621 SkipBody->Previous = Def;
18622 if (!HiddenDefVisible && Hidden)
18623 makeMergedDefinitionVisible(ND: Hidden);
18624 // Carry on and handle it like a normal definition. We'll
18625 // skip starting the definition later.
18626
18627 } else if (!IsExplicitSpecializationAfterInstantiation) {
18628 // A redeclaration in function prototype scope in C isn't
18629 // visible elsewhere, so merely issue a warning.
18630 if (!getLangOpts().CPlusPlus &&
18631 S->containedInPrototypeScope())
18632 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list)
18633 << Name;
18634 else
18635 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18636 notePreviousDefinition(Old: Def,
18637 New: NameLoc.isValid() ? NameLoc : KWLoc);
18638 // If this is a redefinition, recover by making this
18639 // struct be anonymous, which will make any later
18640 // references get the previous definition.
18641 Name = nullptr;
18642 Previous.clear();
18643 Invalid = true;
18644 }
18645 }
18646 }
18647
18648 // Okay, this is definition of a previously declared or referenced
18649 // tag. We're going to create a new Decl for it.
18650 }
18651
18652 // Okay, we're going to make a redeclaration. If this is some kind
18653 // of reference, make sure we build the redeclaration in the same DC
18654 // as the original, and ignore the current access specifier.
18655 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18656 SearchDC = PrevTagDecl->getDeclContext();
18657 AS = AS_none;
18658 }
18659 }
18660 // If we get here we have (another) forward declaration or we
18661 // have a definition. Just create a new decl.
18662
18663 } else {
18664 // If we get here, this is a definition of a new tag type in a nested
18665 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18666 // new decl/type. We set PrevDecl to NULL so that the entities
18667 // have distinct types.
18668 Previous.clear();
18669 }
18670 // If we get here, we're going to create a new Decl. If PrevDecl
18671 // is non-NULL, it's a definition of the tag declared by
18672 // PrevDecl. If it's NULL, we have a new definition.
18673
18674 // Otherwise, PrevDecl is not a tag, but was found with tag
18675 // lookup. This is only actually possible in C++, where a few
18676 // things like templates still live in the tag namespace.
18677 } else {
18678 // Use a better diagnostic if an elaborated-type-specifier
18679 // found the wrong kind of type on the first
18680 // (non-redeclaration) lookup.
18681 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18682 !Previous.isForRedeclaration()) {
18683 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18684 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18685 << PrevDecl << NTK << Kind;
18686 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18687 Invalid = true;
18688
18689 // Otherwise, only diagnose if the declaration is in scope.
18690 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18691 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18692 // do nothing
18693
18694 // Diagnose implicit declarations introduced by elaborated types.
18695 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18696 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18697 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
18698 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18699 Invalid = true;
18700
18701 // Otherwise it's a declaration. Call out a particularly common
18702 // case here.
18703 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18704 unsigned Kind = 0;
18705 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18706 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
18707 << Name << Kind << TND->getUnderlyingType();
18708 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18709 Invalid = true;
18710
18711 // Otherwise, diagnose.
18712 } else {
18713 // The tag name clashes with something else in the target scope,
18714 // issue an error and recover by making this tag be anonymous.
18715 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
18716 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18717 Name = nullptr;
18718 Invalid = true;
18719 }
18720
18721 // The existing declaration isn't relevant to us; we're in a
18722 // new scope, so clear out the previous declaration.
18723 Previous.clear();
18724 }
18725 }
18726
18727CreateNewDecl:
18728
18729 TagDecl *PrevDecl = nullptr;
18730 if (Previous.isSingleResult())
18731 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18732
18733 // If there is an identifier, use the location of the identifier as the
18734 // location of the decl, otherwise use the location of the struct/union
18735 // keyword.
18736 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18737
18738 // Otherwise, create a new declaration. If there is a previous
18739 // declaration of the same entity, the two will be linked via
18740 // PrevDecl.
18741 TagDecl *New;
18742
18743 if (Kind == TagTypeKind::Enum) {
18744 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18745 // enum X { A, B, C } D; D should chain to X.
18746 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18747 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
18748 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18749
18750 EnumDecl *ED = cast<EnumDecl>(Val: New);
18751 ED->setEnumKeyRange(SourceRange(
18752 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18753
18754 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18755 StdAlignValT = cast<EnumDecl>(Val: New);
18756
18757 // If this is an undefined enum, warn.
18758 if (TUK != TagUseKind::Definition && !Invalid) {
18759 TagDecl *Def;
18760 if (IsFixed && ED->isFixed()) {
18761 // C++0x: 7.2p2: opaque-enum-declaration.
18762 // Conflicts are diagnosed above. Do nothing.
18763 } else if (PrevDecl &&
18764 (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
18765 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
18766 << New;
18767 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
18768 } else {
18769 unsigned DiagID = diag::ext_forward_ref_enum;
18770 if (getLangOpts().MSVCCompat)
18771 DiagID = diag::ext_ms_forward_ref_enum;
18772 else if (getLangOpts().CPlusPlus)
18773 DiagID = diag::err_forward_ref_enum;
18774 Diag(Loc, DiagID);
18775 }
18776 }
18777
18778 if (EnumUnderlying) {
18779 EnumDecl *ED = cast<EnumDecl>(Val: New);
18780 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18781 ED->setIntegerTypeSourceInfo(TI);
18782 else
18783 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18784 QualType EnumTy = ED->getIntegerType();
18785 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18786 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18787 : EnumTy);
18788 assert(ED->isComplete() && "enum with type should be complete");
18789 }
18790 } else {
18791 // struct/union/class
18792
18793 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18794 // struct X { int A; } D; D should chain to X.
18795 if (getLangOpts().CPlusPlus) {
18796 // FIXME: Look for a way to use RecordDecl for simple structs.
18797 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18798 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
18799
18800 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18801 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
18802 } else
18803 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18804 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
18805 }
18806
18807 // Only C23 and later allow defining new types in 'offsetof()'.
18808 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18809 !getLangOpts().CPlusPlus && !getLangOpts().C23)
18810 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
18811 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18812
18813 // C++11 [dcl.type]p3:
18814 // A type-specifier-seq shall not define a class or enumeration [...].
18815 if (!Invalid && getLangOpts().CPlusPlus &&
18816 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18817 TUK == TagUseKind::Definition) {
18818 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
18819 << Context.getCanonicalTagType(TD: New);
18820 Invalid = true;
18821 }
18822
18823 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
18824 DC->getDeclKind() == Decl::Enum) {
18825 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
18826 << Context.getCanonicalTagType(TD: New);
18827 Invalid = true;
18828 }
18829
18830 // Maybe add qualifier info.
18831 if (SS.isNotEmpty()) {
18832 if (SS.isSet()) {
18833 // If this is either a declaration or a definition, check the
18834 // nested-name-specifier against the current context.
18835 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18836 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
18837 /*TemplateId=*/nullptr,
18838 IsMemberSpecialization: isMemberSpecialization))
18839 Invalid = true;
18840
18841 New->setQualifierInfo(SS.getWithLocInContext(Context));
18842 if (TemplateParameterLists.size() > 0) {
18843 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
18844 }
18845 }
18846 else
18847 Invalid = true;
18848 }
18849
18850 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18851 // Add alignment attributes if necessary; these attributes are checked when
18852 // the ASTContext lays out the structure.
18853 //
18854 // It is important for implementing the correct semantics that this
18855 // happen here (in ActOnTag). The #pragma pack stack is
18856 // maintained as a result of parser callbacks which can occur at
18857 // many points during the parsing of a struct declaration (because
18858 // the #pragma tokens are effectively skipped over during the
18859 // parsing of the struct).
18860 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18861 if (LangOpts.HLSL)
18862 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18863 AddAlignmentAttributesForRecord(RD);
18864 AddMsStructLayoutForRecord(RD);
18865 }
18866 }
18867
18868 if (ModulePrivateLoc.isValid()) {
18869 if (isMemberSpecialization)
18870 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
18871 << 2
18872 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
18873 // __module_private__ does not apply to local classes. However, we only
18874 // diagnose this as an error when the declaration specifiers are
18875 // freestanding. Here, we just ignore the __module_private__.
18876 else if (!SearchDC->isFunctionOrMethod())
18877 New->setModulePrivate();
18878 }
18879
18880 // If this is a specialization of a member class (of a class template),
18881 // check the specialization.
18882 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
18883 Invalid = true;
18884
18885 // If we're declaring or defining a tag in function prototype scope in C,
18886 // note that this type can only be used within the function and add it to
18887 // the list of decls to inject into the function definition scope. However,
18888 // in C23 and later, while the type is only visible within the function, the
18889 // function can be called with a compatible type defined in the same TU, so
18890 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18891 if ((Name || Kind == TagTypeKind::Enum) &&
18892 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18893 if (getLangOpts().CPlusPlus) {
18894 // C++ [dcl.fct]p6:
18895 // Types shall not be defined in return or parameter types.
18896 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18897 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
18898 << Name;
18899 Invalid = true;
18900 }
18901 if (TUK == TagUseKind::Declaration)
18902 Invalid = true;
18903 } else if (!PrevDecl) {
18904 // In C23 mode, if the declaration is complete, we do not want to
18905 // diagnose.
18906 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18907 Diag(Loc, DiagID: diag::warn_decl_in_param_list)
18908 << Context.getCanonicalTagType(TD: New);
18909 }
18910 }
18911
18912 if (Invalid)
18913 New->setInvalidDecl();
18914
18915 // Set the lexical context. If the tag has a C++ scope specifier, the
18916 // lexical context will be different from the semantic context.
18917 New->setLexicalDeclContext(CurContext);
18918
18919 // Mark this as a friend decl if applicable.
18920 // In Microsoft mode, a friend declaration also acts as a forward
18921 // declaration so we always pass true to setObjectOfFriendDecl to make
18922 // the tag name visible.
18923 if (TUK == TagUseKind::Friend)
18924 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18925
18926 // Set the access specifier.
18927 if (!Invalid && SearchDC->isRecord())
18928 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
18929
18930 if (PrevDecl)
18931 CheckRedeclarationInModule(New, Old: PrevDecl);
18932
18933 if (TUK == TagUseKind::Definition) {
18934 if (!SkipBody || !SkipBody->ShouldSkip) {
18935 New->startDefinition();
18936 } else {
18937 New->setCompleteDefinition();
18938 New->demoteThisDefinitionToDeclaration();
18939 }
18940 }
18941
18942 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
18943 AddPragmaAttributes(S, D: New);
18944
18945 // If this has an identifier, add it to the scope stack.
18946 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18947 // We might be replacing an existing declaration in the lookup tables;
18948 // if so, borrow its access specifier.
18949 if (PrevDecl)
18950 New->setAccess(PrevDecl->getAccess());
18951
18952 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18953 DC->makeDeclVisibleInContext(D: New);
18954 if (Name) // can be null along some error paths
18955 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18956 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
18957 } else if (Name) {
18958 S = getNonFieldDeclScope(S);
18959 PushOnScopeChains(D: New, S, AddToContext: true);
18960 } else {
18961 CurContext->addDecl(D: New);
18962 }
18963
18964 // If this is the C FILE type, notify the AST context.
18965 if (IdentifierInfo *II = New->getIdentifier())
18966 if (!New->isInvalidDecl() &&
18967 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18968 II->isStr(Str: "FILE"))
18969 Context.setFILEDecl(New);
18970
18971 if (PrevDecl)
18972 mergeDeclAttributes(New, Old: PrevDecl);
18973
18974 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
18975 inferGslOwnerPointerAttribute(Record: CXXRD);
18976 inferNullableClassAttribute(CRD: CXXRD);
18977 }
18978
18979 // If there's a #pragma GCC visibility in scope, set the visibility of this
18980 // record.
18981 AddPushedVisibilityAttribute(RD: New);
18982
18983 // If this is not a definition, process API notes for it now.
18984 if (TUK != TagUseKind::Definition)
18985 ProcessAPINotes(D: New);
18986
18987 if (isMemberSpecialization && !New->isInvalidDecl())
18988 CompleteMemberSpecialization(Member: New, Previous);
18989
18990 OwnedDecl = true;
18991 // In C++, don't return an invalid declaration. We can't recover well from
18992 // the cases where we make the type anonymous.
18993 if (Invalid && getLangOpts().CPlusPlus) {
18994 if (New->isBeingDefined())
18995 if (auto RD = dyn_cast<RecordDecl>(Val: New))
18996 RD->completeDefinition();
18997 return true;
18998 } else if (SkipBody && SkipBody->ShouldSkip) {
18999 return SkipBody->Previous;
19000 } else {
19001 return New;
19002 }
19003}
19004
19005void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
19006 AdjustDeclIfTemplate(Decl&: TagD);
19007 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19008
19009 // Enter the tag context.
19010 PushDeclContext(S, DC: Tag);
19011
19012 ActOnDocumentableDecl(D: TagD);
19013
19014 // If there's a #pragma GCC visibility in scope, set the visibility of this
19015 // record.
19016 AddPushedVisibilityAttribute(RD: Tag);
19017}
19018
19019bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
19020 SkipBodyInfo &SkipBody) {
19021 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
19022 return false;
19023
19024 // Make the previous decl visible.
19025 makeMergedDefinitionVisible(ND: SkipBody.Previous);
19026 CleanupMergedEnum(S, New: SkipBody.New);
19027 return true;
19028}
19029
19030void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
19031 SourceLocation FinalLoc,
19032 bool IsFinalSpelledSealed,
19033 bool IsAbstract,
19034 SourceLocation LBraceLoc) {
19035 AdjustDeclIfTemplate(Decl&: TagD);
19036 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
19037
19038 FieldCollector->StartClass();
19039
19040 if (!Record->getIdentifier())
19041 return;
19042
19043 if (IsAbstract)
19044 Record->markAbstract();
19045
19046 if (FinalLoc.isValid()) {
19047 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
19048 S: IsFinalSpelledSealed
19049 ? FinalAttr::Keyword_sealed
19050 : FinalAttr::Keyword_final));
19051 }
19052
19053 // C++ [class]p2:
19054 // [...] The class-name is also inserted into the scope of the
19055 // class itself; this is known as the injected-class-name. For
19056 // purposes of access checking, the injected-class-name is treated
19057 // as if it were a public member name.
19058 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19059 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
19060 IdLoc: Record->getLocation(), Id: Record->getIdentifier());
19061 InjectedClassName->setImplicit();
19062 InjectedClassName->setAccess(AS_public);
19063 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19064 InjectedClassName->setDescribedClassTemplate(Template);
19065
19066 PushOnScopeChains(D: InjectedClassName, S);
19067 assert(InjectedClassName->isInjectedClassName() &&
19068 "Broken injected-class-name");
19069}
19070
19071void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
19072 SourceRange BraceRange) {
19073 AdjustDeclIfTemplate(Decl&: TagD);
19074 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19075 Tag->setBraceRange(BraceRange);
19076
19077 // Make sure we "complete" the definition even it is invalid.
19078 if (Tag->isBeingDefined()) {
19079 assert(Tag->isInvalidDecl() && "We should already have completed it");
19080 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19081 RD->completeDefinition();
19082 }
19083
19084 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
19085 FieldCollector->FinishClass();
19086 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19087 auto *Def = RD->getDefinition();
19088 assert(Def && "The record is expected to have a completed definition");
19089 unsigned NumInitMethods = 0;
19090 for (auto *Method : Def->methods()) {
19091 if (!Method->getIdentifier())
19092 continue;
19093 if (Method->getName() == "__init")
19094 NumInitMethods++;
19095 }
19096 if (NumInitMethods > 1 || !Def->hasInitMethod())
19097 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
19098 }
19099
19100 // If we're defining a dynamic class in a module interface unit, we always
19101 // need to produce the vtable for it, even if the vtable is not used in the
19102 // current TU.
19103 //
19104 // The case where the current class is not dynamic is handled in
19105 // MarkVTableUsed.
19106 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19107 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
19108 }
19109
19110 // Exit this scope of this tag's definition.
19111 PopDeclContext();
19112
19113 if (getCurLexicalContext()->isObjCContainer() &&
19114 Tag->getDeclContext()->isFileContext())
19115 Tag->setTopLevelDeclInObjCContainer();
19116
19117 // Notify the consumer that we've defined a tag.
19118 if (!Tag->isInvalidDecl())
19119 Consumer.HandleTagDeclDefinition(D: Tag);
19120
19121 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19122 // from XLs and instead matches the XL #pragma pack(1) behavior.
19123 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19124 AlignPackStack.hasValue()) {
19125 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19126 // Only diagnose #pragma align(packed).
19127 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19128 return;
19129 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
19130 if (!RD)
19131 return;
19132 // Only warn if there is at least 1 bitfield member.
19133 if (llvm::any_of(Range: RD->fields(),
19134 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
19135 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
19136 }
19137}
19138
19139void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
19140 AdjustDeclIfTemplate(Decl&: TagD);
19141 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19142 Tag->setInvalidDecl();
19143
19144 // Make sure we "complete" the definition even it is invalid.
19145 if (Tag->isBeingDefined()) {
19146 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19147 RD->completeDefinition();
19148 }
19149
19150 // We're undoing ActOnTagStartDefinition here, not
19151 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19152 // the FieldCollector.
19153
19154 PopDeclContext();
19155}
19156
19157// Note that FieldName may be null for anonymous bitfields.
19158ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
19159 const IdentifierInfo *FieldName,
19160 QualType FieldTy, bool IsMsStruct,
19161 Expr *BitWidth) {
19162 assert(BitWidth);
19163 if (BitWidth->containsErrors())
19164 return ExprError();
19165
19166 // C99 6.7.2.1p4 - verify the field type.
19167 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19168 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19169 // Handle incomplete and sizeless types with a specific error.
19170 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
19171 DiagID: diag::err_field_incomplete_or_sizeless))
19172 return ExprError();
19173 if (FieldName)
19174 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
19175 << FieldName << FieldTy << BitWidth->getSourceRange();
19176 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
19177 << FieldTy << BitWidth->getSourceRange();
19178 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
19179 return ExprError();
19180
19181 // If the bit-width is type- or value-dependent, don't try to check
19182 // it now.
19183 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19184 return BitWidth;
19185
19186 llvm::APSInt Value;
19187 ExprResult ICE =
19188 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
19189 if (ICE.isInvalid())
19190 return ICE;
19191 BitWidth = ICE.get();
19192
19193 // Zero-width bitfield is ok for anonymous field.
19194 if (Value == 0 && FieldName)
19195 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
19196 << FieldName << BitWidth->getSourceRange();
19197
19198 if (Value.isSigned() && Value.isNegative()) {
19199 if (FieldName)
19200 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
19201 << FieldName << toString(I: Value, Radix: 10);
19202 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
19203 << toString(I: Value, Radix: 10);
19204 }
19205
19206 // The size of the bit-field must not exceed our maximum permitted object
19207 // size.
19208 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19209 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
19210 << !FieldName << FieldName << toString(I: Value, Radix: 10);
19211 }
19212
19213 if (!FieldTy->isDependentType()) {
19214 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
19215 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
19216 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
19217
19218 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19219 // ABI.
19220 bool CStdConstraintViolation =
19221 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19222 bool MSBitfieldViolation = Value.ugt(RHS: TypeStorageSize) && IsMsStruct;
19223 if (CStdConstraintViolation || MSBitfieldViolation) {
19224 unsigned DiagWidth =
19225 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19226 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
19227 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
19228 << !CStdConstraintViolation << DiagWidth;
19229 }
19230
19231 // Warn on types where the user might conceivably expect to get all
19232 // specified bits as value bits: that's all integral types other than
19233 // 'bool'.
19234 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19235 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
19236 << FieldName << Value << (unsigned)TypeWidth;
19237 }
19238 }
19239
19240 if (isa<ConstantExpr>(Val: BitWidth))
19241 return BitWidth;
19242 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
19243}
19244
19245Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19246 Declarator &D, Expr *BitfieldWidth) {
19247 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
19248 D, BitfieldWidth,
19249 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
19250 return Res;
19251}
19252
19253FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19254 SourceLocation DeclStart,
19255 Declarator &D, Expr *BitWidth,
19256 InClassInitStyle InitStyle,
19257 AccessSpecifier AS) {
19258 if (D.isDecompositionDeclarator()) {
19259 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19260 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
19261 << Decomp.getSourceRange();
19262 return nullptr;
19263 }
19264
19265 const IdentifierInfo *II = D.getIdentifier();
19266 SourceLocation Loc = DeclStart;
19267 if (II) Loc = D.getIdentifierLoc();
19268
19269 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19270 QualType T = TInfo->getType();
19271 if (getLangOpts().CPlusPlus) {
19272 CheckExtraCXXDefaultArguments(D);
19273
19274 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19275 UPPC: UPPC_DataMemberType)) {
19276 D.setInvalidType();
19277 T = Context.IntTy;
19278 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19279 }
19280 }
19281
19282 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19283
19284 if (D.getDeclSpec().isInlineSpecified())
19285 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19286 << getLangOpts().CPlusPlus17;
19287 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19288 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19289 DiagID: diag::err_invalid_thread)
19290 << DeclSpec::getSpecifierName(S: TSCS);
19291
19292 // Check to see if this name was declared as a member previously
19293 NamedDecl *PrevDecl = nullptr;
19294 LookupResult Previous(*this, II, Loc, LookupMemberName,
19295 RedeclarationKind::ForVisibleRedeclaration);
19296 LookupName(R&: Previous, S);
19297 switch (Previous.getResultKind()) {
19298 case LookupResultKind::Found:
19299 case LookupResultKind::FoundUnresolvedValue:
19300 PrevDecl = Previous.getAsSingle<NamedDecl>();
19301 break;
19302
19303 case LookupResultKind::FoundOverloaded:
19304 PrevDecl = Previous.getRepresentativeDecl();
19305 break;
19306
19307 case LookupResultKind::NotFound:
19308 case LookupResultKind::NotFoundInCurrentInstantiation:
19309 case LookupResultKind::Ambiguous:
19310 break;
19311 }
19312 Previous.suppressDiagnostics();
19313
19314 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19315 // Maybe we will complain about the shadowed template parameter.
19316 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19317 // Just pretend that we didn't see the previous declaration.
19318 PrevDecl = nullptr;
19319 }
19320
19321 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19322 PrevDecl = nullptr;
19323
19324 bool Mutable
19325 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19326 SourceLocation TSSL = D.getBeginLoc();
19327 FieldDecl *NewFD
19328 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
19329 TSSL, AS, PrevDecl, D: &D);
19330
19331 if (NewFD->isInvalidDecl())
19332 Record->setInvalidDecl();
19333
19334 if (D.getDeclSpec().isModulePrivateSpecified())
19335 NewFD->setModulePrivate();
19336
19337 if (NewFD->isInvalidDecl() && PrevDecl) {
19338 // Don't introduce NewFD into scope; there's already something
19339 // with the same name in the same scope.
19340 } else if (II) {
19341 PushOnScopeChains(D: NewFD, S);
19342 } else
19343 Record->addDecl(D: NewFD);
19344
19345 return NewFD;
19346}
19347
19348FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19349 TypeSourceInfo *TInfo,
19350 RecordDecl *Record, SourceLocation Loc,
19351 bool Mutable, Expr *BitWidth,
19352 InClassInitStyle InitStyle,
19353 SourceLocation TSSL,
19354 AccessSpecifier AS, NamedDecl *PrevDecl,
19355 Declarator *D) {
19356 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19357 bool InvalidDecl = false;
19358 if (D) InvalidDecl = D->isInvalidType();
19359
19360 // If we receive a broken type, recover by assuming 'int' and
19361 // marking this declaration as invalid.
19362 if (T.isNull() || T->containsErrors()) {
19363 InvalidDecl = true;
19364 T = Context.IntTy;
19365 }
19366
19367 QualType EltTy = Context.getBaseElementType(QT: T);
19368 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19369 bool isIncomplete =
19370 LangOpts.HLSL // HLSL allows sizeless builtin types
19371 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
19372 : RequireCompleteSizedType(Loc, T: EltTy,
19373 DiagID: diag::err_field_incomplete_or_sizeless);
19374 if (isIncomplete) {
19375 // Fields of incomplete type force their record to be invalid.
19376 Record->setInvalidDecl();
19377 InvalidDecl = true;
19378 } else {
19379 NamedDecl *Def;
19380 EltTy->isIncompleteType(Def: &Def);
19381 if (Def && Def->isInvalidDecl()) {
19382 Record->setInvalidDecl();
19383 InvalidDecl = true;
19384 }
19385 }
19386 }
19387
19388 // TR 18037 does not allow fields to be declared with address space
19389 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19390 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19391 Diag(Loc, DiagID: diag::err_field_with_address_space);
19392 Record->setInvalidDecl();
19393 InvalidDecl = true;
19394 }
19395
19396 if (LangOpts.OpenCL) {
19397 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19398 // used as structure or union field: image, sampler, event or block types.
19399 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19400 T->isBlockPointerType()) {
19401 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
19402 Record->setInvalidDecl();
19403 InvalidDecl = true;
19404 }
19405 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19406 // is enabled.
19407 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19408 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
19409 Diag(Loc, DiagID: diag::err_opencl_bitfields);
19410 InvalidDecl = true;
19411 }
19412 }
19413
19414 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19415 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19416 T.hasQualifiers()) {
19417 InvalidDecl = true;
19418 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
19419 }
19420
19421 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19422 // than a variably modified type.
19423 if (!InvalidDecl && T->isVariablyModifiedType()) {
19424 if (!tryToFixVariablyModifiedVarType(
19425 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
19426 InvalidDecl = true;
19427 }
19428
19429 // Fields can not have abstract class types
19430 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19431 DiagID: diag::err_abstract_type_in_decl,
19432 Args: AbstractFieldType))
19433 InvalidDecl = true;
19434
19435 if (InvalidDecl)
19436 BitWidth = nullptr;
19437 // If this is declared as a bit-field, check the bit-field.
19438 if (BitWidth) {
19439 BitWidth =
19440 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
19441 if (!BitWidth) {
19442 InvalidDecl = true;
19443 BitWidth = nullptr;
19444 }
19445 }
19446
19447 // Check that 'mutable' is consistent with the type of the declaration.
19448 if (!InvalidDecl && Mutable) {
19449 unsigned DiagID = 0;
19450 if (T->isReferenceType())
19451 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19452 : diag::err_mutable_reference;
19453 else if (T.isConstQualified())
19454 DiagID = diag::err_mutable_const;
19455
19456 if (DiagID) {
19457 SourceLocation ErrLoc = Loc;
19458 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19459 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19460 Diag(Loc: ErrLoc, DiagID);
19461 if (DiagID != diag::ext_mutable_reference) {
19462 Mutable = false;
19463 InvalidDecl = true;
19464 }
19465 }
19466 }
19467
19468 // C++11 [class.union]p8 (DR1460):
19469 // At most one variant member of a union may have a
19470 // brace-or-equal-initializer.
19471 if (InitStyle != ICIS_NoInit)
19472 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
19473
19474 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
19475 BW: BitWidth, Mutable, InitStyle);
19476 if (InvalidDecl)
19477 NewFD->setInvalidDecl();
19478
19479 if (!InvalidDecl)
19480 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
19481
19482 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
19483 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
19484 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
19485 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
19486 NewFD->setInvalidDecl();
19487 }
19488
19489 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19490 if (Record->isUnion()) {
19491 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19492 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19493
19494 // C++ [class.union]p1: An object of a class with a non-trivial
19495 // constructor, a non-trivial copy constructor, a non-trivial
19496 // destructor, or a non-trivial copy assignment operator
19497 // cannot be a member of a union, nor can an array of such
19498 // objects.
19499 if (CheckNontrivialField(FD: NewFD))
19500 NewFD->setInvalidDecl();
19501 }
19502
19503 // C++ [class.union]p1: If a union contains a member of reference type,
19504 // the program is ill-formed, except when compiling with MSVC extensions
19505 // enabled.
19506 if (EltTy->isReferenceType()) {
19507 const bool HaveMSExt =
19508 getLangOpts().MicrosoftExt &&
19509 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19510
19511 Diag(Loc: NewFD->getLocation(),
19512 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19513 : diag::err_union_member_of_reference_type)
19514 << NewFD->getDeclName() << EltTy;
19515 if (!HaveMSExt)
19516 NewFD->setInvalidDecl();
19517 }
19518 }
19519 }
19520
19521 // FIXME: We need to pass in the attributes given an AST
19522 // representation, not a parser representation.
19523 if (D) {
19524 // FIXME: The current scope is almost... but not entirely... correct here.
19525 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19526
19527 if (NewFD->hasAttrs())
19528 CheckAlignasUnderalignment(D: NewFD);
19529 }
19530
19531 // In auto-retain/release, infer strong retension for fields of
19532 // retainable type.
19533 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19534 NewFD->setInvalidDecl();
19535
19536 if (T.isObjCGCWeak())
19537 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19538
19539 // PPC MMA non-pointer types are not allowed as field types.
19540 if (Context.getTargetInfo().getTriple().isPPC64() &&
19541 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19542 NewFD->setInvalidDecl();
19543
19544 NewFD->setAccess(AS);
19545 return NewFD;
19546}
19547
19548bool Sema::CheckNontrivialField(FieldDecl *FD) {
19549 assert(FD);
19550 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19551
19552 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19553 return false;
19554
19555 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19556 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19557 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19558 // We check for copy constructors before constructors
19559 // because otherwise we'll never get complaints about
19560 // copy constructors.
19561
19562 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19563 // We're required to check for any non-trivial constructors. Since the
19564 // implicit default constructor is suppressed if there are any
19565 // user-declared constructors, we just need to check that there is a
19566 // trivial default constructor and a trivial copy constructor. (We don't
19567 // worry about move constructors here, since this is a C++98 check.)
19568 if (RDecl->hasNonTrivialCopyConstructor())
19569 member = CXXSpecialMemberKind::CopyConstructor;
19570 else if (!RDecl->hasTrivialDefaultConstructor())
19571 member = CXXSpecialMemberKind::DefaultConstructor;
19572 else if (RDecl->hasNonTrivialCopyAssignment())
19573 member = CXXSpecialMemberKind::CopyAssignment;
19574 else if (RDecl->hasNonTrivialDestructor())
19575 member = CXXSpecialMemberKind::Destructor;
19576
19577 if (member != CXXSpecialMemberKind::Invalid) {
19578 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19579 RDecl->hasObjectMember()) {
19580 // Objective-C++ ARC: it is an error to have a non-trivial field of
19581 // a union. However, system headers in Objective-C programs
19582 // occasionally have Objective-C lifetime objects within unions,
19583 // and rather than cause the program to fail, we make those
19584 // members unavailable.
19585 SourceLocation Loc = FD->getLocation();
19586 if (getSourceManager().isInSystemHeader(Loc)) {
19587 if (!FD->hasAttr<UnavailableAttr>())
19588 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19589 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19590 return false;
19591 }
19592 }
19593
19594 Diag(Loc: FD->getLocation(),
19595 DiagID: getLangOpts().CPlusPlus11
19596 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19597 : diag::err_illegal_union_or_anon_struct_member)
19598 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19599 DiagnoseNontrivial(Record: RDecl, CSM: member);
19600 return !getLangOpts().CPlusPlus11;
19601 }
19602 }
19603
19604 return false;
19605}
19606
19607void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19608 SmallVectorImpl<Decl *> &AllIvarDecls) {
19609 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19610 return;
19611
19612 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19613 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19614
19615 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19616 return;
19617 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19618 if (!ID) {
19619 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19620 if (!CD->IsClassExtension())
19621 return;
19622 }
19623 // No need to add this to end of @implementation.
19624 else
19625 return;
19626 }
19627 // All conditions are met. Add a new bitfield to the tail end of ivars.
19628 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19629 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19630 Expr *BitWidth =
19631 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19632
19633 Ivar = ObjCIvarDecl::Create(
19634 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19635 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19636 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19637 AllIvarDecls.push_back(Elt: Ivar);
19638}
19639
19640/// [class.dtor]p4:
19641/// At the end of the definition of a class, overload resolution is
19642/// performed among the prospective destructors declared in that class with
19643/// an empty argument list to select the destructor for the class, also
19644/// known as the selected destructor.
19645///
19646/// We do the overload resolution here, then mark the selected constructor in the AST.
19647/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19648static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19649 if (!Record->hasUserDeclaredDestructor()) {
19650 return;
19651 }
19652
19653 SourceLocation Loc = Record->getLocation();
19654 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19655
19656 for (auto *Decl : Record->decls()) {
19657 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19658 if (DD->isInvalidDecl())
19659 continue;
19660 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19661 CandidateSet&: OCS);
19662 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19663 }
19664 }
19665
19666 if (OCS.empty()) {
19667 return;
19668 }
19669 OverloadCandidateSet::iterator Best;
19670 unsigned Msg = 0;
19671 OverloadCandidateDisplayKind DisplayKind;
19672
19673 switch (OCS.BestViableFunction(S, Loc, Best)) {
19674 case OR_Success:
19675 case OR_Deleted:
19676 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19677 break;
19678
19679 case OR_Ambiguous:
19680 Msg = diag::err_ambiguous_destructor;
19681 DisplayKind = OCD_AmbiguousCandidates;
19682 break;
19683
19684 case OR_No_Viable_Function:
19685 Msg = diag::err_no_viable_destructor;
19686 DisplayKind = OCD_AllCandidates;
19687 break;
19688 }
19689
19690 if (Msg) {
19691 // OpenCL have got their own thing going with destructors. It's slightly broken,
19692 // but we allow it.
19693 if (!S.LangOpts.OpenCL) {
19694 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19695 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19696 Record->setInvalidDecl();
19697 }
19698 // It's a bit hacky: At this point we've raised an error but we want the
19699 // rest of the compiler to continue somehow working. However almost
19700 // everything we'll try to do with the class will depend on there being a
19701 // destructor. So let's pretend the first one is selected and hope for the
19702 // best.
19703 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19704 }
19705}
19706
19707/// [class.mem.special]p5
19708/// Two special member functions are of the same kind if:
19709/// - they are both default constructors,
19710/// - they are both copy or move constructors with the same first parameter
19711/// type, or
19712/// - they are both copy or move assignment operators with the same first
19713/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19714static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19715 CXXMethodDecl *M1,
19716 CXXMethodDecl *M2,
19717 CXXSpecialMemberKind CSM) {
19718 // We don't want to compare templates to non-templates: See
19719 // https://github.com/llvm/llvm-project/issues/59206
19720 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19721 return bool(M1->getDescribedFunctionTemplate()) ==
19722 bool(M2->getDescribedFunctionTemplate());
19723 // FIXME: better resolve CWG
19724 // https://cplusplus.github.io/CWG/issues/2787.html
19725 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
19726 T2: M2->getNonObjectParameter(I: 0)->getType()))
19727 return false;
19728 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19729 T2: M2->getFunctionObjectParameterReferenceType()))
19730 return false;
19731
19732 return true;
19733}
19734
19735/// [class.mem.special]p6:
19736/// An eligible special member function is a special member function for which:
19737/// - the function is not deleted,
19738/// - the associated constraints, if any, are satisfied, and
19739/// - no special member function of the same kind whose associated constraints
19740/// [CWG2595], if any, are satisfied is more constrained.
19741static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19742 ArrayRef<CXXMethodDecl *> Methods,
19743 CXXSpecialMemberKind CSM) {
19744 SmallVector<bool, 4> SatisfactionStatus;
19745
19746 for (CXXMethodDecl *Method : Methods) {
19747 if (!Method->getTrailingRequiresClause())
19748 SatisfactionStatus.push_back(Elt: true);
19749 else {
19750 ConstraintSatisfaction Satisfaction;
19751 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
19752 SatisfactionStatus.push_back(Elt: false);
19753 else
19754 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19755 }
19756 }
19757
19758 for (size_t i = 0; i < Methods.size(); i++) {
19759 if (!SatisfactionStatus[i])
19760 continue;
19761 CXXMethodDecl *Method = Methods[i];
19762 CXXMethodDecl *OrigMethod = Method;
19763 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19764 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19765
19766 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
19767 bool AnotherMethodIsMoreConstrained = false;
19768 for (size_t j = 0; j < Methods.size(); j++) {
19769 if (i == j || !SatisfactionStatus[j])
19770 continue;
19771 CXXMethodDecl *OtherMethod = Methods[j];
19772 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19773 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19774
19775 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19776 CSM))
19777 continue;
19778
19779 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
19780 if (!Other)
19781 continue;
19782 if (!Orig) {
19783 AnotherMethodIsMoreConstrained = true;
19784 break;
19785 }
19786 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
19787 Result&: AnotherMethodIsMoreConstrained)) {
19788 // There was an error with the constraints comparison. Exit the loop
19789 // and don't consider this function eligible.
19790 AnotherMethodIsMoreConstrained = true;
19791 }
19792 if (AnotherMethodIsMoreConstrained)
19793 break;
19794 }
19795 // FIXME: Do not consider deleted methods as eligible after implementing
19796 // DR1734 and DR1496.
19797 if (!AnotherMethodIsMoreConstrained) {
19798 Method->setIneligibleOrNotSelected(false);
19799 Record->addedEligibleSpecialMemberFunction(MD: Method,
19800 SMKind: 1 << llvm::to_underlying(E: CSM));
19801 }
19802 }
19803}
19804
19805static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19806 CXXRecordDecl *Record) {
19807 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19808 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19809 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19810 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19811 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19812
19813 for (auto *Decl : Record->decls()) {
19814 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
19815 if (!MD) {
19816 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
19817 if (FTD)
19818 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
19819 }
19820 if (!MD)
19821 continue;
19822 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
19823 if (CD->isInvalidDecl())
19824 continue;
19825 if (CD->isDefaultConstructor())
19826 DefaultConstructors.push_back(Elt: MD);
19827 else if (CD->isCopyConstructor())
19828 CopyConstructors.push_back(Elt: MD);
19829 else if (CD->isMoveConstructor())
19830 MoveConstructors.push_back(Elt: MD);
19831 } else if (MD->isCopyAssignmentOperator()) {
19832 CopyAssignmentOperators.push_back(Elt: MD);
19833 } else if (MD->isMoveAssignmentOperator()) {
19834 MoveAssignmentOperators.push_back(Elt: MD);
19835 }
19836 }
19837
19838 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
19839 CSM: CXXSpecialMemberKind::DefaultConstructor);
19840 SetEligibleMethods(S, Record, Methods: CopyConstructors,
19841 CSM: CXXSpecialMemberKind::CopyConstructor);
19842 SetEligibleMethods(S, Record, Methods: MoveConstructors,
19843 CSM: CXXSpecialMemberKind::MoveConstructor);
19844 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
19845 CSM: CXXSpecialMemberKind::CopyAssignment);
19846 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
19847 CSM: CXXSpecialMemberKind::MoveAssignment);
19848}
19849
19850bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19851 // Check to see if a FieldDecl is a pointer to a function.
19852 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19853 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
19854 if (!FD) {
19855 // Check whether this is a forward declaration that was inserted by
19856 // Clang. This happens when a non-forward declared / defined type is
19857 // used, e.g.:
19858 //
19859 // struct foo {
19860 // struct bar *(*f)();
19861 // struct bar *(*g)();
19862 // };
19863 //
19864 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19865 // incomplete definition.
19866 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
19867 return !TD->isCompleteDefinition();
19868 return false;
19869 }
19870 QualType FieldType = FD->getType().getDesugaredType(Context);
19871 if (isa<PointerType>(Val: FieldType)) {
19872 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
19873 return PointeeType.getDesugaredType(Context)->isFunctionType();
19874 }
19875 // If a member is a struct entirely of function pointers, that counts too.
19876 if (const auto *Record = FieldType->getAsRecordDecl();
19877 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19878 return true;
19879 return false;
19880 };
19881
19882 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
19883}
19884
19885void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19886 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19887 SourceLocation RBrac,
19888 const ParsedAttributesView &Attrs) {
19889 assert(EnclosingDecl && "missing record or interface decl");
19890
19891 // If this is an Objective-C @implementation or category and we have
19892 // new fields here we should reset the layout of the interface since
19893 // it will now change.
19894 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
19895 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
19896 switch (DC->getKind()) {
19897 default: break;
19898 case Decl::ObjCCategory:
19899 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
19900 break;
19901 case Decl::ObjCImplementation:
19902 Context.
19903 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
19904 break;
19905 }
19906 }
19907
19908 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
19909 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
19910
19911 // Start counting up the number of named members; make sure to include
19912 // members of anonymous structs and unions in the total.
19913 unsigned NumNamedMembers = 0;
19914 if (Record) {
19915 for (const auto *I : Record->decls()) {
19916 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
19917 if (IFD->getDeclName())
19918 ++NumNamedMembers;
19919 }
19920 }
19921
19922 // Verify that all the fields are okay.
19923 SmallVector<FieldDecl*, 32> RecFields;
19924 const FieldDecl *PreviousField = nullptr;
19925 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19926 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
19927 FieldDecl *FD = cast<FieldDecl>(Val: *i);
19928
19929 // Get the type for the field.
19930 const Type *FDTy = FD->getType().getTypePtr();
19931
19932 if (!FD->isAnonymousStructOrUnion()) {
19933 // Remember all fields written by the user.
19934 RecFields.push_back(Elt: FD);
19935 }
19936
19937 // If the field is already invalid for some reason, don't emit more
19938 // diagnostics about it.
19939 if (FD->isInvalidDecl()) {
19940 EnclosingDecl->setInvalidDecl();
19941 continue;
19942 }
19943
19944 // C99 6.7.2.1p2:
19945 // A structure or union shall not contain a member with
19946 // incomplete or function type (hence, a structure shall not
19947 // contain an instance of itself, but may contain a pointer to
19948 // an instance of itself), except that the last member of a
19949 // structure with more than one named member may have incomplete
19950 // array type; such a structure (and any union containing,
19951 // possibly recursively, a member that is such a structure)
19952 // shall not be a member of a structure or an element of an
19953 // array.
19954 bool IsLastField = (i + 1 == Fields.end());
19955 if (FDTy->isFunctionType()) {
19956 // Field declared as a function.
19957 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
19958 << FD->getDeclName();
19959 FD->setInvalidDecl();
19960 EnclosingDecl->setInvalidDecl();
19961 continue;
19962 } else if (FDTy->isIncompleteArrayType() &&
19963 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
19964 if (Record) {
19965 // Flexible array member.
19966 // Microsoft and g++ is more permissive regarding flexible array.
19967 // It will accept flexible array in union and also
19968 // as the sole element of a struct/class.
19969 unsigned DiagID = 0;
19970 if (!Record->isUnion() && !IsLastField) {
19971 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
19972 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19973 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
19974 FD->setInvalidDecl();
19975 EnclosingDecl->setInvalidDecl();
19976 continue;
19977 } else if (Record->isUnion())
19978 DiagID = getLangOpts().MicrosoftExt
19979 ? diag::ext_flexible_array_union_ms
19980 : diag::ext_flexible_array_union_gnu;
19981 else if (NumNamedMembers < 1)
19982 DiagID = getLangOpts().MicrosoftExt
19983 ? diag::ext_flexible_array_empty_aggregate_ms
19984 : diag::ext_flexible_array_empty_aggregate_gnu;
19985
19986 if (DiagID)
19987 Diag(Loc: FD->getLocation(), DiagID)
19988 << FD->getDeclName() << Record->getTagKind();
19989 // While the layout of types that contain virtual bases is not specified
19990 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19991 // virtual bases after the derived members. This would make a flexible
19992 // array member declared at the end of an object not adjacent to the end
19993 // of the type.
19994 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19995 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
19996 << FD->getDeclName() << Record->getTagKind();
19997 if (!getLangOpts().C99)
19998 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
19999 << FD->getDeclName() << Record->getTagKind();
20000
20001 // If the element type has a non-trivial destructor, we would not
20002 // implicitly destroy the elements, so disallow it for now.
20003 //
20004 // FIXME: GCC allows this. We should probably either implicitly delete
20005 // the destructor of the containing class, or just allow this.
20006 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
20007 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20008 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
20009 << FD->getDeclName() << FD->getType();
20010 FD->setInvalidDecl();
20011 EnclosingDecl->setInvalidDecl();
20012 continue;
20013 }
20014 // Okay, we have a legal flexible array member at the end of the struct.
20015 Record->setHasFlexibleArrayMember(true);
20016 } else {
20017 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20018 // unless they are followed by another ivar. That check is done
20019 // elsewhere, after synthesized ivars are known.
20020 }
20021 } else if (!FDTy->isDependentType() &&
20022 (LangOpts.HLSL // HLSL allows sizeless builtin types
20023 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
20024 DiagID: diag::err_incomplete_type)
20025 : RequireCompleteSizedType(
20026 Loc: FD->getLocation(), T: FD->getType(),
20027 DiagID: diag::err_field_incomplete_or_sizeless))) {
20028 // Incomplete type
20029 FD->setInvalidDecl();
20030 EnclosingDecl->setInvalidDecl();
20031 continue;
20032 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20033 if (Record && RD->hasFlexibleArrayMember()) {
20034 // A type which contains a flexible array member is considered to be a
20035 // flexible array member.
20036 Record->setHasFlexibleArrayMember(true);
20037 if (!Record->isUnion()) {
20038 // If this is a struct/class and this is not the last element, reject
20039 // it. Note that GCC supports variable sized arrays in the middle of
20040 // structures.
20041 if (!IsLastField)
20042 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
20043 << FD->getDeclName() << FD->getType();
20044 else {
20045 // We support flexible arrays at the end of structs in
20046 // other structs as an extension.
20047 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
20048 << FD->getDeclName();
20049 }
20050 }
20051 }
20052 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
20053 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
20054 DiagID: diag::err_abstract_type_in_decl,
20055 Args: AbstractIvarType)) {
20056 // Ivars can not have abstract class types
20057 FD->setInvalidDecl();
20058 }
20059 if (Record && RD->hasObjectMember())
20060 Record->setHasObjectMember(true);
20061 if (Record && RD->hasVolatileMember())
20062 Record->setHasVolatileMember(true);
20063 } else if (FDTy->isObjCObjectType()) {
20064 /// A field cannot be an Objective-c object
20065 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
20066 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
20067 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
20068 FD->setType(T);
20069 } else if (Record && Record->isUnion() &&
20070 FD->getType().hasNonTrivialObjCLifetime() &&
20071 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
20072 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20073 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
20074 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
20075 // For backward compatibility, fields of C unions declared in system
20076 // headers that have non-trivial ObjC ownership qualifications are marked
20077 // as unavailable unless the qualifier is explicit and __strong. This can
20078 // break ABI compatibility between programs compiled with ARC and MRR, but
20079 // is a better option than rejecting programs using those unions under
20080 // ARC.
20081 FD->addAttr(A: UnavailableAttr::CreateImplicit(
20082 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
20083 Range: FD->getLocation()));
20084 } else if (getLangOpts().ObjC &&
20085 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20086 !Record->hasObjectMember()) {
20087 if (FD->getType()->isObjCObjectPointerType() ||
20088 FD->getType().isObjCGCStrong())
20089 Record->setHasObjectMember(true);
20090 else if (Context.getAsArrayType(T: FD->getType())) {
20091 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
20092 if (const auto *RD = BaseType->getAsRecordDecl();
20093 RD && RD->hasObjectMember())
20094 Record->setHasObjectMember(true);
20095 else if (BaseType->isObjCObjectPointerType() ||
20096 BaseType.isObjCGCStrong())
20097 Record->setHasObjectMember(true);
20098 }
20099 }
20100
20101 if (Record && !getLangOpts().CPlusPlus &&
20102 !shouldIgnoreForRecordTriviality(FD)) {
20103 QualType FT = FD->getType();
20104 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
20105 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20106 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
20107 Record->isUnion())
20108 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20109 }
20110 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
20111 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
20112 Record->setNonTrivialToPrimitiveCopy(true);
20113 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20114 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20115 }
20116 if (FD->hasAttr<ExplicitInitAttr>())
20117 Record->setHasUninitializedExplicitInitFields(true);
20118 if (FT.isDestructedType()) {
20119 Record->setNonTrivialToPrimitiveDestroy(true);
20120 Record->setParamDestroyedInCallee(true);
20121 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20122 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20123 }
20124
20125 if (const auto *RD = FT->getAsRecordDecl()) {
20126 if (RD->getArgPassingRestrictions() ==
20127 RecordArgPassingKind::CanNeverPassInRegs)
20128 Record->setArgPassingRestrictions(
20129 RecordArgPassingKind::CanNeverPassInRegs);
20130 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20131 Record->setArgPassingRestrictions(
20132 RecordArgPassingKind::CanNeverPassInRegs);
20133 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20134 Q && Q.isAddressDiscriminated()) {
20135 Record->setArgPassingRestrictions(
20136 RecordArgPassingKind::CanNeverPassInRegs);
20137 Record->setNonTrivialToPrimitiveCopy(true);
20138 }
20139 }
20140
20141 if (Record && FD->getType().isVolatileQualified())
20142 Record->setHasVolatileMember(true);
20143 bool ReportMSBitfieldStoragePacking =
20144 Record && PreviousField &&
20145 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
20146 Loc: Record->getLocation());
20147 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20148 return FD->isBitField() && !FD->getType()->isDependentType();
20149 };
20150
20151 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20152 IsNonDependentBitField(PreviousField)) {
20153 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
20154 CharUnits PreviousFieldStorageSize =
20155 Context.getTypeSizeInChars(T: PreviousField->getType());
20156 if (FDStorageSize != PreviousFieldStorageSize) {
20157 Diag(Loc: FD->getLocation(),
20158 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
20159 << FD << FD->getType() << FDStorageSize.getQuantity()
20160 << PreviousFieldStorageSize.getQuantity();
20161 Diag(Loc: PreviousField->getLocation(),
20162 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
20163 << PreviousField << PreviousField->getType();
20164 }
20165 }
20166 // Keep track of the number of named members.
20167 if (FD->getIdentifier())
20168 ++NumNamedMembers;
20169 }
20170
20171 // Okay, we successfully defined 'Record'.
20172 if (Record) {
20173 bool Completed = false;
20174 if (S) {
20175 Scope *Parent = S->getParent();
20176 if (Parent && Parent->isTypeAliasScope() &&
20177 Parent->isTemplateParamScope())
20178 Record->setInvalidDecl();
20179 }
20180
20181 if (CXXRecord) {
20182 if (!CXXRecord->isInvalidDecl()) {
20183 // Set access bits correctly on the directly-declared conversions.
20184 for (CXXRecordDecl::conversion_iterator
20185 I = CXXRecord->conversion_begin(),
20186 E = CXXRecord->conversion_end(); I != E; ++I)
20187 I.setAccess((*I)->getAccess());
20188 }
20189
20190 // Add any implicitly-declared members to this class.
20191 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
20192
20193 if (!CXXRecord->isDependentType()) {
20194 if (!CXXRecord->isInvalidDecl()) {
20195 // If we have virtual base classes, we may end up finding multiple
20196 // final overriders for a given virtual function. Check for this
20197 // problem now.
20198 if (CXXRecord->getNumVBases()) {
20199 CXXFinalOverriderMap FinalOverriders;
20200 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
20201
20202 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20203 MEnd = FinalOverriders.end();
20204 M != MEnd; ++M) {
20205 for (OverridingMethods::iterator SO = M->second.begin(),
20206 SOEnd = M->second.end();
20207 SO != SOEnd; ++SO) {
20208 assert(SO->second.size() > 0 &&
20209 "Virtual function without overriding functions?");
20210 if (SO->second.size() == 1)
20211 continue;
20212
20213 // C++ [class.virtual]p2:
20214 // In a derived class, if a virtual member function of a base
20215 // class subobject has more than one final overrider the
20216 // program is ill-formed.
20217 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
20218 << (const NamedDecl *)M->first << Record;
20219 Diag(Loc: M->first->getLocation(),
20220 DiagID: diag::note_overridden_virtual_function);
20221 for (OverridingMethods::overriding_iterator
20222 OM = SO->second.begin(),
20223 OMEnd = SO->second.end();
20224 OM != OMEnd; ++OM)
20225 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
20226 << (const NamedDecl *)M->first << OM->Method->getParent();
20227
20228 Record->setInvalidDecl();
20229 }
20230 }
20231 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
20232 Completed = true;
20233 }
20234 }
20235 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
20236 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
20237 }
20238 }
20239
20240 if (!Completed)
20241 Record->completeDefinition();
20242
20243 // Handle attributes before checking the layout.
20244 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
20245
20246 // Maybe randomize the record's decls. We automatically randomize a record
20247 // of function pointers, unless it has the "no_randomize_layout" attribute.
20248 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20249 !Record->isRandomized() && !Record->isUnion() &&
20250 (Record->hasAttr<RandomizeLayoutAttr>() ||
20251 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20252 EntirelyFunctionPointers(Record)))) {
20253 SmallVector<Decl *, 32> NewDeclOrdering;
20254 if (randstruct::randomizeStructureLayout(Context, RD: Record,
20255 FinalOrdering&: NewDeclOrdering))
20256 Record->reorderDecls(Decls: NewDeclOrdering);
20257 }
20258
20259 // We may have deferred checking for a deleted destructor. Check now.
20260 if (CXXRecord) {
20261 auto *Dtor = CXXRecord->getDestructor();
20262 if (Dtor && Dtor->isImplicit() &&
20263 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
20264 CXXRecord->setImplicitDestructorIsDeleted();
20265 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
20266 }
20267 }
20268
20269 if (Record->hasAttrs()) {
20270 CheckAlignasUnderalignment(D: Record);
20271
20272 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20273 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
20274 Range: IA->getRange(), BestCase: IA->getBestCase(),
20275 SemanticSpelling: IA->getInheritanceModel());
20276 }
20277
20278 // Check if the structure/union declaration is a type that can have zero
20279 // size in C. For C this is a language extension, for C++ it may cause
20280 // compatibility problems.
20281 bool CheckForZeroSize;
20282 if (!getLangOpts().CPlusPlus) {
20283 CheckForZeroSize = true;
20284 } else {
20285 // For C++ filter out types that cannot be referenced in C code.
20286 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
20287 CheckForZeroSize =
20288 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20289 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20290 CXXRecord->isCLike();
20291 }
20292 if (CheckForZeroSize) {
20293 bool ZeroSize = true;
20294 bool IsEmpty = true;
20295 unsigned NonBitFields = 0;
20296 for (RecordDecl::field_iterator I = Record->field_begin(),
20297 E = Record->field_end();
20298 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20299 IsEmpty = false;
20300 if (I->isUnnamedBitField()) {
20301 if (!I->isZeroLengthBitField())
20302 ZeroSize = false;
20303 } else {
20304 ++NonBitFields;
20305 QualType FieldType = I->getType();
20306 if (FieldType->isIncompleteType() ||
20307 !Context.getTypeSizeInChars(T: FieldType).isZero())
20308 ZeroSize = false;
20309 }
20310 }
20311
20312 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20313 // allowed in C++, but warn if its declaration is inside
20314 // extern "C" block.
20315 if (ZeroSize) {
20316 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
20317 diag::warn_zero_size_struct_union_in_extern_c :
20318 diag::warn_zero_size_struct_union_compat)
20319 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20320 }
20321
20322 // Structs without named members are extension in C (C99 6.7.2.1p7),
20323 // but are accepted by GCC. In C2y, this became implementation-defined
20324 // (C2y 6.7.3.2p10).
20325 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20326 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
20327 : diag::ext_no_named_members_in_struct_union)
20328 << Record->isUnion();
20329 }
20330 }
20331 } else {
20332 ObjCIvarDecl **ClsFields =
20333 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20334 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
20335 ID->setEndOfDefinitionLoc(RBrac);
20336 // Add ivar's to class's DeclContext.
20337 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20338 ClsFields[i]->setLexicalDeclContext(ID);
20339 ID->addDecl(D: ClsFields[i]);
20340 }
20341 // Must enforce the rule that ivars in the base classes may not be
20342 // duplicates.
20343 if (ID->getSuperClass())
20344 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
20345 } else if (ObjCImplementationDecl *IMPDecl =
20346 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
20347 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20348 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20349 // Ivar declared in @implementation never belongs to the implementation.
20350 // Only it is in implementation's lexical context.
20351 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20352 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
20353 Loc: RBrac);
20354 IMPDecl->setIvarLBraceLoc(LBrac);
20355 IMPDecl->setIvarRBraceLoc(RBrac);
20356 } else if (ObjCCategoryDecl *CDecl =
20357 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
20358 // case of ivars in class extension; all other cases have been
20359 // reported as errors elsewhere.
20360 // FIXME. Class extension does not have a LocEnd field.
20361 // CDecl->setLocEnd(RBrac);
20362 // Add ivar's to class extension's DeclContext.
20363 // Diagnose redeclaration of private ivars.
20364 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20365 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20366 if (IDecl) {
20367 if (const ObjCIvarDecl *ClsIvar =
20368 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20369 Diag(Loc: ClsFields[i]->getLocation(),
20370 DiagID: diag::err_duplicate_ivar_declaration);
20371 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
20372 continue;
20373 }
20374 for (const auto *Ext : IDecl->known_extensions()) {
20375 if (const ObjCIvarDecl *ClsExtIvar
20376 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20377 Diag(Loc: ClsFields[i]->getLocation(),
20378 DiagID: diag::err_duplicate_ivar_declaration);
20379 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
20380 continue;
20381 }
20382 }
20383 }
20384 ClsFields[i]->setLexicalDeclContext(CDecl);
20385 CDecl->addDecl(D: ClsFields[i]);
20386 }
20387 CDecl->setIvarLBraceLoc(LBrac);
20388 CDecl->setIvarRBraceLoc(RBrac);
20389 }
20390 }
20391 if (Record && !isa<ClassTemplateSpecializationDecl>(Val: Record))
20392 ProcessAPINotes(D: Record);
20393}
20394
20395// Given an integral type, return the next larger integral type
20396// (or a NULL type of no such type exists).
20397static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20398 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20399 // enum checking below.
20400 assert((T->isIntegralType(Context) ||
20401 T->isEnumeralType()) && "Integral type required!");
20402 const unsigned NumTypes = 4;
20403 QualType SignedIntegralTypes[NumTypes] = {
20404 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20405 };
20406 QualType UnsignedIntegralTypes[NumTypes] = {
20407 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20408 Context.UnsignedLongLongTy
20409 };
20410
20411 unsigned BitWidth = Context.getTypeSize(T);
20412 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20413 : UnsignedIntegralTypes;
20414 for (unsigned I = 0; I != NumTypes; ++I)
20415 if (Context.getTypeSize(T: Types[I]) > BitWidth)
20416 return Types[I];
20417
20418 return QualType();
20419}
20420
20421EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20422 EnumConstantDecl *LastEnumConst,
20423 SourceLocation IdLoc,
20424 IdentifierInfo *Id,
20425 Expr *Val) {
20426 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20427 llvm::APSInt EnumVal(IntWidth);
20428 QualType EltTy;
20429
20430 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
20431 Val = nullptr;
20432
20433 if (Val)
20434 Val = DefaultLvalueConversion(E: Val).get();
20435
20436 if (Val) {
20437 if (Enum->isDependentType() || Val->isTypeDependent() ||
20438 Val->containsErrors())
20439 EltTy = Context.DependentTy;
20440 else {
20441 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20442 // underlying type, but do allow it in all other contexts.
20443 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20444 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20445 // constant-expression in the enumerator-definition shall be a converted
20446 // constant expression of the underlying type.
20447 EltTy = Enum->getIntegerType();
20448 ExprResult Converted = CheckConvertedConstantExpression(
20449 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
20450 if (Converted.isInvalid())
20451 Val = nullptr;
20452 else
20453 Val = Converted.get();
20454 } else if (!Val->isValueDependent() &&
20455 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
20456 CanFold: AllowFoldKind::Allow)
20457 .get())) {
20458 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20459 } else {
20460 if (Enum->isComplete()) {
20461 EltTy = Enum->getIntegerType();
20462
20463 // In Obj-C and Microsoft mode, require the enumeration value to be
20464 // representable in the underlying type of the enumeration. In C++11,
20465 // we perform a non-narrowing conversion as part of converted constant
20466 // expression checking.
20467 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20468 if (Context.getTargetInfo()
20469 .getTriple()
20470 .isWindowsMSVCEnvironment()) {
20471 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
20472 } else {
20473 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
20474 }
20475 }
20476
20477 // Cast to the underlying type.
20478 Val = ImpCastExprToType(E: Val, Type: EltTy,
20479 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
20480 : CK_IntegralCast)
20481 .get();
20482 } else if (getLangOpts().CPlusPlus) {
20483 // C++11 [dcl.enum]p5:
20484 // If the underlying type is not fixed, the type of each enumerator
20485 // is the type of its initializing value:
20486 // - If an initializer is specified for an enumerator, the
20487 // initializing value has the same type as the expression.
20488 EltTy = Val->getType();
20489 } else {
20490 // C99 6.7.2.2p2:
20491 // The expression that defines the value of an enumeration constant
20492 // shall be an integer constant expression that has a value
20493 // representable as an int.
20494
20495 // Complain if the value is not representable in an int.
20496 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20497 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20498 ? diag::warn_c17_compat_enum_value_not_int
20499 : diag::ext_c23_enum_value_not_int)
20500 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20501 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20502 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20503 // Force the type of the expression to 'int'.
20504 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20505 }
20506 EltTy = Val->getType();
20507 }
20508 }
20509 }
20510 }
20511
20512 if (!Val) {
20513 if (Enum->isDependentType())
20514 EltTy = Context.DependentTy;
20515 else if (!LastEnumConst) {
20516 // C++0x [dcl.enum]p5:
20517 // If the underlying type is not fixed, the type of each enumerator
20518 // is the type of its initializing value:
20519 // - If no initializer is specified for the first enumerator, the
20520 // initializing value has an unspecified integral type.
20521 //
20522 // GCC uses 'int' for its unspecified integral type, as does
20523 // C99 6.7.2.2p3.
20524 if (Enum->isFixed()) {
20525 EltTy = Enum->getIntegerType();
20526 }
20527 else {
20528 EltTy = Context.IntTy;
20529 }
20530 } else {
20531 // Assign the last value + 1.
20532 EnumVal = LastEnumConst->getInitVal();
20533 ++EnumVal;
20534 EltTy = LastEnumConst->getType();
20535
20536 // Check for overflow on increment.
20537 if (EnumVal < LastEnumConst->getInitVal()) {
20538 // C++0x [dcl.enum]p5:
20539 // If the underlying type is not fixed, the type of each enumerator
20540 // is the type of its initializing value:
20541 //
20542 // - Otherwise the type of the initializing value is the same as
20543 // the type of the initializing value of the preceding enumerator
20544 // unless the incremented value is not representable in that type,
20545 // in which case the type is an unspecified integral type
20546 // sufficient to contain the incremented value. If no such type
20547 // exists, the program is ill-formed.
20548 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20549 if (T.isNull() || Enum->isFixed()) {
20550 // There is no integral type larger enough to represent this
20551 // value. Complain, then allow the value to wrap around.
20552 EnumVal = LastEnumConst->getInitVal();
20553 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20554 ++EnumVal;
20555 if (Enum->isFixed())
20556 // When the underlying type is fixed, this is ill-formed.
20557 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20558 << toString(I: EnumVal, Radix: 10)
20559 << EltTy;
20560 else
20561 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20562 << toString(I: EnumVal, Radix: 10);
20563 } else {
20564 EltTy = T;
20565 }
20566
20567 // Retrieve the last enumerator's value, extent that type to the
20568 // type that is supposed to be large enough to represent the incremented
20569 // value, then increment.
20570 EnumVal = LastEnumConst->getInitVal();
20571 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20572 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20573 ++EnumVal;
20574
20575 // If we're not in C++, diagnose the overflow of enumerator values,
20576 // which in C99 means that the enumerator value is not representable in
20577 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20578 // are representable in some larger integral type and we allow it in
20579 // older language modes as an extension.
20580 // Exclude fixed enumerators since they are diagnosed with an error for
20581 // this case.
20582 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20583 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20584 ? diag::warn_c17_compat_enum_value_not_int
20585 : diag::ext_c23_enum_value_not_int)
20586 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20587 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20588 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20589 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20590 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20591 : diag::ext_c23_enum_value_not_int)
20592 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20593 }
20594 }
20595 }
20596
20597 if (!EltTy->isDependentType()) {
20598 // Make the enumerator value match the signedness and size of the
20599 // enumerator's type.
20600 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20601 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20602 }
20603
20604 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20605 E: Val, V: EnumVal);
20606}
20607
20608SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20609 SourceLocation IILoc) {
20610 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20611 !getLangOpts().CPlusPlus)
20612 return SkipBodyInfo();
20613
20614 // We have an anonymous enum definition. Look up the first enumerator to
20615 // determine if we should merge the definition with an existing one and
20616 // skip the body.
20617 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20618 Redecl: forRedeclarationInCurContext());
20619 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20620 if (!PrevECD)
20621 return SkipBodyInfo();
20622
20623 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20624 NamedDecl *Hidden;
20625 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20626 SkipBodyInfo Skip;
20627 Skip.Previous = Hidden;
20628 return Skip;
20629 }
20630
20631 return SkipBodyInfo();
20632}
20633
20634Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20635 SourceLocation IdLoc, IdentifierInfo *Id,
20636 const ParsedAttributesView &Attrs,
20637 SourceLocation EqualLoc, Expr *Val,
20638 SkipBodyInfo *SkipBody) {
20639 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20640 EnumConstantDecl *LastEnumConst =
20641 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20642
20643 // The scope passed in may not be a decl scope. Zip up the scope tree until
20644 // we find one that is.
20645 S = getNonFieldDeclScope(S);
20646
20647 // Verify that there isn't already something declared with this name in this
20648 // scope.
20649 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20650 RedeclarationKind::ForVisibleRedeclaration);
20651 LookupName(R, S);
20652 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20653
20654 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20655 // Maybe we will complain about the shadowed template parameter.
20656 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20657 // Just pretend that we didn't see the previous declaration.
20658 PrevDecl = nullptr;
20659 }
20660
20661 // C++ [class.mem]p15:
20662 // If T is the name of a class, then each of the following shall have a name
20663 // different from T:
20664 // - every enumerator of every member of class T that is an unscoped
20665 // enumerated type
20666 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20667 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20668 NameInfo: DeclarationNameInfo(Id, IdLoc)))
20669 return nullptr;
20670
20671 EnumConstantDecl *New =
20672 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20673 if (!New)
20674 return nullptr;
20675
20676 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20677 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20678 // Check for other kinds of shadowing not already handled.
20679 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
20680 }
20681
20682 // When in C++, we may get a TagDecl with the same name; in this case the
20683 // enum constant will 'hide' the tag.
20684 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20685 "Received TagDecl when not in C++!");
20686 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20687 if (isa<EnumConstantDecl>(Val: PrevDecl))
20688 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
20689 else
20690 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
20691 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20692 return nullptr;
20693 }
20694 }
20695
20696 // Process attributes.
20697 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
20698 AddPragmaAttributes(S, D: New);
20699 ProcessAPINotes(D: New);
20700
20701 // Register this decl in the current scope stack.
20702 New->setAccess(TheEnumDecl->getAccess());
20703 PushOnScopeChains(D: New, S);
20704
20705 ActOnDocumentableDecl(D: New);
20706
20707 return New;
20708}
20709
20710// Returns true when the enum initial expression does not trigger the
20711// duplicate enum warning. A few common cases are exempted as follows:
20712// Element2 = Element1
20713// Element2 = Element1 + 1
20714// Element2 = Element1 - 1
20715// Where Element2 and Element1 are from the same enum.
20716static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20717 Expr *InitExpr = ECD->getInitExpr();
20718 if (!InitExpr)
20719 return true;
20720 InitExpr = InitExpr->IgnoreImpCasts();
20721
20722 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20723 if (!BO->isAdditiveOp())
20724 return true;
20725 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20726 if (!IL)
20727 return true;
20728 if (IL->getValue() != 1)
20729 return true;
20730
20731 InitExpr = BO->getLHS();
20732 }
20733
20734 // This checks if the elements are from the same enum.
20735 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20736 if (!DRE)
20737 return true;
20738
20739 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20740 if (!EnumConstant)
20741 return true;
20742
20743 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20744 Enum)
20745 return true;
20746
20747 return false;
20748}
20749
20750// Emits a warning when an element is implicitly set a value that
20751// a previous element has already been set to.
20752static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20753 EnumDecl *Enum, QualType EnumType) {
20754 // Avoid anonymous enums
20755 if (!Enum->getIdentifier())
20756 return;
20757
20758 // Only check for small enums.
20759 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20760 return;
20761
20762 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
20763 return;
20764
20765 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20766 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20767
20768 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20769
20770 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20771 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20772
20773 // Use int64_t as a key to avoid needing special handling for map keys.
20774 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20775 llvm::APSInt Val = D->getInitVal();
20776 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20777 };
20778
20779 DuplicatesVector DupVector;
20780 ValueToVectorMap EnumMap;
20781
20782 // Populate the EnumMap with all values represented by enum constants without
20783 // an initializer.
20784 for (auto *Element : Elements) {
20785 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
20786
20787 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20788 // this constant. Skip this enum since it may be ill-formed.
20789 if (!ECD) {
20790 return;
20791 }
20792
20793 // Constants with initializers are handled in the next loop.
20794 if (ECD->getInitExpr())
20795 continue;
20796
20797 // Duplicate values are handled in the next loop.
20798 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
20799 }
20800
20801 if (EnumMap.size() == 0)
20802 return;
20803
20804 // Create vectors for any values that has duplicates.
20805 for (auto *Element : Elements) {
20806 // The last loop returned if any constant was null.
20807 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
20808 if (!ValidDuplicateEnum(ECD, Enum))
20809 continue;
20810
20811 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
20812 if (Iter == EnumMap.end())
20813 continue;
20814
20815 DeclOrVector& Entry = Iter->second;
20816 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
20817 // Ensure constants are different.
20818 if (D == ECD)
20819 continue;
20820
20821 // Create new vector and push values onto it.
20822 auto Vec = std::make_unique<ECDVector>();
20823 Vec->push_back(Elt: D);
20824 Vec->push_back(Elt: ECD);
20825
20826 // Update entry to point to the duplicates vector.
20827 Entry = Vec.get();
20828
20829 // Store the vector somewhere we can consult later for quick emission of
20830 // diagnostics.
20831 DupVector.emplace_back(Args: std::move(Vec));
20832 continue;
20833 }
20834
20835 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
20836 // Make sure constants are not added more than once.
20837 if (*Vec->begin() == ECD)
20838 continue;
20839
20840 Vec->push_back(Elt: ECD);
20841 }
20842
20843 // Emit diagnostics.
20844 for (const auto &Vec : DupVector) {
20845 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20846
20847 // Emit warning for one enum constant.
20848 auto *FirstECD = Vec->front();
20849 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
20850 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
20851 << FirstECD->getSourceRange();
20852
20853 // Emit one note for each of the remaining enum constants with
20854 // the same value.
20855 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
20856 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
20857 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
20858 << ECD->getSourceRange();
20859 }
20860}
20861
20862bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20863 bool AllowMask) const {
20864 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20865 assert(ED->isCompleteDefinition() && "expected enum definition");
20866
20867 auto R = FlagBitsCache.try_emplace(Key: ED);
20868 llvm::APInt &FlagBits = R.first->second;
20869
20870 if (R.second) {
20871 for (auto *E : ED->enumerators()) {
20872 const auto &EVal = E->getInitVal();
20873 // Only single-bit enumerators introduce new flag values.
20874 if (EVal.isPowerOf2())
20875 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
20876 }
20877 }
20878
20879 // A value is in a flag enum if either its bits are a subset of the enum's
20880 // flag bits (the first condition) or we are allowing masks and the same is
20881 // true of its complement (the second condition). When masks are allowed, we
20882 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20883 //
20884 // While it's true that any value could be used as a mask, the assumption is
20885 // that a mask will have all of the insignificant bits set. Anything else is
20886 // likely a logic error.
20887 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
20888 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20889}
20890
20891// Emits a warning when a suspicious comparison operator is used along side
20892// binary operators in enum initializers.
20893static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
20894 const EnumDecl *Enum) {
20895 bool HasBitwiseOp = false;
20896 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20897
20898 // Iterate over all the enum values, gather suspisious comparison ops and
20899 // whether any enum initialisers contain a binary operator.
20900 for (const auto *ECD : Enum->enumerators()) {
20901 const Expr *InitExpr = ECD->getInitExpr();
20902 if (!InitExpr)
20903 continue;
20904
20905 const Expr *E = InitExpr->IgnoreParenImpCasts();
20906
20907 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
20908 BinaryOperatorKind Op = BinOp->getOpcode();
20909
20910 // Check for bitwise ops (<<, >>, &, |)
20911 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20912 HasBitwiseOp = true;
20913 } else if (Op == BO_LT || Op == BO_GT) {
20914 // Check for the typo pattern (Comparison < or >)
20915 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20916 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHS)) {
20917 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20918 if (IntLiteral->getValue() == 1)
20919 SuspiciousCompares.push_back(Elt: BinOp);
20920 }
20921 }
20922 }
20923 }
20924
20925 // If we found a bitwise op and some sus compares, iterate over the compares
20926 // and warn.
20927 if (HasBitwiseOp) {
20928 for (const auto *BinOp : SuspiciousCompares) {
20929 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20930 ? BinaryOperator::getOpcodeStr(Op: BO_Shl)
20931 : BinaryOperator::getOpcodeStr(Op: BO_Shr);
20932 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20933
20934 Sema.Diag(Loc: OperatorLoc, DiagID: diag::warn_comparison_in_enum_initializer)
20935 << BinOp->getOpcodeStr() << SuggestedOp;
20936
20937 Sema.Diag(Loc: OperatorLoc, DiagID: diag::note_enum_compare_typo_suggest)
20938 << SuggestedOp
20939 << FixItHint::CreateReplacement(RemoveRange: OperatorLoc, Code: SuggestedOp);
20940 }
20941 }
20942}
20943
20944void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20945 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20946 const ParsedAttributesView &Attrs) {
20947 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
20948 CanQualType EnumType = Context.getCanonicalTagType(TD: Enum);
20949
20950 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
20951 ProcessAPINotes(D: Enum);
20952
20953 if (Enum->isDependentType()) {
20954 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20955 EnumConstantDecl *ECD =
20956 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20957 if (!ECD) continue;
20958
20959 ECD->setType(EnumType);
20960 }
20961
20962 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
20963 return;
20964 }
20965
20966 // Verify that all the values are okay, compute the size of the values, and
20967 // reverse the list.
20968 unsigned NumNegativeBits = 0;
20969 unsigned NumPositiveBits = 0;
20970 bool MembersRepresentableByInt =
20971 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
20972
20973 // Figure out the type that should be used for this enum.
20974 QualType BestType;
20975 unsigned BestWidth;
20976
20977 // C++0x N3000 [conv.prom]p3:
20978 // An rvalue of an unscoped enumeration type whose underlying
20979 // type is not fixed can be converted to an rvalue of the first
20980 // of the following types that can represent all the values of
20981 // the enumeration: int, unsigned int, long int, unsigned long
20982 // int, long long int, or unsigned long long int.
20983 // C99 6.4.4.3p2:
20984 // An identifier declared as an enumeration constant has type int.
20985 // The C99 rule is modified by C23.
20986 QualType BestPromotionType;
20987
20988 bool Packed = Enum->hasAttr<PackedAttr>();
20989 // -fshort-enums is the equivalent to specifying the packed attribute on all
20990 // enum definitions.
20991 if (LangOpts.ShortEnums)
20992 Packed = true;
20993
20994 // If the enum already has a type because it is fixed or dictated by the
20995 // target, promote that type instead of analyzing the enumerators.
20996 if (Enum->isComplete()) {
20997 BestType = Enum->getIntegerType();
20998 if (Context.isPromotableIntegerType(T: BestType))
20999 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
21000 else
21001 BestPromotionType = BestType;
21002
21003 BestWidth = Context.getIntWidth(T: BestType);
21004 } else {
21005 bool EnumTooLarge = Context.computeBestEnumTypes(
21006 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21007 BestWidth = Context.getIntWidth(T: BestType);
21008 if (EnumTooLarge)
21009 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
21010 }
21011
21012 // Loop over all of the enumerator constants, changing their types to match
21013 // the type of the enum if needed.
21014 for (auto *D : Elements) {
21015 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21016 if (!ECD) continue; // Already issued a diagnostic.
21017
21018 // C99 says the enumerators have int type, but we allow, as an
21019 // extension, the enumerators to be larger than int size. If each
21020 // enumerator value fits in an int, type it as an int, otherwise type it the
21021 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21022 // that X has type 'int', not 'unsigned'.
21023
21024 // Determine whether the value fits into an int.
21025 llvm::APSInt InitVal = ECD->getInitVal();
21026
21027 // If it fits into an integer type, force it. Otherwise force it to match
21028 // the enum decl type.
21029 QualType NewTy;
21030 unsigned NewWidth;
21031 bool NewSign;
21032 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21033 MembersRepresentableByInt) {
21034 // C23 6.7.3.3.3p15:
21035 // The enumeration member type for an enumerated type without fixed
21036 // underlying type upon completion is:
21037 // - int if all the values of the enumeration are representable as an
21038 // int; or,
21039 // - the enumerated type
21040 NewTy = Context.IntTy;
21041 NewWidth = Context.getTargetInfo().getIntWidth();
21042 NewSign = true;
21043 } else if (ECD->getType() == BestType) {
21044 // Already the right type!
21045 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21046 // C++ [dcl.enum]p4: Following the closing brace of an
21047 // enum-specifier, each enumerator has the type of its
21048 // enumeration.
21049 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21050 // with fixed underlying type is the enumerated type.
21051 ECD->setType(EnumType);
21052 continue;
21053 } else {
21054 NewTy = BestType;
21055 NewWidth = BestWidth;
21056 NewSign = BestType->isSignedIntegerOrEnumerationType();
21057 }
21058
21059 // Adjust the APSInt value.
21060 InitVal = InitVal.extOrTrunc(width: NewWidth);
21061 InitVal.setIsSigned(NewSign);
21062 ECD->setInitVal(C: Context, V: InitVal);
21063
21064 // Adjust the Expr initializer and type.
21065 if (ECD->getInitExpr() &&
21066 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
21067 ECD->setInitExpr(ImplicitCastExpr::Create(
21068 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
21069 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
21070 if (getLangOpts().CPlusPlus ||
21071 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21072 // C++ [dcl.enum]p4: Following the closing brace of an
21073 // enum-specifier, each enumerator has the type of its
21074 // enumeration.
21075 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21076 // with fixed underlying type is the enumerated type.
21077 ECD->setType(EnumType);
21078 else
21079 ECD->setType(NewTy);
21080 }
21081
21082 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
21083 NumPositiveBits, NumNegativeBits);
21084
21085 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
21086 CheckForComparisonInEnumInitializer(Sema&: *this, Enum);
21087
21088 if (Enum->isClosedFlag()) {
21089 for (Decl *D : Elements) {
21090 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21091 if (!ECD) continue; // Already issued a diagnostic.
21092
21093 llvm::APSInt InitVal = ECD->getInitVal();
21094 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21095 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
21096 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
21097 << ECD << Enum;
21098 }
21099 }
21100
21101 // Now that the enum type is defined, ensure it's not been underaligned.
21102 if (Enum->hasAttrs())
21103 CheckAlignasUnderalignment(D: Enum);
21104}
21105
21106Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
21107 SourceLocation EndLoc) {
21108
21109 FileScopeAsmDecl *New =
21110 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
21111 CurContext->addDecl(D: New);
21112 return New;
21113}
21114
21115TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
21116 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
21117 CurContext->addDecl(D: New);
21118 PushDeclContext(S, DC: New);
21119 PushFunctionScope();
21120 PushCompoundScope(IsStmtExpr: false);
21121 return New;
21122}
21123
21124void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
21125 if (Statement)
21126 D->setStmt(Statement);
21127 PopCompoundScope();
21128 PopFunctionScopeInfo();
21129 PopDeclContext();
21130}
21131
21132void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
21133 IdentifierInfo* AliasName,
21134 SourceLocation PragmaLoc,
21135 SourceLocation NameLoc,
21136 SourceLocation AliasNameLoc) {
21137 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
21138 NameKind: LookupOrdinaryName);
21139 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21140 AttributeCommonInfo::Form::Pragma());
21141 AsmLabelAttr *Attr =
21142 AsmLabelAttr::CreateImplicit(Ctx&: Context, Label: AliasName->getName(), CommonInfo: Info);
21143
21144 // If a declaration that:
21145 // 1) declares a function or a variable
21146 // 2) has external linkage
21147 // already exists, add a label attribute to it.
21148 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21149 if (isDeclExternC(D: PrevDecl))
21150 PrevDecl->addAttr(A: Attr);
21151 else
21152 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
21153 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
21154 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21155 } else
21156 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
21157}
21158
21159void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
21160 SourceLocation PragmaLoc,
21161 SourceLocation NameLoc) {
21162 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
21163
21164 if (PrevDecl) {
21165 PrevDecl->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc));
21166 } else {
21167 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
21168 }
21169}
21170
21171void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
21172 IdentifierInfo* AliasName,
21173 SourceLocation PragmaLoc,
21174 SourceLocation NameLoc,
21175 SourceLocation AliasNameLoc) {
21176 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
21177 NameKind: LookupOrdinaryName);
21178 WeakInfo W = WeakInfo(Name, NameLoc);
21179
21180 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21181 if (!PrevDecl->hasAttr<AliasAttr>())
21182 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
21183 DeclApplyPragmaWeak(S: TUScope, ND, W);
21184 } else {
21185 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
21186 }
21187}
21188
21189Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21190 bool Final) {
21191 assert(FD && "Expected non-null FunctionDecl");
21192
21193 // Templates are emitted when they're instantiated.
21194 if (FD->isDependentContext())
21195 return FunctionEmissionStatus::TemplateDiscarded;
21196
21197 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21198 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21199 FD->hasAttr<SYCLExternalAttr>()))
21200 return FunctionEmissionStatus::Emitted;
21201
21202 // Check whether this function is an externally visible definition.
21203 auto IsEmittedForExternalSymbol = [this, FD]() {
21204 // We have to check the GVA linkage of the function's *definition* -- if we
21205 // only have a declaration, we don't know whether or not the function will
21206 // be emitted, because (say) the definition could include "inline".
21207 const FunctionDecl *Def = FD->getDefinition();
21208
21209 // We can't compute linkage when we skip function bodies.
21210 return Def && !Def->hasSkippedBody() &&
21211 !isDiscardableGVALinkage(
21212 L: getASTContext().GetGVALinkageForFunction(FD: Def));
21213 };
21214
21215 if (LangOpts.OpenMPIsTargetDevice) {
21216 // In OpenMP device mode we will not emit host only functions, or functions
21217 // we don't need due to their linkage.
21218 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21219 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21220 // DevTy may be changed later by
21221 // #pragma omp declare target to(*) device_type(*).
21222 // Therefore DevTy having no value does not imply host. The emission status
21223 // will be checked again at the end of compilation unit with Final = true.
21224 if (DevTy)
21225 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21226 return FunctionEmissionStatus::OMPDiscarded;
21227 // If we have an explicit value for the device type, or we are in a target
21228 // declare context, we need to emit all extern and used symbols.
21229 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21230 if (IsEmittedForExternalSymbol())
21231 return FunctionEmissionStatus::Emitted;
21232 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21233 // we'll omit it.
21234 if (Final)
21235 return FunctionEmissionStatus::OMPDiscarded;
21236 } else if (LangOpts.OpenMP > 45) {
21237 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21238 // function. In 5.0, no_host was introduced which might cause a function to
21239 // be omitted.
21240 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21241 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21242 if (DevTy)
21243 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21244 return FunctionEmissionStatus::OMPDiscarded;
21245 }
21246
21247 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21248 return FunctionEmissionStatus::Emitted;
21249
21250 if (LangOpts.CUDA) {
21251 // When compiling for device, host functions are never emitted. Similarly,
21252 // when compiling for host, device and global functions are never emitted.
21253 // (Technically, we do emit a host-side stub for global functions, but this
21254 // doesn't count for our purposes here.)
21255 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
21256 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21257 return FunctionEmissionStatus::CUDADiscarded;
21258 if (!LangOpts.CUDAIsDevice &&
21259 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21260 return FunctionEmissionStatus::CUDADiscarded;
21261
21262 if (IsEmittedForExternalSymbol())
21263 return FunctionEmissionStatus::Emitted;
21264
21265 // If FD is a virtual destructor of an explicit instantiation
21266 // of a template class, return Emitted.
21267 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: FD)) {
21268 if (Destructor->isVirtual()) {
21269 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
21270 Val: Destructor->getParent())) {
21271 TemplateSpecializationKind TSK =
21272 Spec->getTemplateSpecializationKind();
21273 if (TSK == TSK_ExplicitInstantiationDeclaration ||
21274 TSK == TSK_ExplicitInstantiationDefinition)
21275 return FunctionEmissionStatus::Emitted;
21276 }
21277 }
21278 }
21279 }
21280
21281 // Otherwise, the function is known-emitted if it's in our set of
21282 // known-emitted functions.
21283 return FunctionEmissionStatus::Unknown;
21284}
21285
21286bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21287 // Host-side references to a __global__ function refer to the stub, so the
21288 // function itself is never emitted and therefore should not be marked.
21289 // If we have host fn calls kernel fn calls host+device, the HD function
21290 // does not get instantiated on the host. We model this by omitting at the
21291 // call to the kernel from the callgraph. This ensures that, when compiling
21292 // for host, only HD functions actually called from the host get marked as
21293 // known-emitted.
21294 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21295 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
21296}
21297
21298bool Sema::isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
21299 bool &Visible) {
21300 Visible = hasVisibleDefinition(D, Suggested);
21301 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21302 // for declaratins which is attached to named modules.
21303 // We only did this if the current module is named module as we have better
21304 // diagnostics for declarations in global module and named modules.
21305 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21306 D->isInNamedModule())
21307 return false;
21308 // The redefinition of D in the **current** TU is allowed if D is invisible or
21309 // D is defined in the global module of other module units.
21310 return D->isInAnotherModuleUnit() || !Visible;
21311}
21312