1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/MangleNumberingContext.h"
28#include "clang/AST/NonTrivialTypeVisitor.h"
29#include "clang/AST/Randstruct.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/DiagnosticComment.h"
34#include "clang/Basic/HLSLRuntime.h"
35#include "clang/Basic/PartialDiagnostic.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
40#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
41#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42#include "clang/Sema/CXXFieldCollector.h"
43#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/DelayedDiagnostic.h"
45#include "clang/Sema/Initialization.h"
46#include "clang/Sema/Lookup.h"
47#include "clang/Sema/ParsedTemplate.h"
48#include "clang/Sema/Scope.h"
49#include "clang/Sema/ScopeInfo.h"
50#include "clang/Sema/SemaAMDGPU.h"
51#include "clang/Sema/SemaARM.h"
52#include "clang/Sema/SemaCUDA.h"
53#include "clang/Sema/SemaHLSL.h"
54#include "clang/Sema/SemaInternal.h"
55#include "clang/Sema/SemaObjC.h"
56#include "clang/Sema/SemaOpenACC.h"
57#include "clang/Sema/SemaOpenMP.h"
58#include "clang/Sema/SemaPPC.h"
59#include "clang/Sema/SemaRISCV.h"
60#include "clang/Sema/SemaSYCL.h"
61#include "clang/Sema/SemaSwift.h"
62#include "clang/Sema/SemaWasm.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/STLForwardCompat.h"
66#include "llvm/ADT/ScopeExit.h"
67#include "llvm/ADT/SmallPtrSet.h"
68#include "llvm/ADT/SmallString.h"
69#include "llvm/ADT/StringExtras.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/Support/SaveAndRestore.h"
72#include "llvm/TargetParser/Triple.h"
73#include <algorithm>
74#include <cstring>
75#include <optional>
76#include <unordered_map>
77
78using namespace clang;
79using namespace sema;
80
81Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
82 if (OwnedType) {
83 Decl *Group[2] = { OwnedType, Ptr };
84 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
85 }
86
87 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
88}
89
90namespace {
91
92class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
93 public:
94 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
95 bool AllowTemplates = false,
96 bool AllowNonTemplates = true)
97 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
98 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
99 WantExpressionKeywords = false;
100 WantCXXNamedCasts = false;
101 WantRemainingKeywords = false;
102 }
103
104 bool ValidateCandidate(const TypoCorrection &candidate) override {
105 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
106 if (!AllowInvalidDecl && ND->isInvalidDecl())
107 return false;
108
109 if (getAsTypeTemplateDecl(D: ND))
110 return AllowTemplates;
111
112 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
113 if (!IsType)
114 return false;
115
116 if (AllowNonTemplates)
117 return true;
118
119 // An injected-class-name of a class template (specialization) is valid
120 // as a template or as a non-template.
121 if (AllowTemplates) {
122 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
123 if (!RD || !RD->isInjectedClassName())
124 return false;
125 RD = cast<CXXRecordDecl>(Val: RD->getDeclContext());
126 return RD->getDescribedClassTemplate() ||
127 isa<ClassTemplateSpecializationDecl>(Val: RD);
128 }
129
130 return false;
131 }
132
133 return !WantClassName && candidate.isKeyword();
134 }
135
136 std::unique_ptr<CorrectionCandidateCallback> clone() override {
137 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
138 }
139
140 private:
141 bool AllowInvalidDecl;
142 bool WantClassName;
143 bool AllowTemplates;
144 bool AllowNonTemplates;
145};
146
147} // end anonymous namespace
148
149void Sema::checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
150 TypeDecl *TD, SourceLocation NameLoc) {
151 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
152 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
153 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
154 FoundRD->isInjectedClassName() &&
155 declaresSameEntity(D1: LookupRD, D2: cast<Decl>(Val: FoundRD->getParent()))) {
156 Diag(Loc: NameLoc,
157 DiagID: DCK == DiagCtorKind::Typename
158 ? diag::ext_out_of_line_qualified_id_type_names_constructor
159 : diag::err_out_of_line_qualified_id_type_names_constructor)
160 << TD->getIdentifier() << /*Type=*/1
161 << 0 /*if any keyword was present, it was 'typename'*/;
162 }
163
164 DiagnoseUseOfDecl(D: TD, Locs: NameLoc);
165 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
181lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
191 if (BaseRD) {
192 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
193 Val: Base.getType().getCanonicalType())) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
206 if (const ClassTemplatePartialSpecializationDecl *PS =
207 CTD->findPartialSpecialization(T: Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(Name: &II)) {
215 if (!isa<TypeDecl>(Val: ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
236static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(Val: DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
257 // allowed. We'll fully resolve the lookup during template instantiation.
258 S.Diag(Loc: NameLoc, DiagID: diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD).getTypePtr());
262 QualType T =
263 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
271 DepTL.setElaboratedKeywordLoc(SourceLocation());
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
274}
275
276ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
277 Scope *S, CXXScopeSpec *SS, bool isClassName,
278 bool HasTrailingDot, ParsedType ObjectTypePtr,
279 bool IsCtorOrDtorName,
280 bool WantNontrivialTypeSourceInfo,
281 bool IsClassTemplateDeductionContext,
282 ImplicitTypenameContext AllowImplicitTypename,
283 IdentifierInfo **CorrectedII) {
284 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
285 // FIXME: Consider allowing this outside C++1z mode as an extension.
286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
288 !HasTrailingDot;
289
290 // Determine where we will perform name lookup.
291 DeclContext *LookupCtx = nullptr;
292 if (ObjectTypePtr) {
293 QualType ObjectType = ObjectTypePtr.get();
294 if (ObjectType->isRecordType())
295 LookupCtx = computeDeclContext(T: ObjectType);
296 } else if (SS && SS->isNotEmpty()) {
297 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
298
299 if (!LookupCtx) {
300 if (isDependentScopeSpecifier(SS: *SS)) {
301 // C++ [temp.res]p3:
302 // A qualified-id that refers to a type and in which the
303 // nested-name-specifier depends on a template-parameter (14.6.2)
304 // shall be prefixed by the keyword typename to indicate that the
305 // qualified-id denotes a type, forming an
306 // elaborated-type-specifier (7.1.5.3).
307 //
308 // We therefore do not perform any name lookup if the result would
309 // refer to a member of an unknown specialization.
310 // In C++2a, in several contexts a 'typename' is not required. Also
311 // allow this as an extension.
312 if (IsImplicitTypename) {
313 if (AllowImplicitTypename == ImplicitTypenameContext::No)
314 return nullptr;
315 SourceLocation QualifiedLoc = SS->getRange().getBegin();
316 // FIXME: Defer the diagnostic after we build the type and use it.
317 auto DB = DiagCompat(Loc: QualifiedLoc, CompatDiagId: diag_compat::implicit_typename)
318 << Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
319 NNS: SS->getScopeRep(), Name: &II);
320 if (!getLangOpts().CPlusPlus20)
321 DB << FixItHint::CreateInsertion(InsertionLoc: QualifiedLoc, Code: "typename ");
322 }
323
324 // We know from the grammar that this name refers to a type,
325 // so build a dependent node to describe the type.
326 if (WantNontrivialTypeSourceInfo)
327 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
328 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
329 .get();
330
331 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
332 QualType T = CheckTypenameType(
333 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
334 : ElaboratedTypeKeyword::None,
335 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
336 return ParsedType::make(P: T);
337 }
338
339 return nullptr;
340 }
341
342 if (!LookupCtx->isDependentContext() &&
343 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
344 return nullptr;
345 }
346
347 // In the case where we know that the identifier is a class name, we know that
348 // it is a type declaration (struct, class, union or enum) so we can use tag
349 // name lookup.
350 //
351 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
352 // the component name of the type-name or simple-template-id is type-only.
353 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
354 LookupResult Result(*this, &II, NameLoc, Kind);
355 if (LookupCtx) {
356 // Perform "qualified" name lookup into the declaration context we
357 // computed, which is either the type of the base of a member access
358 // expression or the declaration context associated with a prior
359 // nested-name-specifier.
360 LookupQualifiedName(R&: Result, LookupCtx);
361
362 if (ObjectTypePtr && Result.empty()) {
363 // C++ [basic.lookup.classref]p3:
364 // If the unqualified-id is ~type-name, the type-name is looked up
365 // in the context of the entire postfix-expression. If the type T of
366 // the object expression is of a class type C, the type-name is also
367 // looked up in the scope of class C. At least one of the lookups shall
368 // find a name that refers to (possibly cv-qualified) T.
369 LookupName(R&: Result, S);
370 }
371 } else {
372 // Perform unqualified name lookup.
373 LookupName(R&: Result, S);
374
375 // For unqualified lookup in a class template in MSVC mode, look into
376 // dependent base classes where the primary class template is known.
377 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
378 if (ParsedType TypeInBase =
379 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
380 return TypeInBase;
381 }
382 }
383
384 NamedDecl *IIDecl = nullptr;
385 UsingShadowDecl *FoundUsingShadow = nullptr;
386 switch (Result.getResultKind()) {
387 case LookupResultKind::NotFound:
388 if (CorrectedII) {
389 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
390 AllowDeducedTemplate);
391 TypoCorrection Correction =
392 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind, S, SS, CCC,
393 Mode: CorrectTypoKind::ErrorRecovery);
394 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
395 TemplateTy Template;
396 bool MemberOfUnknownSpecialization;
397 UnqualifiedId TemplateName;
398 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
399 NestedNameSpecifier NNS = Correction.getCorrectionSpecifier();
400 CXXScopeSpec NewSS, *NewSSPtr = SS;
401 if (SS && NNS) {
402 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
403 NewSSPtr = &NewSS;
404 }
405 if (Correction && (NNS || NewII != &II) &&
406 // Ignore a correction to a template type as the to-be-corrected
407 // identifier is not a template (typo correction for template names
408 // is handled elsewhere).
409 !(getLangOpts().CPlusPlus && NewSSPtr &&
410 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
411 Template, MemberOfUnknownSpecialization))) {
412 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
413 isClassName, HasTrailingDot, ObjectTypePtr,
414 IsCtorOrDtorName,
415 WantNontrivialTypeSourceInfo,
416 IsClassTemplateDeductionContext);
417 if (Ty) {
418 diagnoseTypo(Correction,
419 TypoDiag: PDiag(DiagID: diag::err_unknown_type_or_class_name_suggest)
420 << Result.getLookupName() << isClassName);
421 if (SS && NNS)
422 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
423 *CorrectedII = NewII;
424 return Ty;
425 }
426 }
427 }
428 Result.suppressDiagnostics();
429 return nullptr;
430 case LookupResultKind::NotFoundInCurrentInstantiation:
431 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
432 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
433 NNS: SS->getScopeRep(), Name: &II);
434 TypeLocBuilder TLB;
435 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
436 TL.setElaboratedKeywordLoc(SourceLocation());
437 TL.setQualifierLoc(SS->getWithLocInContext(Context));
438 TL.setNameLoc(NameLoc);
439 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
440 }
441 [[fallthrough]];
442 case LookupResultKind::FoundOverloaded:
443 case LookupResultKind::FoundUnresolvedValue:
444 Result.suppressDiagnostics();
445 return nullptr;
446
447 case LookupResultKind::Ambiguous:
448 // Recover from type-hiding ambiguities by hiding the type. We'll
449 // do the lookup again when looking for an object, and we can
450 // diagnose the error then. If we don't do this, then the error
451 // about hiding the type will be immediately followed by an error
452 // that only makes sense if the identifier was treated like a type.
453 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
454 Result.suppressDiagnostics();
455 return nullptr;
456 }
457
458 // Look to see if we have a type anywhere in the list of results.
459 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
460 Res != ResEnd; ++Res) {
461 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
462 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
463 Val: RealRes) ||
464 (AllowDeducedTemplate && getAsTypeTemplateDecl(D: RealRes))) {
465 if (!IIDecl ||
466 // Make the selection of the recovery decl deterministic.
467 RealRes->getLocation() < IIDecl->getLocation()) {
468 IIDecl = RealRes;
469 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
470 }
471 }
472 }
473
474 if (!IIDecl) {
475 // None of the entities we found is a type, so there is no way
476 // to even assume that the result is a type. In this case, don't
477 // complain about the ambiguity. The parser will either try to
478 // perform this lookup again (e.g., as an object name), which
479 // will produce the ambiguity, or will complain that it expected
480 // a type name.
481 Result.suppressDiagnostics();
482 return nullptr;
483 }
484
485 // We found a type within the ambiguous lookup; diagnose the
486 // ambiguity and then return that type. This might be the right
487 // answer, or it might not be, but it suppresses any attempt to
488 // perform the name lookup again.
489 break;
490
491 case LookupResultKind::Found:
492 IIDecl = Result.getFoundDecl();
493 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
494 break;
495 }
496
497 assert(IIDecl && "Didn't find decl");
498
499 TypeLocBuilder TLB;
500 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
501 checkTypeDeclType(LookupCtx,
502 DCK: IsImplicitTypename ? DiagCtorKind::Implicit
503 : DiagCtorKind::None,
504 TD, NameLoc);
505 QualType T;
506 if (FoundUsingShadow) {
507 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None,
508 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
509 D: FoundUsingShadow);
510 if (!WantNontrivialTypeSourceInfo)
511 return ParsedType::make(P: T);
512 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
513 QualifierLoc: SS ? SS->getWithLocInContext(Context)
514 : NestedNameSpecifierLoc(),
515 NameLoc);
516 } else if (auto *Tag = dyn_cast<TagDecl>(Val: TD)) {
517 T = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
518 Qualifier: SS ? SS->getScopeRep() : std::nullopt, TD: Tag,
519 /*OwnsTag=*/false);
520 if (!WantNontrivialTypeSourceInfo)
521 return ParsedType::make(P: T);
522 auto TL = TLB.push<TagTypeLoc>(T);
523 TL.setElaboratedKeywordLoc(SourceLocation());
524 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
525 : NestedNameSpecifierLoc());
526 TL.setNameLoc(NameLoc);
527 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD);
528 TN && !isa<ObjCTypeParamDecl>(Val: TN)) {
529 T = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
530 Qualifier: SS ? SS->getScopeRep() : std::nullopt, Decl: TN);
531 if (!WantNontrivialTypeSourceInfo)
532 return ParsedType::make(P: T);
533 TLB.push<TypedefTypeLoc>(T).set(
534 /*ElaboratedKeywordLoc=*/SourceLocation(),
535 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
536 NameLoc);
537 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD)) {
538 T = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
539 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
540 D: UD);
541 if (!WantNontrivialTypeSourceInfo)
542 return ParsedType::make(P: T);
543 TLB.push<UnresolvedUsingTypeLoc>(T).set(
544 /*ElaboratedKeywordLoc=*/SourceLocation(),
545 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
546 NameLoc);
547 } else {
548 T = Context.getTypeDeclType(Decl: TD);
549 if (!WantNontrivialTypeSourceInfo)
550 return ParsedType::make(P: T);
551 if (isa<ObjCTypeParamType>(Val: T))
552 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
553 else
554 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
555 }
556 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
557 }
558
559 if (getLangOpts().HLSL) {
560 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
561 Val: getAsTemplateNameDecl(D: IIDecl, /*AllowFunctionTemplates=*/false,
562 /*AllowDependent=*/false))) {
563 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(Template: TD, NameLoc);
564 if (!ShorthandTy.isNull())
565 return ParsedType::make(P: ShorthandTy);
566 }
567 }
568
569 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
570 (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc);
571 if (!HasTrailingDot) {
572 // FIXME: Support UsingType for this case.
573 QualType T = Context.getObjCInterfaceType(Decl: IDecl);
574 if (!WantNontrivialTypeSourceInfo)
575 return ParsedType::make(P: T);
576 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
577 TL.setNameLoc(NameLoc);
578 // FIXME: Pass in this source location.
579 TL.setNameEndLoc(NameLoc);
580 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
581 }
582 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
583 (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc);
584 // Recover with 'int'
585 return ParsedType::make(P: Context.IntTy);
586 } else if (AllowDeducedTemplate) {
587 if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) {
588 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
589 // FIXME: Support UsingType here.
590 TemplateName Template = Context.getQualifiedTemplateName(
591 Qualifier: SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
592 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
593 QualType T = Context.getDeducedTemplateSpecializationType(
594 DK: DeducedKind::Undeduced, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None,
595 Template);
596 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
597 TL.setElaboratedKeywordLoc(SourceLocation());
598 TL.setNameLoc(NameLoc);
599 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
600 : NestedNameSpecifierLoc());
601 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
602 }
603 }
604
605 // As it's not plausibly a type, suppress diagnostics.
606 Result.suppressDiagnostics();
607 return nullptr;
608}
609
610// Builds a fake NNS for the given decl context.
611static NestedNameSpecifier
612synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
613 for (;; DC = DC->getLookupParent()) {
614 DC = DC->getPrimaryContext();
615 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
616 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
617 return NestedNameSpecifier(Context, ND, std::nullopt);
618 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
619 return NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
620 if (isa<TranslationUnitDecl>(Val: DC))
621 return NestedNameSpecifier::getGlobal();
622 }
623 llvm_unreachable("something isn't in TU scope?");
624}
625
626/// Find the parent class with dependent bases of the innermost enclosing method
627/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
628/// up allowing unqualified dependent type names at class-level, which MSVC
629/// correctly rejects.
630static const CXXRecordDecl *
631findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
632 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
633 DC = DC->getPrimaryContext();
634 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
635 if (MD->getParent()->hasAnyDependentBases())
636 return MD->getParent();
637 }
638 return nullptr;
639}
640
641ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
642 SourceLocation NameLoc,
643 bool IsTemplateTypeArg) {
644 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
645
646 NestedNameSpecifier NNS = std::nullopt;
647 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
648 // If we weren't able to parse a default template argument, delay lookup
649 // until instantiation time by making a non-dependent DependentTypeName. We
650 // pretend we saw a NestedNameSpecifier referring to the current scope, and
651 // lookup is retried.
652 // FIXME: This hurts our diagnostic quality, since we get errors like "no
653 // type named 'Foo' in 'current_namespace'" when the user didn't write any
654 // name specifiers.
655 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
656 Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II;
657 } else if (const CXXRecordDecl *RD =
658 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
659 // Build a DependentNameType that will perform lookup into RD at
660 // instantiation time.
661 NNS = NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
662
663 // Diagnose that this identifier was undeclared, and retry the lookup during
664 // template instantiation.
665 Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II
666 << RD;
667 } else {
668 // This is not a situation that we should recover from.
669 return ParsedType();
670 }
671
672 QualType T =
673 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
674
675 // Build type location information. We synthesized the qualifier, so we have
676 // to build a fake NestedNameSpecifierLoc.
677 NestedNameSpecifierLocBuilder NNSLocBuilder;
678 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
679 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
680
681 TypeLocBuilder Builder;
682 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
683 DepTL.setNameLoc(NameLoc);
684 DepTL.setElaboratedKeywordLoc(SourceLocation());
685 DepTL.setQualifierLoc(QualifierLoc);
686 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
687}
688
689DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
690 // Do a tag name lookup in this scope.
691 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
692 LookupName(R, S, AllowBuiltinCreation: false);
693 R.suppressDiagnostics();
694 if (R.getResultKind() == LookupResultKind::Found)
695 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
696 switch (TD->getTagKind()) {
697 case TagTypeKind::Struct:
698 return DeclSpec::TST_struct;
699 case TagTypeKind::Interface:
700 return DeclSpec::TST_interface;
701 case TagTypeKind::Union:
702 return DeclSpec::TST_union;
703 case TagTypeKind::Class:
704 return DeclSpec::TST_class;
705 case TagTypeKind::Enum:
706 return DeclSpec::TST_enum;
707 }
708 }
709
710 return DeclSpec::TST_unspecified;
711}
712
713bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
714 if (!CurContext->isRecord())
715 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
716
717 switch (SS->getScopeRep().getKind()) {
718 case NestedNameSpecifier::Kind::MicrosoftSuper:
719 return true;
720 case NestedNameSpecifier::Kind::Type: {
721 QualType T(SS->getScopeRep().getAsType(), 0);
722 for (const auto &Base : cast<CXXRecordDecl>(Val: CurContext)->bases())
723 if (Context.hasSameUnqualifiedType(T1: T, T2: Base.getType()))
724 return true;
725 [[fallthrough]];
726 }
727 default:
728 return S->isFunctionPrototypeScope();
729 }
730}
731
732void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
733 SourceLocation IILoc,
734 Scope *S,
735 CXXScopeSpec *SS,
736 ParsedType &SuggestedType,
737 bool IsTemplateName) {
738 // Don't report typename errors for editor placeholders.
739 if (II->isEditorPlaceholder())
740 return;
741 // We don't have anything to suggest (yet).
742 SuggestedType = nullptr;
743
744 // There may have been a typo in the name of the type. Look up typo
745 // results, in case we have something that we can suggest.
746 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
747 /*AllowTemplates=*/IsTemplateName,
748 /*AllowNonTemplates=*/!IsTemplateName);
749 if (TypoCorrection Corrected =
750 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
751 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
752 // FIXME: Support error recovery for the template-name case.
753 bool CanRecover = !IsTemplateName;
754 if (Corrected.isKeyword()) {
755 // We corrected to a keyword.
756 diagnoseTypo(Correction: Corrected,
757 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
758 : diag::err_unknown_typename_suggest)
759 << II);
760 II = Corrected.getCorrectionAsIdentifierInfo();
761 } else {
762 // We found a similarly-named type or interface; suggest that.
763 if (!SS || !SS->isSet()) {
764 diagnoseTypo(Correction: Corrected,
765 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
766 : diag::err_unknown_typename_suggest)
767 << II, ErrorRecovery: CanRecover);
768 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
769 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
770 bool DroppedSpecifier =
771 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
772 diagnoseTypo(Correction: Corrected,
773 TypoDiag: PDiag(DiagID: IsTemplateName
774 ? diag::err_no_member_template_suggest
775 : diag::err_unknown_nested_typename_suggest)
776 << II << DC << DroppedSpecifier << SS->getRange(),
777 ErrorRecovery: CanRecover);
778 } else {
779 llvm_unreachable("could not have corrected a typo here");
780 }
781
782 if (!CanRecover)
783 return;
784
785 CXXScopeSpec tmpSS;
786 if (Corrected.getCorrectionSpecifier())
787 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
788 R: SourceRange(IILoc));
789 // FIXME: Support class template argument deduction here.
790 SuggestedType =
791 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
792 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
793 /*IsCtorOrDtorName=*/false,
794 /*WantNontrivialTypeSourceInfo=*/true);
795 }
796 return;
797 }
798
799 if (getLangOpts().CPlusPlus && !IsTemplateName) {
800 // See if II is a class template that the user forgot to pass arguments to.
801 UnqualifiedId Name;
802 Name.setIdentifier(Id: II, IdLoc: IILoc);
803 CXXScopeSpec EmptySS;
804 TemplateTy TemplateResult;
805 bool MemberOfUnknownSpecialization;
806 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
807 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
808 MemberOfUnknownSpecialization) == TNK_Type_template) {
809 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
810 return;
811 }
812 }
813
814 // FIXME: Should we move the logic that tries to recover from a missing tag
815 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
816
817 if (!SS || (!SS->isSet() && !SS->isInvalid()))
818 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template
819 : diag::err_unknown_typename)
820 << II;
821 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
822 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template
823 : diag::err_typename_nested_not_found)
824 << II << DC << SS->getRange();
825 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
826 SuggestedType =
827 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
828 } else if (isDependentScopeSpecifier(SS: *SS)) {
829 unsigned DiagID = diag::err_typename_missing;
830 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
831 DiagID = diag::ext_typename_missing;
832
833 SuggestedType =
834 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
835
836 Diag(Loc: SS->getRange().getBegin(), DiagID)
837 << GetTypeFromParser(Ty: SuggestedType)
838 << SourceRange(SS->getRange().getBegin(), IILoc)
839 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
840 } else {
841 assert(SS && SS->isInvalid() &&
842 "Invalid scope specifier has already been diagnosed");
843 }
844}
845
846/// Determine whether the given result set contains either a type name
847/// or
848static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
849 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
850 NextToken.is(K: tok::less);
851
852 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
853 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
854 return true;
855
856 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
857 return true;
858 }
859
860 return false;
861}
862
863static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
864 Scope *S, CXXScopeSpec &SS,
865 IdentifierInfo *&Name,
866 SourceLocation NameLoc) {
867 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
868 SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
869 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
870 StringRef FixItTagName;
871 switch (Tag->getTagKind()) {
872 case TagTypeKind::Class:
873 FixItTagName = "class ";
874 break;
875
876 case TagTypeKind::Enum:
877 FixItTagName = "enum ";
878 break;
879
880 case TagTypeKind::Struct:
881 FixItTagName = "struct ";
882 break;
883
884 case TagTypeKind::Interface:
885 FixItTagName = "__interface ";
886 break;
887
888 case TagTypeKind::Union:
889 FixItTagName = "union ";
890 break;
891 }
892
893 StringRef TagName = FixItTagName.drop_back();
894 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag)
895 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
896 << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName);
897
898 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
899 I != IEnd; ++I)
900 SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type)
901 << Name << TagName;
902
903 // Replace lookup results with just the tag decl.
904 Result.clear(Kind: Sema::LookupTagName);
905 SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType());
906 return true;
907 }
908
909 return false;
910}
911
912Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
913 IdentifierInfo *&Name,
914 SourceLocation NameLoc,
915 const Token &NextToken,
916 CorrectionCandidateCallback *CCC) {
917 DeclarationNameInfo NameInfo(Name, NameLoc);
918 ObjCMethodDecl *CurMethod = getCurMethodDecl();
919
920 assert(NextToken.isNot(tok::coloncolon) &&
921 "parse nested name specifiers before calling ClassifyName");
922 if (getLangOpts().CPlusPlus && SS.isSet() &&
923 isCurrentClassName(II: *Name, S, SS: &SS)) {
924 // Per [class.qual]p2, this names the constructors of SS, not the
925 // injected-class-name. We don't have a classification for that.
926 // There's not much point caching this result, since the parser
927 // will reject it later.
928 return NameClassification::Unknown();
929 }
930
931 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
932 LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(),
933 /*AllowBuiltinCreation=*/!CurMethod);
934
935 if (SS.isInvalid())
936 return NameClassification::Error();
937
938 // For unqualified lookup in a class template in MSVC mode, look into
939 // dependent base classes where the primary class template is known.
940 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
941 if (ParsedType TypeInBase =
942 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
943 return TypeInBase;
944 }
945
946 // Perform lookup for Objective-C instance variables (including automatically
947 // synthesized instance variables), if we're in an Objective-C method.
948 // FIXME: This lookup really, really needs to be folded in to the normal
949 // unqualified lookup mechanism.
950 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
951 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
952 if (Ivar.isInvalid())
953 return NameClassification::Error();
954 if (Ivar.isUsable())
955 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
956
957 // We defer builtin creation until after ivar lookup inside ObjC methods.
958 if (Result.empty())
959 LookupBuiltin(R&: Result);
960 }
961
962 bool SecondTry = false;
963 bool IsFilteredTemplateName = false;
964
965Corrected:
966 switch (Result.getResultKind()) {
967 case LookupResultKind::NotFound:
968 // If an unqualified-id is followed by a '(', then we have a function
969 // call.
970 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
971 // In C++, this is an ADL-only call.
972 // FIXME: Reference?
973 if (getLangOpts().CPlusPlus)
974 return NameClassification::UndeclaredNonType();
975
976 // C90 6.3.2.2:
977 // If the expression that precedes the parenthesized argument list in a
978 // function call consists solely of an identifier, and if no
979 // declaration is visible for this identifier, the identifier is
980 // implicitly declared exactly as if, in the innermost block containing
981 // the function call, the declaration
982 //
983 // extern int identifier ();
984 //
985 // appeared.
986 //
987 // We also allow this in C99 as an extension. However, this is not
988 // allowed in all language modes as functions without prototypes may not
989 // be supported.
990 if (getLangOpts().implicitFunctionsAllowed()) {
991 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
992 return NameClassification::NonType(D);
993 }
994 }
995
996 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
997 // In C++20 onwards, this could be an ADL-only call to a function
998 // template, and we're required to assume that this is a template name.
999 //
1000 // FIXME: Find a way to still do typo correction in this case.
1001 TemplateName Template =
1002 Context.getAssumedTemplateName(Name: NameInfo.getName());
1003 return NameClassification::UndeclaredTemplate(Name: Template);
1004 }
1005
1006 // In C, we first see whether there is a tag type by the same name, in
1007 // which case it's likely that the user just forgot to write "enum",
1008 // "struct", or "union".
1009 if (!getLangOpts().CPlusPlus && !SecondTry &&
1010 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1011 break;
1012 }
1013
1014 // Perform typo correction to determine if there is another name that is
1015 // close to this name.
1016 if (!SecondTry && CCC) {
1017 SecondTry = true;
1018 if (TypoCorrection Corrected =
1019 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
1020 SS: &SS, CCC&: *CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
1021 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1022 unsigned QualifiedDiag = diag::err_no_member_suggest;
1023
1024 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1025 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1026 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1027 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
1028 UnqualifiedDiag = diag::err_no_template_suggest;
1029 QualifiedDiag = diag::err_no_member_template_suggest;
1030 } else if (UnderlyingFirstDecl &&
1031 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
1032 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
1033 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
1034 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1035 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1036 }
1037
1038 if (SS.isEmpty()) {
1039 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1040 } else {// FIXME: is this even reachable? Test it.
1041 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1042 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1043 Name->getName() == CorrectedStr;
1044 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1045 << Name << computeDeclContext(SS, EnteringContext: false)
1046 << DroppedSpecifier << SS.getRange());
1047 }
1048
1049 // Update the name, so that the caller has the new name.
1050 Name = Corrected.getCorrectionAsIdentifierInfo();
1051
1052 // Typo correction corrected to a keyword.
1053 if (Corrected.isKeyword())
1054 return Name;
1055
1056 // Also update the LookupResult...
1057 // FIXME: This should probably go away at some point
1058 Result.clear();
1059 Result.setLookupName(Corrected.getCorrection());
1060 if (FirstDecl)
1061 Result.addDecl(D: FirstDecl);
1062
1063 // If we found an Objective-C instance variable, let
1064 // LookupInObjCMethod build the appropriate expression to
1065 // reference the ivar.
1066 // FIXME: This is a gross hack.
1067 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1068 DeclResult R =
1069 ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1070 if (R.isInvalid())
1071 return NameClassification::Error();
1072 if (R.isUsable())
1073 return NameClassification::NonType(D: Ivar);
1074 }
1075
1076 goto Corrected;
1077 }
1078 }
1079
1080 // We failed to correct; just fall through and let the parser deal with it.
1081 Result.suppressDiagnostics();
1082 return NameClassification::Unknown();
1083
1084 case LookupResultKind::NotFoundInCurrentInstantiation: {
1085 // We performed name lookup into the current instantiation, and there were
1086 // dependent bases, so we treat this result the same way as any other
1087 // dependent nested-name-specifier.
1088
1089 // C++ [temp.res]p2:
1090 // A name used in a template declaration or definition and that is
1091 // dependent on a template-parameter is assumed not to name a type
1092 // unless the applicable name lookup finds a type name or the name is
1093 // qualified by the keyword typename.
1094 //
1095 // FIXME: If the next token is '<', we might want to ask the parser to
1096 // perform some heroics to see if we actually have a
1097 // template-argument-list, which would indicate a missing 'template'
1098 // keyword here.
1099 return NameClassification::DependentNonType();
1100 }
1101
1102 case LookupResultKind::Found:
1103 case LookupResultKind::FoundOverloaded:
1104 case LookupResultKind::FoundUnresolvedValue:
1105 break;
1106
1107 case LookupResultKind::Ambiguous:
1108 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1109 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false)) {
1111 // C++ [temp.local]p3:
1112 // A lookup that finds an injected-class-name (10.2) can result in an
1113 // ambiguity in certain cases (for example, if it is found in more than
1114 // one base class). If all of the injected-class-names that are found
1115 // refer to specializations of the same class template, and if the name
1116 // is followed by a template-argument-list, the reference refers to the
1117 // class template itself and not a specialization thereof, and is not
1118 // ambiguous.
1119 //
1120 // This filtering can make an ambiguous result into an unambiguous one,
1121 // so try again after filtering out template names.
1122 FilterAcceptableTemplateNames(R&: Result);
1123 if (!Result.isAmbiguous()) {
1124 IsFilteredTemplateName = true;
1125 break;
1126 }
1127 }
1128
1129 // Diagnose the ambiguity and return an error.
1130 return NameClassification::Error();
1131 }
1132
1133 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1134 (IsFilteredTemplateName ||
1135 hasAnyAcceptableTemplateNames(
1136 R&: Result, /*AllowFunctionTemplates=*/true,
1137 /*AllowDependent=*/false,
1138 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1139 getLangOpts().CPlusPlus20))) {
1140 // C++ [temp.names]p3:
1141 // After name lookup (3.4) finds that a name is a template-name or that
1142 // an operator-function-id or a literal- operator-id refers to a set of
1143 // overloaded functions any member of which is a function template if
1144 // this is followed by a <, the < is always taken as the delimiter of a
1145 // template-argument-list and never as the less-than operator.
1146 // C++2a [temp.names]p2:
1147 // A name is also considered to refer to a template if it is an
1148 // unqualified-id followed by a < and name lookup finds either one
1149 // or more functions or finds nothing.
1150 if (!IsFilteredTemplateName)
1151 FilterAcceptableTemplateNames(R&: Result);
1152
1153 bool IsFunctionTemplate;
1154 bool IsVarTemplate;
1155 TemplateName Template;
1156 if (Result.end() - Result.begin() > 1) {
1157 IsFunctionTemplate = true;
1158 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1159 End: Result.end());
1160 } else if (!Result.empty()) {
1161 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1162 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1163 /*AllowDependent=*/false));
1164 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1165 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1166
1167 UsingShadowDecl *FoundUsingShadow =
1168 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1169 assert(!FoundUsingShadow ||
1170 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1171 Template = Context.getQualifiedTemplateName(
1172 Qualifier: SS.getScopeRep(),
1173 /*TemplateKeyword=*/false,
1174 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1175 } else {
1176 // All results were non-template functions. This is a function template
1177 // name.
1178 IsFunctionTemplate = true;
1179 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1180 }
1181
1182 if (IsFunctionTemplate) {
1183 // Function templates always go through overload resolution, at which
1184 // point we'll perform the various checks (e.g., accessibility) we need
1185 // to based on which function we selected.
1186 Result.suppressDiagnostics();
1187
1188 return NameClassification::FunctionTemplate(Name: Template);
1189 }
1190
1191 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1192 : NameClassification::TypeTemplate(Name: Template);
1193 }
1194
1195 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1196 QualType T;
1197 TypeLocBuilder TLB;
1198 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found)) {
1199 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1200 D: USD);
1201 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1202 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1203 } else {
1204 T = Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1205 Decl: Type);
1206 if (isa<TagType>(Val: T)) {
1207 auto TTL = TLB.push<TagTypeLoc>(T);
1208 TTL.setElaboratedKeywordLoc(SourceLocation());
1209 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1210 TTL.setNameLoc(NameLoc);
1211 } else if (isa<TypedefType>(Val: T)) {
1212 TLB.push<TypedefTypeLoc>(T).set(
1213 /*ElaboratedKeywordLoc=*/SourceLocation(),
1214 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1215 } else if (isa<UnresolvedUsingType>(Val: T)) {
1216 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1217 /*ElaboratedKeywordLoc=*/SourceLocation(),
1218 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1219 } else {
1220 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1221 }
1222 }
1223 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
1224 };
1225
1226 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1227 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1228 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1229 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1230 return BuildTypeFor(Type, *Result.begin());
1231 }
1232
1233 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1234 if (!Class) {
1235 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1236 if (ObjCCompatibleAliasDecl *Alias =
1237 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1238 Class = Alias->getClassInterface();
1239 }
1240
1241 if (Class) {
1242 DiagnoseUseOfDecl(D: Class, Locs: NameLoc);
1243
1244 if (NextToken.is(K: tok::period)) {
1245 // Interface. <something> is parsed as a property reference expression.
1246 // Just return "unknown" as a fall-through for now.
1247 Result.suppressDiagnostics();
1248 return NameClassification::Unknown();
1249 }
1250
1251 QualType T = Context.getObjCInterfaceType(Decl: Class);
1252 return ParsedType::make(P: T);
1253 }
1254
1255 if (isa<ConceptDecl>(Val: FirstDecl)) {
1256 // We want to preserve the UsingShadowDecl for concepts.
1257 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1258 return NameClassification::Concept(Name: TemplateName(USD));
1259 return NameClassification::Concept(
1260 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1261 }
1262
1263 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1264 (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc);
1265 return NameClassification::Error();
1266 }
1267
1268 // We can have a type template here if we're classifying a template argument.
1269 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1270 !isa<VarTemplateDecl>(Val: FirstDecl))
1271 return NameClassification::TypeTemplate(
1272 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1273
1274 // Check for a tag type hidden by a non-type decl in a few cases where it
1275 // seems likely a type is wanted instead of the non-type that was found.
1276 bool NextIsOp = NextToken.isOneOf(Ks: tok::amp, Ks: tok::star);
1277 if ((NextToken.is(K: tok::identifier) ||
1278 (NextIsOp &&
1279 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1280 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1281 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1282 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1283 return BuildTypeFor(Type, *Result.begin());
1284 }
1285
1286 // If we already know which single declaration is referenced, just annotate
1287 // that declaration directly. Defer resolving even non-overloaded class
1288 // member accesses, as we need to defer certain access checks until we know
1289 // the context.
1290 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1291 if (Result.isSingleResult() && !ADL &&
1292 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1293 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1294
1295 // Otherwise, this is an overload set that we will need to resolve later.
1296 Result.suppressDiagnostics();
1297 return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create(
1298 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1299 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1300 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1301}
1302
1303ExprResult
1304Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1305 SourceLocation NameLoc) {
1306 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1307 CXXScopeSpec SS;
1308 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1309 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1310}
1311
1312ExprResult
1313Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1314 IdentifierInfo *Name,
1315 SourceLocation NameLoc,
1316 bool IsAddressOfOperand) {
1317 DeclarationNameInfo NameInfo(Name, NameLoc);
1318 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1319 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1320 /*TemplateArgs=*/nullptr);
1321}
1322
1323ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1324 NamedDecl *Found,
1325 SourceLocation NameLoc,
1326 const Token &NextToken) {
1327 if (getCurMethodDecl() && SS.isEmpty())
1328 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1329 return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1330
1331 // Reconstruct the lookup result.
1332 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1333 Result.addDecl(D: Found);
1334 Result.resolveKind();
1335
1336 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1337 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1338}
1339
1340ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1341 // For an implicit class member access, transform the result into a member
1342 // access expression if necessary.
1343 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1344 if ((*ULE->decls_begin())->isCXXClassMember()) {
1345 CXXScopeSpec SS;
1346 SS.Adopt(Other: ULE->getQualifierLoc());
1347
1348 // Reconstruct the lookup result.
1349 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1350 LookupOrdinaryName);
1351 Result.setNamingClass(ULE->getNamingClass());
1352 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1353 Result.addDecl(D: *I, AS: I.getAccess());
1354 Result.resolveKind();
1355 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1356 TemplateArgs: nullptr, S);
1357 }
1358
1359 // Otherwise, this is already in the form we needed, and no further checks
1360 // are necessary.
1361 return ULE;
1362}
1363
1364Sema::TemplateNameKindForDiagnostics
1365Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1366 auto *TD = Name.getAsTemplateDecl();
1367 if (!TD)
1368 return TemplateNameKindForDiagnostics::DependentTemplate;
1369 if (isa<ClassTemplateDecl>(Val: TD))
1370 return TemplateNameKindForDiagnostics::ClassTemplate;
1371 if (isa<FunctionTemplateDecl>(Val: TD))
1372 return TemplateNameKindForDiagnostics::FunctionTemplate;
1373 if (isa<VarTemplateDecl>(Val: TD))
1374 return TemplateNameKindForDiagnostics::VarTemplate;
1375 if (isa<TypeAliasTemplateDecl>(Val: TD))
1376 return TemplateNameKindForDiagnostics::AliasTemplate;
1377 if (isa<TemplateTemplateParmDecl>(Val: TD))
1378 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1379 if (isa<ConceptDecl>(Val: TD))
1380 return TemplateNameKindForDiagnostics::Concept;
1381 return TemplateNameKindForDiagnostics::DependentTemplate;
1382}
1383
1384void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1385 assert(DC->getLexicalParent() == CurContext &&
1386 "The next DeclContext should be lexically contained in the current one.");
1387 CurContext = DC;
1388 if (S)
1389 S->setEntity(DC);
1390}
1391
1392void Sema::PopDeclContext() {
1393 assert(CurContext && "DeclContext imbalance!");
1394
1395 CurContext = CurContext->getLexicalParent();
1396 assert(CurContext && "Popped translation unit!");
1397}
1398
1399Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1400 Decl *D) {
1401 // Unlike PushDeclContext, the context to which we return is not necessarily
1402 // the containing DC of TD, because the new context will be some pre-existing
1403 // TagDecl definition instead of a fresh one.
1404 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1405 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1406 assert(CurContext && "skipping definition of undefined tag");
1407 // Start lookups from the parent of the current context; we don't want to look
1408 // into the pre-existing complete definition.
1409 S->setEntity(CurContext->getLookupParent());
1410 return Result;
1411}
1412
1413void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1414 CurContext = static_cast<decltype(CurContext)>(Context);
1415}
1416
1417void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1418 // C++0x [basic.lookup.unqual]p13:
1419 // A name used in the definition of a static data member of class
1420 // X (after the qualified-id of the static member) is looked up as
1421 // if the name was used in a member function of X.
1422 // C++0x [basic.lookup.unqual]p14:
1423 // If a variable member of a namespace is defined outside of the
1424 // scope of its namespace then any name used in the definition of
1425 // the variable member (after the declarator-id) is looked up as
1426 // if the definition of the variable member occurred in its
1427 // namespace.
1428 // Both of these imply that we should push a scope whose context
1429 // is the semantic context of the declaration. We can't use
1430 // PushDeclContext here because that context is not necessarily
1431 // lexically contained in the current context. Fortunately,
1432 // the containing scope should have the appropriate information.
1433
1434 assert(!S->getEntity() && "scope already has entity");
1435
1436#ifndef NDEBUG
1437 Scope *Ancestor = S->getParent();
1438 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1439 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1440#endif
1441
1442 CurContext = DC;
1443 S->setEntity(DC);
1444
1445 if (S->getParent()->isTemplateParamScope()) {
1446 // Also set the corresponding entities for all immediately-enclosing
1447 // template parameter scopes.
1448 EnterTemplatedContext(S: S->getParent(), DC);
1449 }
1450}
1451
1452void Sema::ExitDeclaratorContext(Scope *S) {
1453 assert(S->getEntity() == CurContext && "Context imbalance!");
1454
1455 // Switch back to the lexical context. The safety of this is
1456 // enforced by an assert in EnterDeclaratorContext.
1457 Scope *Ancestor = S->getParent();
1458 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1459 CurContext = Ancestor->getEntity();
1460
1461 // We don't need to do anything with the scope, which is going to
1462 // disappear.
1463}
1464
1465void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1466 assert(S->isTemplateParamScope() &&
1467 "expected to be initializing a template parameter scope");
1468
1469 // C++20 [temp.local]p7:
1470 // In the definition of a member of a class template that appears outside
1471 // of the class template definition, the name of a member of the class
1472 // template hides the name of a template-parameter of any enclosing class
1473 // templates (but not a template-parameter of the member if the member is a
1474 // class or function template).
1475 // C++20 [temp.local]p9:
1476 // In the definition of a class template or in the definition of a member
1477 // of such a template that appears outside of the template definition, for
1478 // each non-dependent base class (13.8.2.1), if the name of the base class
1479 // or the name of a member of the base class is the same as the name of a
1480 // template-parameter, the base class name or member name hides the
1481 // template-parameter name (6.4.10).
1482 //
1483 // This means that a template parameter scope should be searched immediately
1484 // after searching the DeclContext for which it is a template parameter
1485 // scope. For example, for
1486 // template<typename T> template<typename U> template<typename V>
1487 // void N::A<T>::B<U>::f(...)
1488 // we search V then B<U> (and base classes) then U then A<T> (and base
1489 // classes) then T then N then ::.
1490 unsigned ScopeDepth = getTemplateDepth(S);
1491 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1492 DeclContext *SearchDCAfterScope = DC;
1493 for (; DC; DC = DC->getLookupParent()) {
1494 if (const TemplateParameterList *TPL =
1495 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1496 unsigned DCDepth = TPL->getDepth() + 1;
1497 if (DCDepth > ScopeDepth)
1498 continue;
1499 if (ScopeDepth == DCDepth)
1500 SearchDCAfterScope = DC = DC->getLookupParent();
1501 break;
1502 }
1503 }
1504 S->setLookupEntity(SearchDCAfterScope);
1505 }
1506}
1507
1508void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1509 // We assume that the caller has already called
1510 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1511 FunctionDecl *FD = D->getAsFunction();
1512 if (!FD)
1513 return;
1514
1515 // Same implementation as PushDeclContext, but enters the context
1516 // from the lexical parent, rather than the top-level class.
1517 assert(CurContext == FD->getLexicalParent() &&
1518 "The next DeclContext should be lexically contained in the current one.");
1519 CurContext = FD;
1520 S->setEntity(CurContext);
1521
1522 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1523 ParmVarDecl *Param = FD->getParamDecl(i: P);
1524 // If the parameter has an identifier, then add it to the scope
1525 if (Param->getIdentifier()) {
1526 S->AddDecl(D: Param);
1527 IdResolver.AddDecl(D: Param);
1528 }
1529 }
1530}
1531
1532void Sema::ActOnExitFunctionContext() {
1533 // Same implementation as PopDeclContext, but returns to the lexical parent,
1534 // rather than the top-level class.
1535 assert(CurContext && "DeclContext imbalance!");
1536 CurContext = CurContext->getLexicalParent();
1537 assert(CurContext && "Popped translation unit!");
1538}
1539
1540/// Determine whether overloading is allowed for a new function
1541/// declaration considering prior declarations of the same name.
1542///
1543/// This routine determines whether overloading is possible, not
1544/// whether a new declaration actually overloads a previous one.
1545/// It will return true in C++ (where overloads are always permitted)
1546/// or, as a C extension, when either the new declaration or a
1547/// previous one is declared with the 'overloadable' attribute.
1548static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1549 ASTContext &Context,
1550 const FunctionDecl *New) {
1551 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1552 return true;
1553
1554 // Multiversion function declarations are not overloads in the
1555 // usual sense of that term, but lookup will report that an
1556 // overload set was found if more than one multiversion function
1557 // declaration is present for the same name. It is therefore
1558 // inadequate to assume that some prior declaration(s) had
1559 // the overloadable attribute; checking is required. Since one
1560 // declaration is permitted to omit the attribute, it is necessary
1561 // to check at least two; hence the 'any_of' check below. Note that
1562 // the overloadable attribute is implicitly added to declarations
1563 // that were required to have it but did not.
1564 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1565 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1566 return ND->hasAttr<OverloadableAttr>();
1567 });
1568 } else if (Previous.getResultKind() == LookupResultKind::Found)
1569 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1570
1571 return false;
1572}
1573
1574void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1575 // Move up the scope chain until we find the nearest enclosing
1576 // non-transparent context. The declaration will be introduced into this
1577 // scope.
1578 while (S->getEntity() && S->getEntity()->isTransparentContext())
1579 S = S->getParent();
1580
1581 // Add scoped declarations into their context, so that they can be
1582 // found later. Declarations without a context won't be inserted
1583 // into any context.
1584 if (AddToContext)
1585 CurContext->addDecl(D);
1586
1587 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1588 // are function-local declarations.
1589 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1590 if (!S->getFnParent())
1591 return;
1592
1593 // Even inside a function, an out-of-line definition of a type that is
1594 // nested inside a local class must not be pushed into the enclosing
1595 // function scope. For example:
1596 //
1597 // class A { public: class B; };
1598 // class A::B {}; // out-of-line definition inside the function
1599 // B b; // must fail - only A::B is valid
1600 // Wrapper{B{}} // must also fail
1601 //
1602 // Per C++ scoping rules only the qualified form A::B is accessible.
1603 // Without this guard, PushOnScopeChains would add B to the function's
1604 // local scope, making it findable via unqualified lookup, which is
1605 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1606 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1607 // of a local class being defined out-of-line.
1608 if (isa<TagDecl>(Val: D) && isa<CXXRecordDecl>(Val: D->getDeclContext()))
1609 return;
1610 }
1611
1612 // Template instantiations should also not be pushed into scope.
1613 if (isa<FunctionDecl>(Val: D) &&
1614 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1615 return;
1616
1617 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1618 S->AddDecl(D);
1619 return;
1620 }
1621 // If this replaces anything in the current scope,
1622 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1623 IEnd = IdResolver.end();
1624 for (; I != IEnd; ++I) {
1625 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1626 S->RemoveDecl(D: *I);
1627 IdResolver.RemoveDecl(D: *I);
1628
1629 // Should only need to replace one decl.
1630 break;
1631 }
1632 }
1633
1634 S->AddDecl(D);
1635
1636 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1637 // Implicitly-generated labels may end up getting generated in an order that
1638 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1639 // the label at the appropriate place in the identifier chain.
1640 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1641 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1642 if (IDC == CurContext) {
1643 if (!S->isDeclScope(D: *I))
1644 continue;
1645 } else if (IDC->Encloses(DC: CurContext))
1646 break;
1647 }
1648
1649 IdResolver.InsertDeclAfter(Pos: I, D);
1650 } else {
1651 IdResolver.AddDecl(D);
1652 }
1653 warnOnReservedIdentifier(D);
1654}
1655
1656bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1657 bool AllowInlineNamespace) const {
1658 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1659}
1660
1661Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1662 DeclContext *TargetDC = DC->getPrimaryContext();
1663 do {
1664 if (DeclContext *ScopeDC = S->getEntity())
1665 if (ScopeDC->getPrimaryContext() == TargetDC)
1666 return S;
1667 } while ((S = S->getParent()));
1668
1669 return nullptr;
1670}
1671
1672static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1673 DeclContext*,
1674 ASTContext&);
1675
1676void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1677 bool ConsiderLinkage,
1678 bool AllowInlineNamespace) {
1679 LookupResult::Filter F = R.makeFilter();
1680 while (F.hasNext()) {
1681 NamedDecl *D = F.next();
1682
1683 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1684 continue;
1685
1686 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1687 continue;
1688
1689 F.erase();
1690 }
1691
1692 F.done();
1693}
1694
1695static bool isImplicitInstantiation(NamedDecl *D) {
1696 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1697 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1698 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1699 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1700 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1701 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1702
1703 return false;
1704}
1705
1706bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1707 // [module.interface]p7:
1708 // A declaration is attached to a module as follows:
1709 // - If the declaration is a non-dependent friend declaration that nominates a
1710 // function with a declarator-id that is a qualified-id or template-id or that
1711 // nominates a class other than with an elaborated-type-specifier with neither
1712 // a nested-name-specifier nor a simple-template-id, it is attached to the
1713 // module to which the friend is attached ([basic.link]).
1714 if (New->getFriendObjectKind() &&
1715 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1716 New->setLocalOwningModule(Old->getOwningModule());
1717 makeMergedDefinitionVisible(ND: New);
1718 return false;
1719 }
1720
1721 // Although we have questions for the module ownership of implicit
1722 // instantiations, it should be sure that we shouldn't diagnose the
1723 // redeclaration of incorrect module ownership for different implicit
1724 // instantiations in different modules. We will diagnose the redeclaration of
1725 // incorrect module ownership for the template itself.
1726 if (isImplicitInstantiation(D: New) || isImplicitInstantiation(D: Old))
1727 return false;
1728
1729 Module *NewM = New->getOwningModule();
1730 Module *OldM = Old->getOwningModule();
1731
1732 if (NewM && NewM->isPrivateModule())
1733 NewM = NewM->Parent;
1734 if (OldM && OldM->isPrivateModule())
1735 OldM = OldM->Parent;
1736
1737 if (NewM == OldM)
1738 return false;
1739
1740 if (NewM && OldM) {
1741 // A module implementation unit has visibility of the decls in its
1742 // implicitly imported interface.
1743 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1744 return false;
1745
1746 // Partitions are part of the module, but a partition could import another
1747 // module, so verify that the PMIs agree.
1748 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1749 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1750 return false;
1751 }
1752
1753 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1754 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1755 if (NewIsModuleInterface || OldIsModuleInterface) {
1756 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1757 // if a declaration of D [...] appears in the purview of a module, all
1758 // other such declarations shall appear in the purview of the same module
1759 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1760 << New
1761 << NewIsModuleInterface
1762 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1763 << OldIsModuleInterface
1764 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1765 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1766 New->setInvalidDecl();
1767 return true;
1768 }
1769
1770 return false;
1771}
1772
1773bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1774 // [module.interface]p1:
1775 // An export-declaration shall inhabit a namespace scope.
1776 //
1777 // So it is meaningless to talk about redeclaration which is not at namespace
1778 // scope.
1779 if (!New->getLexicalDeclContext()
1780 ->getNonTransparentContext()
1781 ->isFileContext() ||
1782 !Old->getLexicalDeclContext()
1783 ->getNonTransparentContext()
1784 ->isFileContext())
1785 return false;
1786
1787 bool IsNewExported = New->isInExportDeclContext();
1788 bool IsOldExported = Old->isInExportDeclContext();
1789
1790 // It should be irrevelant if both of them are not exported.
1791 if (!IsNewExported && !IsOldExported)
1792 return false;
1793
1794 if (IsOldExported)
1795 return false;
1796
1797 // If the Old declaration are not attached to named modules
1798 // and the New declaration are attached to global module.
1799 // It should be fine to allow the export since it doesn't change
1800 // the linkage of declarations. See
1801 // https://github.com/llvm/llvm-project/issues/98583 for details.
1802 if (!Old->isInNamedModule() && New->getOwningModule() &&
1803 New->getOwningModule()->isImplicitGlobalModule())
1804 return false;
1805
1806 assert(IsNewExported);
1807
1808 auto Lk = Old->getFormalLinkage();
1809 int S = 0;
1810 if (Lk == Linkage::Internal)
1811 S = 1;
1812 else if (Lk == Linkage::Module)
1813 S = 2;
1814 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1815 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1816 return true;
1817}
1818
1819bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1820 if (CheckRedeclarationModuleOwnership(New, Old))
1821 return true;
1822
1823 if (CheckRedeclarationExported(New, Old))
1824 return true;
1825
1826 return false;
1827}
1828
1829bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1830 const NamedDecl *Old) const {
1831 assert(getASTContext().isSameEntity(New, Old) &&
1832 "New and Old are not the same definition, we should diagnostic it "
1833 "immediately instead of checking it.");
1834 assert(const_cast<Sema *>(this)->isReachable(New) &&
1835 const_cast<Sema *>(this)->isReachable(Old) &&
1836 "We shouldn't see unreachable definitions here.");
1837
1838 Module *NewM = New->getOwningModule();
1839 Module *OldM = Old->getOwningModule();
1840
1841 // We only checks for named modules here. The header like modules is skipped.
1842 // FIXME: This is not right if we import the header like modules in the module
1843 // purview.
1844 //
1845 // For example, assuming "header.h" provides definition for `D`.
1846 // ```C++
1847 // //--- M.cppm
1848 // export module M;
1849 // import "header.h"; // or #include "header.h" but import it by clang modules
1850 // actually.
1851 //
1852 // //--- Use.cpp
1853 // import M;
1854 // import "header.h"; // or uses clang modules.
1855 // ```
1856 //
1857 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1858 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1859 // reject it. But the current implementation couldn't detect the case since we
1860 // don't record the information about the importee modules.
1861 //
1862 // But this might not be painful in practice. Since the design of C++20 Named
1863 // Modules suggests us to use headers in global module fragment instead of
1864 // module purview.
1865 if (NewM && NewM->isHeaderLikeModule())
1866 NewM = nullptr;
1867 if (OldM && OldM->isHeaderLikeModule())
1868 OldM = nullptr;
1869
1870 if (!NewM && !OldM)
1871 return true;
1872
1873 // [basic.def.odr]p14.3
1874 // Each such definition shall not be attached to a named module
1875 // ([module.unit]).
1876 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1877 return true;
1878
1879 // Then New and Old lives in the same TU if their share one same module unit.
1880 if (NewM)
1881 NewM = NewM->getTopLevelModule();
1882 if (OldM)
1883 OldM = OldM->getTopLevelModule();
1884 return OldM == NewM;
1885}
1886
1887static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1888 if (D->getDeclContext()->isFileContext())
1889 return false;
1890
1891 return isa<UsingShadowDecl>(Val: D) ||
1892 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1893 isa<UnresolvedUsingValueDecl>(Val: D);
1894}
1895
1896/// Removes using shadow declarations not at class scope from the lookup
1897/// results.
1898static void RemoveUsingDecls(LookupResult &R) {
1899 LookupResult::Filter F = R.makeFilter();
1900 while (F.hasNext())
1901 if (isUsingDeclNotAtClassScope(D: F.next()))
1902 F.erase();
1903
1904 F.done();
1905}
1906
1907/// Check for this common pattern:
1908/// @code
1909/// class S {
1910/// S(const S&); // DO NOT IMPLEMENT
1911/// void operator=(const S&); // DO NOT IMPLEMENT
1912/// };
1913/// @endcode
1914static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1915 // FIXME: Should check for private access too but access is set after we get
1916 // the decl here.
1917 if (D->doesThisDeclarationHaveABody())
1918 return false;
1919
1920 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1921 return CD->isCopyConstructor();
1922 return D->isCopyAssignmentOperator();
1923}
1924
1925bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1926 const DeclContext *DC = D->getDeclContext();
1927 while (!DC->isTranslationUnit()) {
1928 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1929 if (!RD->hasNameForLinkage())
1930 return true;
1931 }
1932 DC = DC->getParent();
1933 }
1934
1935 return !D->isExternallyVisible();
1936}
1937
1938bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1939 assert(D);
1940
1941 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1942 return false;
1943
1944 // Ignore all entities declared within templates, and out-of-line definitions
1945 // of members of class templates.
1946 if (D->getDeclContext()->isDependentContext() ||
1947 D->getLexicalDeclContext()->isDependentContext())
1948 return false;
1949
1950 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1951 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1952 return false;
1953 // A non-out-of-line declaration of a member specialization was implicitly
1954 // instantiated; it's the out-of-line declaration that we're interested in.
1955 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1956 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1957 return false;
1958
1959 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1960 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1961 return false;
1962 } else {
1963 // 'static inline' functions are defined in headers; don't warn.
1964 if (FD->isInlined() && !isMainFileLoc(Loc: FD->getLocation()))
1965 return false;
1966 }
1967
1968 if (FD->doesThisDeclarationHaveABody() &&
1969 Context.DeclMustBeEmitted(D: FD))
1970 return false;
1971 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1972 // Constants and utility variables are defined in headers with internal
1973 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1974 // like "inline".)
1975 if (!isMainFileLoc(Loc: VD->getLocation()))
1976 return false;
1977
1978 if (Context.DeclMustBeEmitted(D: VD))
1979 return false;
1980
1981 if (VD->isStaticDataMember() &&
1982 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1983 return false;
1984 if (VD->isStaticDataMember() &&
1985 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1986 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1987 return false;
1988
1989 if (VD->isInline() && !isMainFileLoc(Loc: VD->getLocation()))
1990 return false;
1991 } else {
1992 return false;
1993 }
1994
1995 // Only warn for unused decls internal to the translation unit.
1996 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1997 // for inline functions defined in the main source file, for instance.
1998 return mightHaveNonExternalLinkage(D);
1999}
2000
2001void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
2002 if (!D)
2003 return;
2004
2005 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2006 const FunctionDecl *First = FD->getFirstDecl();
2007 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2008 return; // First should already be in the vector.
2009 }
2010
2011 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2012 const VarDecl *First = VD->getFirstDecl();
2013 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
2014 return; // First should already be in the vector.
2015 }
2016
2017 if (ShouldWarnIfUnusedFileScopedDecl(D))
2018 UnusedFileScopedDecls.push_back(LocalValue: D);
2019}
2020
2021static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2022 const NamedDecl *D) {
2023 if (D->isInvalidDecl())
2024 return false;
2025
2026 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
2027 // For a decomposition declaration, warn if none of the bindings are
2028 // referenced, instead of if the variable itself is referenced (which
2029 // it is, by the bindings' expressions).
2030 bool IsAllIgnored = true;
2031 for (const auto *BD : DD->bindings()) {
2032 if (BD->isReferenced())
2033 return false;
2034 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2035 BD->hasAttr<UnusedAttr>());
2036 }
2037 if (IsAllIgnored)
2038 return false;
2039 } else if (!D->getDeclName()) {
2040 return false;
2041 } else if (D->isReferenced() || D->isUsed()) {
2042 return false;
2043 }
2044
2045 if (D->isPlaceholderVar(LangOpts))
2046 return false;
2047
2048 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2049 D->hasAttr<CleanupAttr>())
2050 return false;
2051
2052 if (isa<LabelDecl>(Val: D))
2053 return true;
2054
2055 // Except for labels, we only care about unused decls that are local to
2056 // functions.
2057 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2058 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
2059 // For dependent types, the diagnostic is deferred.
2060 WithinFunction =
2061 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2062 if (!WithinFunction)
2063 return false;
2064
2065 if (isa<TypedefNameDecl>(Val: D))
2066 return true;
2067
2068 // White-list anything that isn't a local variable.
2069 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2070 return false;
2071
2072 // Types of valid local variables should be complete, so this should succeed.
2073 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2074
2075 const Expr *Init = VD->getInit();
2076 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2077 Init = Cleanups->getSubExpr();
2078
2079 const auto *Ty = VD->getType().getTypePtr();
2080
2081 // Only look at the outermost level of typedef.
2082 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2083 // Allow anything marked with __attribute__((unused)).
2084 if (TT->getDecl()->hasAttr<UnusedAttr>())
2085 return false;
2086 }
2087
2088 // Warn for reference variables whose initializtion performs lifetime
2089 // extension.
2090 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2091 MTE && MTE->getExtendingDecl()) {
2092 Ty = VD->getType().getNonReferenceType().getTypePtr();
2093 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2094 }
2095
2096 // If we failed to complete the type for some reason, or if the type is
2097 // dependent, don't diagnose the variable.
2098 if (Ty->isIncompleteType() || Ty->isDependentType())
2099 return false;
2100
2101 // Look at the element type to ensure that the warning behaviour is
2102 // consistent for both scalars and arrays.
2103 Ty = Ty->getBaseElementTypeUnsafe();
2104
2105 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2106 if (Tag->hasAttr<UnusedAttr>())
2107 return false;
2108
2109 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2110 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2111 return false;
2112
2113 if (Init) {
2114 const auto *Construct =
2115 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2116 if (Construct && !Construct->isElidable()) {
2117 const CXXConstructorDecl *CD = Construct->getConstructor();
2118 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2119 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2120 return false;
2121 }
2122
2123 // Suppress the warning if we don't know how this is constructed, and
2124 // it could possibly be non-trivial constructor.
2125 if (Init->isTypeDependent()) {
2126 for (const CXXConstructorDecl *Ctor : RD->ctors())
2127 if (!Ctor->isTrivial())
2128 return false;
2129 }
2130
2131 // Suppress the warning if the constructor is unresolved because
2132 // its arguments are dependent.
2133 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2134 return false;
2135 }
2136 }
2137 }
2138
2139 // TODO: __attribute__((unused)) templates?
2140 }
2141
2142 return true;
2143}
2144
2145static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2146 FixItHint &Hint) {
2147 if (isa<LabelDecl>(Val: D)) {
2148 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2149 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2150 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2151 if (AfterColon.isInvalid())
2152 return;
2153 Hint = FixItHint::CreateRemoval(
2154 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2155 }
2156}
2157
2158void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2159 DiagnoseUnusedNestedTypedefs(
2160 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2161}
2162
2163void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2164 DiagReceiverTy DiagReceiver) {
2165 if (D->isDependentType())
2166 return;
2167
2168 for (auto *TmpD : D->decls()) {
2169 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2170 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2171 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2172 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2173 }
2174}
2175
2176void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2177 DiagnoseUnusedDecl(
2178 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2179}
2180
2181void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2182 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2183 return;
2184
2185 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2186 // typedefs can be referenced later on, so the diagnostics are emitted
2187 // at end-of-translation-unit.
2188 UnusedLocalTypedefNameCandidates.insert(Ptr: TD);
2189 return;
2190 }
2191
2192 FixItHint Hint;
2193 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2194
2195 unsigned DiagID;
2196 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2197 DiagID = diag::warn_unused_exception_param;
2198 else if (isa<LabelDecl>(Val: D))
2199 DiagID = diag::warn_unused_label;
2200 else
2201 DiagID = diag::warn_unused_variable;
2202
2203 SourceLocation DiagLoc = D->getLocation();
2204 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2205}
2206
2207void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2208 DiagReceiverTy DiagReceiver) {
2209 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2210 // it's not really unused.
2211 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2212 return;
2213
2214 // In C++, `_` variables behave as if they were maybe_unused
2215 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2216 return;
2217
2218 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2219
2220 if (Ty->isReferenceType() || Ty->isDependentType())
2221 return;
2222
2223 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2224 if (Tag->hasAttr<UnusedAttr>())
2225 return;
2226 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2227 // mimic gcc's behavior.
2228 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2229 RD && !RD->hasAttr<WarnUnusedAttr>())
2230 return;
2231 }
2232
2233 // Don't warn on volatile file-scope variables. They are visible beyond their
2234 // declaring function and writes to them could be observable side effects.
2235 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2236 return;
2237
2238 // Don't warn about __block Objective-C pointer variables, as they might
2239 // be assigned in the block but not used elsewhere for the purpose of lifetime
2240 // extension.
2241 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2242 return;
2243
2244 // Don't warn about Objective-C pointer variables with precise lifetime
2245 // semantics; they can be used to ensure ARC releases the object at a known
2246 // time, which may mean assignment but no other references.
2247 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2248 return;
2249
2250 auto iter = RefsMinusAssignments.find(Val: VD->getCanonicalDecl());
2251 if (iter == RefsMinusAssignments.end())
2252 return;
2253
2254 assert(iter->getSecond() >= 0 &&
2255 "Found a negative number of references to a VarDecl");
2256 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2257 // Assume the given VarDecl is "used" if its ref count stored in
2258 // `RefMinusAssignments` is positive, with one exception.
2259 //
2260 // For a C++ variable whose decl (with initializer) entirely consist the
2261 // condition expression of a if/while/for construct,
2262 // Clang creates a DeclRefExpr for the condition expression rather than a
2263 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2264 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2265 // used in the body of the if/while/for construct.
2266 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2267 if (!UnusedCXXCondDecl)
2268 return;
2269 }
2270
2271 unsigned DiagID;
2272 if (isa<ParmVarDecl>(Val: VD))
2273 DiagID = diag::warn_unused_but_set_parameter;
2274 else if (VD->isFileVarDecl())
2275 DiagID = diag::warn_unused_but_set_global;
2276 else
2277 DiagID = diag::warn_unused_but_set_variable;
2278 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2279}
2280
2281static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2282 Sema::DiagReceiverTy DiagReceiver) {
2283 // Verify that we have no forward references left. If so, there was a goto
2284 // or address of a label taken, but no definition of it. Label fwd
2285 // definitions are indicated with a null substmt which is also not a resolved
2286 // MS inline assembly label name.
2287 bool Diagnose = false;
2288 if (L->isMSAsmLabel())
2289 Diagnose = !L->isResolvedMSAsmLabel();
2290 else
2291 Diagnose = L->getStmt() == nullptr;
2292 if (Diagnose)
2293 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2294 << L);
2295}
2296
2297void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2298 S->applyNRVO();
2299
2300 if (S->decl_empty()) return;
2301 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2302 "Scope shouldn't contain decls!");
2303
2304 /// We visit the decls in non-deterministic order, but we want diagnostics
2305 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2306 /// and sort the diagnostics before emitting them, after we visited all decls.
2307 struct LocAndDiag {
2308 SourceLocation Loc;
2309 std::optional<SourceLocation> PreviousDeclLoc;
2310 PartialDiagnostic PD;
2311 };
2312 SmallVector<LocAndDiag, 16> DeclDiags;
2313 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2314 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2315 };
2316 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2317 SourceLocation PreviousDeclLoc,
2318 PartialDiagnostic PD) {
2319 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2320 };
2321
2322 for (auto *TmpD : S->decls()) {
2323 assert(TmpD && "This decl didn't get pushed??");
2324
2325 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2326 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2327
2328 // Diagnose unused variables in this scope.
2329 if (!S->hasUnrecoverableErrorOccurred()) {
2330 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2331 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2332 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2333 // Wait until end of TU to diagnose internal linkage file vars.
2334 if (auto *VD = dyn_cast<VarDecl>(Val: D);
2335 VD && !VD->isInternalLinkageFileVar()) {
2336 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2337 RefsMinusAssignments.erase(Val: VD->getCanonicalDecl());
2338 }
2339 }
2340
2341 if (!D->getDeclName()) continue;
2342
2343 // If this was a forward reference to a label, verify it was defined.
2344 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2345 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2346
2347 // Partial translation units that are created in incremental processing must
2348 // not clean up the IdResolver because PTUs should take into account the
2349 // declarations that came from previous PTUs.
2350 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2351 getLangOpts().CPlusPlus)
2352 IdResolver.RemoveDecl(D);
2353
2354 // Warn on it if we are shadowing a declaration.
2355 auto ShadowI = ShadowingDecls.find(Val: D);
2356 if (ShadowI != ShadowingDecls.end()) {
2357 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2358 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2359 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2360 << D << FD << FD->getParent());
2361 }
2362 ShadowingDecls.erase(I: ShadowI);
2363 }
2364 }
2365
2366 llvm::sort(C&: DeclDiags,
2367 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2368 // The particular order for diagnostics is not important, as long
2369 // as the order is deterministic. Using the raw location is going
2370 // to generally be in source order unless there are macro
2371 // expansions involved.
2372 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2373 });
2374 for (const LocAndDiag &D : DeclDiags) {
2375 Diag(Loc: D.Loc, PD: D.PD);
2376 if (D.PreviousDeclLoc)
2377 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2378 }
2379}
2380
2381Scope *Sema::getNonFieldDeclScope(Scope *S) {
2382 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2383 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2384 (S->isClassScope() && !getLangOpts().CPlusPlus))
2385 S = S->getParent();
2386 return S;
2387}
2388
2389static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2390 ASTContext::GetBuiltinTypeError Error) {
2391 switch (Error) {
2392 case ASTContext::GE_None:
2393 return "";
2394 case ASTContext::GE_Missing_type:
2395 return BuiltinInfo.getHeaderName(ID);
2396 case ASTContext::GE_Missing_stdio:
2397 return "stdio.h";
2398 case ASTContext::GE_Missing_setjmp:
2399 return "setjmp.h";
2400 case ASTContext::GE_Missing_ucontext:
2401 return "ucontext.h";
2402 }
2403 llvm_unreachable("unhandled error kind");
2404}
2405
2406FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2407 unsigned ID, SourceLocation Loc) {
2408 DeclContext *Parent = Context.getTranslationUnitDecl();
2409
2410 if (getLangOpts().CPlusPlus) {
2411 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2412 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2413 CLinkageDecl->setImplicit();
2414 Parent->addDecl(D: CLinkageDecl);
2415 Parent = CLinkageDecl;
2416 }
2417
2418 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2419 if (Context.BuiltinInfo.isImmediate(ID)) {
2420 assert(getLangOpts().CPlusPlus20 &&
2421 "consteval builtins should only be available in C++20 mode");
2422 ConstexprKind = ConstexprSpecKind::Consteval;
2423 }
2424
2425 FunctionDecl *New = FunctionDecl::Create(
2426 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2427 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2428 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2429 New->setImplicit();
2430 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2431
2432 // Create Decl objects for each parameter, adding them to the
2433 // FunctionDecl.
2434 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2435 SmallVector<ParmVarDecl *, 16> Params;
2436 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2437 ParmVarDecl *parm = ParmVarDecl::Create(
2438 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2439 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2440 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2441 Params.push_back(Elt: parm);
2442 }
2443 New->setParams(Params);
2444 }
2445
2446 AddKnownFunctionAttributes(FD: New);
2447 return New;
2448}
2449
2450NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2451 Scope *S, bool ForRedeclaration,
2452 SourceLocation Loc) {
2453 LookupNecessaryTypesForBuiltin(S, ID);
2454
2455 ASTContext::GetBuiltinTypeError Error;
2456 QualType R = Context.GetBuiltinType(ID, Error);
2457 if (Error) {
2458 if (!ForRedeclaration)
2459 return nullptr;
2460
2461 // If we have a builtin without an associated type we should not emit a
2462 // warning when we were not able to find a type for it.
2463 if (Error == ASTContext::GE_Missing_type ||
2464 Context.BuiltinInfo.allowTypeMismatch(ID))
2465 return nullptr;
2466
2467 // If we could not find a type for setjmp it is because the jmp_buf type was
2468 // not defined prior to the setjmp declaration.
2469 if (Error == ASTContext::GE_Missing_setjmp) {
2470 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2471 << Context.BuiltinInfo.getName(ID);
2472 return nullptr;
2473 }
2474
2475 // Generally, we emit a warning that the declaration requires the
2476 // appropriate header.
2477 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2478 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2479 << Context.BuiltinInfo.getName(ID);
2480 return nullptr;
2481 }
2482
2483 if (!ForRedeclaration &&
2484 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2485 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2486 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2487 : diag::ext_implicit_lib_function_decl)
2488 << Context.BuiltinInfo.getName(ID) << R;
2489 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2490 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2491 << Header << Context.BuiltinInfo.getName(ID);
2492 }
2493
2494 if (R.isNull())
2495 return nullptr;
2496
2497 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2498 RegisterLocallyScopedExternCDecl(ND: New, S);
2499
2500 // TUScope is the translation-unit scope to insert this function into.
2501 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2502 // relate Scopes to DeclContexts, and probably eliminate CurContext
2503 // entirely, but we're not there yet.
2504 DeclContext *SavedContext = CurContext;
2505 CurContext = New->getDeclContext();
2506 PushOnScopeChains(D: New, S: TUScope);
2507 CurContext = SavedContext;
2508 return New;
2509}
2510
2511/// Typedef declarations don't have linkage, but they still denote the same
2512/// entity if their types are the same.
2513/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2514/// isSameEntity.
2515static void
2516filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2517 LookupResult &Previous) {
2518 // This is only interesting when modules are enabled.
2519 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2520 return;
2521
2522 // Empty sets are uninteresting.
2523 if (Previous.empty())
2524 return;
2525
2526 LookupResult::Filter Filter = Previous.makeFilter();
2527 while (Filter.hasNext()) {
2528 NamedDecl *Old = Filter.next();
2529
2530 // Non-hidden declarations are never ignored.
2531 if (S.isVisible(D: Old))
2532 continue;
2533
2534 // Declarations of the same entity are not ignored, even if they have
2535 // different linkages.
2536 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2537 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2538 T2: Decl->getUnderlyingType()))
2539 continue;
2540
2541 // If both declarations give a tag declaration a typedef name for linkage
2542 // purposes, then they declare the same entity.
2543 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2544 Decl->getAnonDeclWithTypedefName())
2545 continue;
2546 }
2547
2548 Filter.erase();
2549 }
2550
2551 Filter.done();
2552}
2553
2554bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2555 QualType OldType;
2556 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2557 OldType = OldTypedef->getUnderlyingType();
2558 else
2559 OldType = Context.getTypeDeclType(Decl: Old);
2560 QualType NewType = New->getUnderlyingType();
2561
2562 if (NewType->isVariablyModifiedType()) {
2563 // Must not redefine a typedef with a variably-modified type.
2564 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2565 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2566 << Kind << NewType;
2567 if (Old->getLocation().isValid())
2568 notePreviousDefinition(Old, New: New->getLocation());
2569 New->setInvalidDecl();
2570 return true;
2571 }
2572
2573 if (OldType != NewType &&
2574 !OldType->isDependentType() &&
2575 !NewType->isDependentType() &&
2576 !Context.hasSameType(T1: OldType, T2: NewType)) {
2577 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2578 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2579 << Kind << NewType << OldType;
2580 if (Old->getLocation().isValid())
2581 notePreviousDefinition(Old, New: New->getLocation());
2582 New->setInvalidDecl();
2583 return true;
2584 }
2585 return false;
2586}
2587
2588void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2589 LookupResult &OldDecls) {
2590 // If the new decl is known invalid already, don't bother doing any
2591 // merging checks.
2592 if (New->isInvalidDecl()) return;
2593
2594 // Allow multiple definitions for ObjC built-in typedefs.
2595 // FIXME: Verify the underlying types are equivalent!
2596 if (getLangOpts().ObjC) {
2597 const IdentifierInfo *TypeID = New->getIdentifier();
2598 switch (TypeID->getLength()) {
2599 default: break;
2600 case 2:
2601 {
2602 if (!TypeID->isStr(Str: "id"))
2603 break;
2604 QualType T = New->getUnderlyingType();
2605 if (!T->isPointerType())
2606 break;
2607 if (!T->isVoidPointerType()) {
2608 QualType PT = T->castAs<PointerType>()->getPointeeType();
2609 if (!PT->isStructureType())
2610 break;
2611 }
2612 Context.setObjCIdRedefinitionType(T);
2613 // Install the built-in type for 'id', ignoring the current definition.
2614 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2615 modedTy: Context.getObjCIdType());
2616 return;
2617 }
2618 case 5:
2619 if (!TypeID->isStr(Str: "Class"))
2620 break;
2621 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2622 // Install the built-in type for 'Class', ignoring the current definition.
2623 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2624 modedTy: Context.getObjCClassType());
2625 return;
2626 case 3:
2627 if (!TypeID->isStr(Str: "SEL"))
2628 break;
2629 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2630 // Install the built-in type for 'SEL', ignoring the current definition.
2631 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2632 modedTy: Context.getObjCSelType());
2633 return;
2634 }
2635 // Fall through - the typedef name was not a builtin type.
2636 }
2637
2638 // Verify the old decl was also a type.
2639 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2640 if (!Old) {
2641 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2642 << New->getDeclName();
2643
2644 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2645 if (OldD->getLocation().isValid())
2646 notePreviousDefinition(Old: OldD, New: New->getLocation());
2647
2648 return New->setInvalidDecl();
2649 }
2650
2651 // If the old declaration is invalid, just give up here.
2652 if (Old->isInvalidDecl())
2653 return New->setInvalidDecl();
2654
2655 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2656 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2657 auto *NewTag = New->getAnonDeclWithTypedefName();
2658 NamedDecl *Hidden = nullptr;
2659 if (OldTag && NewTag &&
2660 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2661 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2662 // There is a definition of this tag, but it is not visible. Use it
2663 // instead of our tag.
2664 if (OldTD->isModed())
2665 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2666 modedTy: OldTD->getUnderlyingType());
2667 else
2668 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2669
2670 // Make the old tag definition visible.
2671 makeMergedDefinitionVisible(ND: Hidden);
2672
2673 CleanupMergedEnum(S, New: NewTag);
2674 }
2675 }
2676
2677 // If the typedef types are not identical, reject them in all languages and
2678 // with any extensions enabled.
2679 if (isIncompatibleTypedef(Old, New))
2680 return;
2681
2682 // The types match. Link up the redeclaration chain and merge attributes if
2683 // the old declaration was a typedef.
2684 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2685 New->setPreviousDecl(Typedef);
2686 mergeDeclAttributes(New, Old);
2687 }
2688
2689 if (getLangOpts().MicrosoftExt)
2690 return;
2691
2692 if (getLangOpts().CPlusPlus) {
2693 // C++ [dcl.typedef]p2:
2694 // In a given non-class scope, a typedef specifier can be used to
2695 // redefine the name of any type declared in that scope to refer
2696 // to the type to which it already refers.
2697 if (!isa<CXXRecordDecl>(Val: CurContext))
2698 return;
2699
2700 // C++0x [dcl.typedef]p4:
2701 // In a given class scope, a typedef specifier can be used to redefine
2702 // any class-name declared in that scope that is not also a typedef-name
2703 // to refer to the type to which it already refers.
2704 //
2705 // This wording came in via DR424, which was a correction to the
2706 // wording in DR56, which accidentally banned code like:
2707 //
2708 // struct S {
2709 // typedef struct A { } A;
2710 // };
2711 //
2712 // in the C++03 standard. We implement the C++0x semantics, which
2713 // allow the above but disallow
2714 //
2715 // struct S {
2716 // typedef int I;
2717 // typedef int I;
2718 // };
2719 //
2720 // since that was the intent of DR56.
2721 if (!isa<TypedefNameDecl>(Val: Old))
2722 return;
2723
2724 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2725 << New->getDeclName();
2726 notePreviousDefinition(Old, New: New->getLocation());
2727 return New->setInvalidDecl();
2728 }
2729
2730 // Modules always permit redefinition of typedefs, as does C11.
2731 if (getLangOpts().Modules || getLangOpts().C11)
2732 return;
2733
2734 // If we have a redefinition of a typedef in C, emit a warning. This warning
2735 // is normally mapped to an error, but can be controlled with
2736 // -Wtypedef-redefinition. If either the original or the redefinition is
2737 // in a system header, don't emit this for compatibility with GCC.
2738 if (getDiagnostics().getSuppressSystemWarnings() &&
2739 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2740 (Old->isImplicit() ||
2741 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2742 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2743 return;
2744
2745 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2746 << New->getDeclName();
2747 notePreviousDefinition(Old, New: New->getLocation());
2748}
2749
2750void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2751 // If this was an unscoped enumeration, yank all of its enumerators
2752 // out of the scope.
2753 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2754 Scope *EnumScope = getNonFieldDeclScope(S);
2755 for (auto *ECD : ED->enumerators()) {
2756 assert(EnumScope->isDeclScope(ECD));
2757 EnumScope->RemoveDecl(D: ECD);
2758 IdResolver.RemoveDecl(D: ECD);
2759 }
2760 }
2761}
2762
2763/// DeclhasAttr - returns true if decl Declaration already has the target
2764/// attribute.
2765static bool DeclHasAttr(const Decl *D, const Attr *A) {
2766 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2767 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2768 for (const auto *i : D->attrs())
2769 if (i->getKind() == A->getKind()) {
2770 if (Ann) {
2771 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2772 return true;
2773 continue;
2774 }
2775 // FIXME: Don't hardcode this check
2776 if (OA && isa<OwnershipAttr>(Val: i))
2777 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2778 return true;
2779 }
2780
2781 return false;
2782}
2783
2784static bool isAttributeTargetADefinition(Decl *D) {
2785 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2786 return VD->isThisDeclarationADefinition();
2787 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2788 return TD->isCompleteDefinition() || TD->isBeingDefined();
2789 return true;
2790}
2791
2792/// Merge alignment attributes from \p Old to \p New, taking into account the
2793/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2794///
2795/// \return \c true if any attributes were added to \p New.
2796static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2797 // Look for alignas attributes on Old, and pick out whichever attribute
2798 // specifies the strictest alignment requirement.
2799 AlignedAttr *OldAlignasAttr = nullptr;
2800 AlignedAttr *OldStrictestAlignAttr = nullptr;
2801 unsigned OldAlign = 0;
2802 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2803 // FIXME: We have no way of representing inherited dependent alignments
2804 // in a case like:
2805 // template<int A, int B> struct alignas(A) X;
2806 // template<int A, int B> struct alignas(B) X {};
2807 // For now, we just ignore any alignas attributes which are not on the
2808 // definition in such a case.
2809 if (I->isAlignmentDependent())
2810 return false;
2811
2812 if (I->isAlignas())
2813 OldAlignasAttr = I;
2814
2815 unsigned Align = I->getAlignment(Ctx&: S.Context);
2816 if (Align > OldAlign) {
2817 OldAlign = Align;
2818 OldStrictestAlignAttr = I;
2819 }
2820 }
2821
2822 // Look for alignas attributes on New.
2823 AlignedAttr *NewAlignasAttr = nullptr;
2824 unsigned NewAlign = 0;
2825 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2826 if (I->isAlignmentDependent())
2827 return false;
2828
2829 if (I->isAlignas())
2830 NewAlignasAttr = I;
2831
2832 unsigned Align = I->getAlignment(Ctx&: S.Context);
2833 if (Align > NewAlign)
2834 NewAlign = Align;
2835 }
2836
2837 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2838 // Both declarations have 'alignas' attributes. We require them to match.
2839 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2840 // fall short. (If two declarations both have alignas, they must both match
2841 // every definition, and so must match each other if there is a definition.)
2842
2843 // If either declaration only contains 'alignas(0)' specifiers, then it
2844 // specifies the natural alignment for the type.
2845 if (OldAlign == 0 || NewAlign == 0) {
2846 QualType Ty;
2847 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2848 Ty = VD->getType();
2849 else
2850 Ty = S.Context.getCanonicalTagType(TD: cast<TagDecl>(Val: New));
2851
2852 if (OldAlign == 0)
2853 OldAlign = S.Context.getTypeAlign(T: Ty);
2854 if (NewAlign == 0)
2855 NewAlign = S.Context.getTypeAlign(T: Ty);
2856 }
2857
2858 if (OldAlign != NewAlign) {
2859 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2860 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2861 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2862 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2863 }
2864 }
2865
2866 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2867 // C++11 [dcl.align]p6:
2868 // if any declaration of an entity has an alignment-specifier,
2869 // every defining declaration of that entity shall specify an
2870 // equivalent alignment.
2871 // C11 6.7.5/7:
2872 // If the definition of an object does not have an alignment
2873 // specifier, any other declaration of that object shall also
2874 // have no alignment specifier.
2875 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2876 << OldAlignasAttr;
2877 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2878 << OldAlignasAttr;
2879 }
2880
2881 bool AnyAdded = false;
2882
2883 // Ensure we have an attribute representing the strictest alignment.
2884 if (OldAlign > NewAlign) {
2885 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2886 Clone->setInherited(true);
2887 New->addAttr(A: Clone);
2888 AnyAdded = true;
2889 }
2890
2891 // Ensure we have an alignas attribute if the old declaration had one.
2892 if (OldAlignasAttr && !NewAlignasAttr &&
2893 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2894 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2895 Clone->setInherited(true);
2896 New->addAttr(A: Clone);
2897 AnyAdded = true;
2898 }
2899
2900 return AnyAdded;
2901}
2902
2903#define WANT_DECL_MERGE_LOGIC
2904#include "clang/Sema/AttrParsedAttrImpl.inc"
2905#undef WANT_DECL_MERGE_LOGIC
2906
2907static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2908 const InheritableAttr *Attr,
2909 AvailabilityMergeKind AMK) {
2910 // Diagnose any mutual exclusions between the attribute that we want to add
2911 // and attributes that already exist on the declaration.
2912 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2913 return false;
2914
2915 // This function copies an attribute Attr from a previous declaration to the
2916 // new declaration D if the new declaration doesn't itself have that attribute
2917 // yet or if that attribute allows duplicates.
2918 // If you're adding a new attribute that requires logic different from
2919 // "use explicit attribute on decl if present, else use attribute from
2920 // previous decl", for example if the attribute needs to be consistent
2921 // between redeclarations, you need to call a custom merge function here.
2922 InheritableAttr *NewAttr = nullptr;
2923 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr)) {
2924 const IdentifierInfo *InferredPlatformII = nullptr;
2925 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2926 InferredPlatformII = Inf->getPlatform();
2927 NewAttr = S.mergeAndInferAvailabilityAttr(
2928 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2929 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2930 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2931 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment(), InferredPlatformII);
2932 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2933 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2934 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2935 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2936 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2937 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2938 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2939 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2940 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2941 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2942 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2943 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2944 FirstArg: FA->getFirstArg());
2945 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2946 NewAttr = S.mergeFormatMatchesAttr(
2947 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2948 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Val: Attr))
2949 NewAttr = S.mergeModularFormatAttr(
2950 D, CI: *MFA, ModularImplFn: MFA->getModularImplFn(), ImplName: MFA->getImplName(),
2951 Aspects: MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2952 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2953 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2954 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2955 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2956 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
2957 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
2958 Model: IA->getInheritanceModel());
2959 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
2960 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
2961 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
2962 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
2963 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
2964 isa<CUDAGlobalAttr>(Val: Attr))) {
2965 // CUDA target attributes are part of function signature for
2966 // overloading purposes and must not be merged.
2967 return false;
2968 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
2969 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
2970 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
2971 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
2972 else if (const auto *SAA = dyn_cast<SwiftAttrAttr>(Val: Attr))
2973 NewAttr = S.Swift().mergeAttrAttr(D, SAA: *SAA);
2974 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
2975 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
2976 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
2977 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
2978 else if (isa<AlignedAttr>(Val: Attr))
2979 // AlignedAttrs are handled separately, because we need to handle all
2980 // such attributes on a declaration at the same time.
2981 NewAttr = nullptr;
2982 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
2983 (AMK == AvailabilityMergeKind::Override ||
2984 AMK == AvailabilityMergeKind::ProtocolImplementation ||
2985 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
2986 NewAttr = nullptr;
2987 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
2988 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
2989 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
2990 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
2991 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
2992 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
2993 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
2994 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
2995 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
2996 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
2997 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
2998 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
2999 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
3000 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
3001 Z: NT->getZ());
3002 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
3003 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
3004 Preferred: WS->getPreferred(),
3005 SpelledArgsCount: WS->getSpelledArgsCount());
3006 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
3007 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
3008 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
3009 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
3010 else if (isa<SuppressAttr>(Val: Attr))
3011 // Do nothing. Each redeclaration should be suppressed separately.
3012 NewAttr = nullptr;
3013 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
3014 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
3015 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
3016 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
3017 else if (const auto *PA = dyn_cast<PersonalityAttr>(Val: Attr))
3018 NewAttr = S.mergePersonalityAttr(D, Routine: PA->getRoutine(), CI: *PA);
3019
3020 if (NewAttr) {
3021 NewAttr->setInherited(true);
3022 D->addAttr(A: NewAttr);
3023 if (isa<MSInheritanceAttr>(Val: NewAttr))
3024 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
3025 return true;
3026 }
3027
3028 return false;
3029}
3030
3031static const NamedDecl *getDefinition(const Decl *D) {
3032 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
3033 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3034 return Def;
3035 return nullptr;
3036 }
3037 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
3038 const VarDecl *Def = VD->getDefinition();
3039 if (Def)
3040 return Def;
3041 return VD->getActingDefinition();
3042 }
3043 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3044 const FunctionDecl *Def = nullptr;
3045 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3046 return Def;
3047 }
3048 return nullptr;
3049}
3050
3051static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3052 for (const auto *Attribute : D->attrs())
3053 if (Attribute->getKind() == Kind)
3054 return true;
3055 return false;
3056}
3057
3058/// checkNewAttributesAfterDef - If we already have a definition, check that
3059/// there are no new attributes in this declaration.
3060static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3061 if (!New->hasAttrs())
3062 return;
3063
3064 const NamedDecl *Def = getDefinition(D: Old);
3065 if (!Def || Def == New)
3066 return;
3067
3068 AttrVec &NewAttributes = New->getAttrs();
3069 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3070 Attr *NewAttribute = NewAttributes[I];
3071
3072 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
3073 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3074 SkipBodyInfo SkipBody;
3075 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3076
3077 // If we're skipping this definition, drop the "alias" attribute.
3078 if (SkipBody.ShouldSkip) {
3079 NewAttributes.erase(CI: NewAttributes.begin() + I);
3080 --E;
3081 continue;
3082 }
3083 } else {
3084 VarDecl *VD = cast<VarDecl>(Val: New);
3085 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
3086 VarDecl::TentativeDefinition
3087 ? diag::err_alias_after_tentative
3088 : diag::err_redefinition;
3089 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
3090 if (Diag == diag::err_redefinition)
3091 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3092 else
3093 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3094 VD->setInvalidDecl();
3095 }
3096 ++I;
3097 continue;
3098 }
3099
3100 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3101 // Tentative definitions are only interesting for the alias check above.
3102 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3103 ++I;
3104 continue;
3105 }
3106 }
3107
3108 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
3109 ++I;
3110 continue; // regular attr merging will take care of validating this.
3111 }
3112
3113 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
3114 // C's _Noreturn is allowed to be added to a function after it is defined.
3115 ++I;
3116 continue;
3117 } else if (isa<UuidAttr>(Val: NewAttribute)) {
3118 // msvc will allow a subsequent definition to add an uuid to a class
3119 ++I;
3120 continue;
3121 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3122 Val: NewAttribute) &&
3123 NewAttribute->isStandardAttributeSyntax()) {
3124 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3125 // deprecated attribute can later be re-declared with the attribute and
3126 // vice-versa.
3127 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3128 // maybe_unused attribute can later be redeclared with the attribute and
3129 // vice versa.
3130 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3131 // nodiscard attribute can later be redeclared with the attribute and
3132 // vice-versa.
3133 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3134 ++I;
3135 continue;
3136 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3137 if (AA->isAlignas()) {
3138 // C++11 [dcl.align]p6:
3139 // if any declaration of an entity has an alignment-specifier,
3140 // every defining declaration of that entity shall specify an
3141 // equivalent alignment.
3142 // C11 6.7.5/7:
3143 // If the definition of an object does not have an alignment
3144 // specifier, any other declaration of that object shall also
3145 // have no alignment specifier.
3146 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3147 << AA;
3148 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3149 << AA;
3150 NewAttributes.erase(CI: NewAttributes.begin() + I);
3151 --E;
3152 continue;
3153 }
3154 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3155 // If there is a C definition followed by a redeclaration with this
3156 // attribute then there are two different definitions. In C++, prefer the
3157 // standard diagnostics.
3158 if (!S.getLangOpts().CPlusPlus) {
3159 S.Diag(Loc: NewAttribute->getLocation(),
3160 DiagID: diag::err_loader_uninitialized_redeclaration);
3161 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3162 NewAttributes.erase(CI: NewAttributes.begin() + I);
3163 --E;
3164 continue;
3165 }
3166 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3167 cast<VarDecl>(Val: New)->isInline() &&
3168 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3169 // Don't warn about applying selectany to implicitly inline variables.
3170 // Older compilers and language modes would require the use of selectany
3171 // to make such variables inline, and it would have no effect if we
3172 // honored it.
3173 ++I;
3174 continue;
3175 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3176 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3177 // declarations after definitions.
3178 ++I;
3179 continue;
3180 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3181 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3182 // error since the definition will have already been created without
3183 // the semantic effects of the attribute having been applied.
3184 S.Diag(Loc: NewAttribute->getLocation(),
3185 DiagID: diag::err_sycl_entry_point_after_definition)
3186 << NewAttribute;
3187 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3188 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3189 ++I;
3190 continue;
3191 } else if (isa<SYCLExternalAttr>(Val: NewAttribute)) {
3192 // SYCLExternalAttr may be added after a definition.
3193 ++I;
3194 continue;
3195 }
3196
3197 S.Diag(Loc: NewAttribute->getLocation(),
3198 DiagID: diag::warn_attribute_precede_definition);
3199 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3200 NewAttributes.erase(CI: NewAttributes.begin() + I);
3201 --E;
3202 }
3203}
3204
3205static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3206 const ConstInitAttr *CIAttr,
3207 bool AttrBeforeInit) {
3208 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3209
3210 // Figure out a good way to write this specifier on the old declaration.
3211 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3212 // enough of the attribute list spelling information to extract that without
3213 // heroics.
3214 std::string SuitableSpelling;
3215 if (S.getLangOpts().CPlusPlus20)
3216 SuitableSpelling = std::string(
3217 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3218 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3219 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3220 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3221 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3222 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3223 tok::r_square, tok::r_square}));
3224 if (SuitableSpelling.empty())
3225 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3226 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3227 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3228 tok::r_paren, tok::r_paren}));
3229 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3230 SuitableSpelling = "constinit";
3231 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3232 SuitableSpelling = "[[clang::require_constant_initialization]]";
3233 if (SuitableSpelling.empty())
3234 SuitableSpelling = "__attribute__((require_constant_initialization))";
3235 SuitableSpelling += " ";
3236
3237 if (AttrBeforeInit) {
3238 // extern constinit int a;
3239 // int a = 0; // error (missing 'constinit'), accepted as extension
3240 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3241 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3242 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3243 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3244 } else {
3245 // int a = 0;
3246 // constinit extern int a; // error (missing 'constinit')
3247 S.Diag(Loc: CIAttr->getLocation(),
3248 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3249 : diag::warn_require_const_init_added_too_late)
3250 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3251 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3252 << CIAttr->isConstinit()
3253 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3254 }
3255}
3256
3257void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3258 AvailabilityMergeKind AMK) {
3259 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3260 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3261 NewAttr->setInherited(true);
3262 New->addAttr(A: NewAttr);
3263 }
3264 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3265 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3266 NewAttr->setInherited(true);
3267 New->addAttr(A: NewAttr);
3268 }
3269
3270 if (!Old->hasAttrs() && !New->hasAttrs())
3271 return;
3272
3273 // [dcl.constinit]p1:
3274 // If the [constinit] specifier is applied to any declaration of a
3275 // variable, it shall be applied to the initializing declaration.
3276 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3277 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3278 if (bool(OldConstInit) != bool(NewConstInit)) {
3279 const auto *OldVD = cast<VarDecl>(Val: Old);
3280 auto *NewVD = cast<VarDecl>(Val: New);
3281
3282 // Find the initializing declaration. Note that we might not have linked
3283 // the new declaration into the redeclaration chain yet.
3284 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3285 if (!InitDecl &&
3286 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3287 InitDecl = NewVD;
3288
3289 if (InitDecl == NewVD) {
3290 // This is the initializing declaration. If it would inherit 'constinit',
3291 // that's ill-formed. (Note that we do not apply this to the attribute
3292 // form).
3293 if (OldConstInit && OldConstInit->isConstinit())
3294 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3295 /*AttrBeforeInit=*/true);
3296 } else if (NewConstInit) {
3297 // This is the first time we've been told that this declaration should
3298 // have a constant initializer. If we already saw the initializing
3299 // declaration, this is too late.
3300 if (InitDecl && InitDecl != NewVD) {
3301 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3302 /*AttrBeforeInit=*/false);
3303 NewVD->dropAttr<ConstInitAttr>();
3304 }
3305 }
3306 }
3307
3308 // Attributes declared post-definition are currently ignored.
3309 checkNewAttributesAfterDef(S&: *this, New, Old);
3310
3311 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3312 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3313 if (!OldA->isEquivalent(Other: NewA)) {
3314 // This redeclaration changes __asm__ label.
3315 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3316 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3317 }
3318 } else if (Old->isUsed()) {
3319 // This redeclaration adds an __asm__ label to a declaration that has
3320 // already been ODR-used.
3321 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3322 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3323 }
3324 }
3325
3326 // Re-declaration cannot add abi_tag's.
3327 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3328 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3329 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3330 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3331 Diag(Loc: NewAbiTagAttr->getLocation(),
3332 DiagID: diag::err_new_abi_tag_on_redeclaration)
3333 << NewTag;
3334 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3335 }
3336 }
3337 } else {
3338 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3339 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3340 }
3341 }
3342
3343 // This redeclaration adds a section attribute.
3344 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3345 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3346 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3347 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3348 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3349 }
3350 }
3351 }
3352
3353 // Redeclaration adds code-seg attribute.
3354 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3355 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3356 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3357 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3358 << 0 /*codeseg*/;
3359 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3360 }
3361
3362 if (!Old->hasAttrs())
3363 return;
3364
3365 bool foundAny = New->hasAttrs();
3366
3367 // Ensure that any moving of objects within the allocated map is done before
3368 // we process them.
3369 if (!foundAny) New->setAttrs(AttrVec());
3370
3371 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3372 // Ignore deprecated/unavailable/availability attributes if requested.
3373 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3374 if (isa<DeprecatedAttr>(Val: I) ||
3375 isa<UnavailableAttr>(Val: I) ||
3376 isa<AvailabilityAttr>(Val: I)) {
3377 switch (AMK) {
3378 case AvailabilityMergeKind::None:
3379 continue;
3380
3381 case AvailabilityMergeKind::Redeclaration:
3382 case AvailabilityMergeKind::Override:
3383 case AvailabilityMergeKind::ProtocolImplementation:
3384 case AvailabilityMergeKind::OptionalProtocolImplementation:
3385 LocalAMK = AMK;
3386 break;
3387 }
3388 }
3389
3390 // Already handled.
3391 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3392 continue;
3393
3394 // Don't propagate inferred noreturn or conflicting inline attributes to
3395 // explicit specializations.
3396 if (isa<InferredNoReturnAttr>(Val: I) || isa<AlwaysInlineAttr>(Val: I) ||
3397 isa<NoInlineAttr>(Val: I)) {
3398 if (auto *FD = dyn_cast<FunctionDecl>(Val: New);
3399 FD &&
3400 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3401 continue;
3402 }
3403
3404 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3405 foundAny = true;
3406 }
3407
3408 if (mergeAlignedAttrs(S&: *this, New, Old))
3409 foundAny = true;
3410
3411 if (!foundAny) New->dropAttrs();
3412}
3413
3414void Sema::CheckAttributesOnDeducedType(Decl *D) {
3415 for (const Attr *A : D->attrs())
3416 checkAttrIsTypeDependent(D, A);
3417}
3418
3419// Returns the number of added attributes.
3420template <class T>
3421static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3422 Sema &S) {
3423 unsigned found = 0;
3424 for (const auto *I : From->specific_attrs<T>()) {
3425 if (!DeclHasAttr(To, I)) {
3426 T *newAttr = cast<T>(I->clone(S.Context));
3427 newAttr->setInherited(true);
3428 To->addAttr(A: newAttr);
3429 ++found;
3430 }
3431 }
3432 return found;
3433}
3434
3435template <class F>
3436static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3437 F &&propagator) {
3438 if (!From->hasAttrs()) {
3439 return;
3440 }
3441
3442 bool foundAny = To->hasAttrs();
3443
3444 // Ensure that any moving of objects within the allocated map is
3445 // done before we process them.
3446 if (!foundAny)
3447 To->setAttrs(AttrVec());
3448
3449 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3450
3451 if (!foundAny)
3452 To->dropAttrs();
3453}
3454
3455/// mergeParamDeclAttributes - Copy attributes from the old parameter
3456/// to the new one.
3457static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3458 const ParmVarDecl *oldDecl,
3459 Sema &S) {
3460 // C++11 [dcl.attr.depend]p2:
3461 // The first declaration of a function shall specify the
3462 // carries_dependency attribute for its declarator-id if any declaration
3463 // of the function specifies the carries_dependency attribute.
3464 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3465 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3466 S.Diag(Loc: CDA->getLocation(),
3467 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3468 // Find the first declaration of the parameter.
3469 // FIXME: Should we build redeclaration chains for function parameters?
3470 const FunctionDecl *FirstFD =
3471 cast<FunctionDecl>(Val: oldDecl->getDeclContext())->getFirstDecl();
3472 const ParmVarDecl *FirstVD =
3473 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3474 S.Diag(Loc: FirstVD->getLocation(),
3475 DiagID: diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3476 }
3477
3478 propagateAttributes(
3479 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3480 unsigned found = 0;
3481 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3482 // Propagate the lifetimebound attribute from parameters to the
3483 // most recent declaration. Note that this doesn't include the implicit
3484 // 'this' parameter, as the attribute is applied to the function type in
3485 // that case.
3486 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3487 return found;
3488 });
3489}
3490
3491static bool EquivalentArrayTypes(QualType Old, QualType New,
3492 const ASTContext &Ctx) {
3493
3494 auto NoSizeInfo = [&Ctx](QualType Ty) {
3495 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3496 return true;
3497 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3498 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3499 return false;
3500 };
3501
3502 // `type[]` is equivalent to `type *` and `type[*]`.
3503 if (NoSizeInfo(Old) && NoSizeInfo(New))
3504 return true;
3505
3506 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3507 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3508 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3509 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3510 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3511 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3512 return false;
3513 return true;
3514 }
3515
3516 // Only compare size, ignore Size modifiers and CVR.
3517 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3518 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3519 Ctx.getAsConstantArrayType(T: New)->getSize();
3520 }
3521
3522 // Don't try to compare dependent sized array
3523 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3524 return true;
3525 }
3526
3527 return Old == New;
3528}
3529
3530static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3531 const ParmVarDecl *OldParam,
3532 Sema &S) {
3533 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3534 if (auto Newnullability = NewParam->getType()->getNullability()) {
3535 if (*Oldnullability != *Newnullability) {
3536 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3537 << DiagNullabilityKind(
3538 *Newnullability,
3539 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3540 != 0))
3541 << DiagNullabilityKind(
3542 *Oldnullability,
3543 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3544 != 0));
3545 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3546 }
3547 } else {
3548 QualType NewT = NewParam->getType();
3549 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3550 NewParam->setType(NewT);
3551 }
3552 }
3553 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3554 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3555 if (OldParamDT && NewParamDT &&
3556 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3557 QualType OldParamOT = OldParamDT->getOriginalType();
3558 QualType NewParamOT = NewParamDT->getOriginalType();
3559 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3560 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3561 << NewParam << NewParamOT;
3562 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3563 << OldParamOT;
3564 }
3565 }
3566}
3567
3568namespace {
3569
3570/// Used in MergeFunctionDecl to keep track of function parameters in
3571/// C.
3572struct GNUCompatibleParamWarning {
3573 ParmVarDecl *OldParm;
3574 ParmVarDecl *NewParm;
3575 QualType PromotedType;
3576};
3577
3578} // end anonymous namespace
3579
3580// Determine whether the previous declaration was a definition, implicit
3581// declaration, or a declaration.
3582template <typename T>
3583static std::pair<diag::kind, SourceLocation>
3584getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3585 diag::kind PrevDiag;
3586 SourceLocation OldLocation = Old->getLocation();
3587 if (Old->isThisDeclarationADefinition())
3588 PrevDiag = diag::note_previous_definition;
3589 else if (Old->isImplicit()) {
3590 PrevDiag = diag::note_previous_implicit_declaration;
3591 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3592 if (FD->getBuiltinID())
3593 PrevDiag = diag::note_previous_builtin_declaration;
3594 }
3595 if (OldLocation.isInvalid())
3596 OldLocation = New->getLocation();
3597 } else
3598 PrevDiag = diag::note_previous_declaration;
3599 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3600}
3601
3602/// canRedefineFunction - checks if a function can be redefined. Currently,
3603/// only extern inline functions can be redefined, and even then only in
3604/// GNU89 mode.
3605static bool canRedefineFunction(const FunctionDecl *FD,
3606 const LangOptions& LangOpts) {
3607 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3608 !LangOpts.CPlusPlus &&
3609 FD->isInlineSpecified() &&
3610 FD->getStorageClass() == SC_Extern);
3611}
3612
3613const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3614 const AttributedType *AT = T->getAs<AttributedType>();
3615 while (AT && !AT->isCallingConv())
3616 AT = AT->getModifiedType()->getAs<AttributedType>();
3617 return AT;
3618}
3619
3620template <typename T>
3621static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3622 const DeclContext *DC = Old->getDeclContext();
3623 if (DC->isRecord())
3624 return false;
3625
3626 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3627 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3628 return true;
3629 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3630 return true;
3631 return false;
3632}
3633
3634template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3635static bool isExternC(VarTemplateDecl *) { return false; }
3636static bool isExternC(FunctionTemplateDecl *) { return false; }
3637
3638/// Check whether a redeclaration of an entity introduced by a
3639/// using-declaration is valid, given that we know it's not an overload
3640/// (nor a hidden tag declaration).
3641template<typename ExpectedDecl>
3642static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3643 ExpectedDecl *New) {
3644 // C++11 [basic.scope.declarative]p4:
3645 // Given a set of declarations in a single declarative region, each of
3646 // which specifies the same unqualified name,
3647 // -- they shall all refer to the same entity, or all refer to functions
3648 // and function templates; or
3649 // -- exactly one declaration shall declare a class name or enumeration
3650 // name that is not a typedef name and the other declarations shall all
3651 // refer to the same variable or enumerator, or all refer to functions
3652 // and function templates; in this case the class name or enumeration
3653 // name is hidden (3.3.10).
3654
3655 // C++11 [namespace.udecl]p14:
3656 // If a function declaration in namespace scope or block scope has the
3657 // same name and the same parameter-type-list as a function introduced
3658 // by a using-declaration, and the declarations do not declare the same
3659 // function, the program is ill-formed.
3660
3661 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3662 if (Old &&
3663 !Old->getDeclContext()->getRedeclContext()->Equals(
3664 New->getDeclContext()->getRedeclContext()) &&
3665 !(isExternC(Old) && isExternC(New)))
3666 Old = nullptr;
3667
3668 if (!Old) {
3669 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3670 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3671 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3672 return true;
3673 }
3674 return false;
3675}
3676
3677static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3678 const FunctionDecl *B) {
3679 assert(A->getNumParams() == B->getNumParams());
3680
3681 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3682 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3683 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3684 if (AttrA == AttrB)
3685 return true;
3686 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3687 AttrA->isDynamic() == AttrB->isDynamic();
3688 };
3689
3690 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3691}
3692
3693/// If necessary, adjust the semantic declaration context for a qualified
3694/// declaration to name the correct inline namespace within the qualifier.
3695static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3696 DeclaratorDecl *OldD) {
3697 // The only case where we need to update the DeclContext is when
3698 // redeclaration lookup for a qualified name finds a declaration
3699 // in an inline namespace within the context named by the qualifier:
3700 //
3701 // inline namespace N { int f(); }
3702 // int ::f(); // Sema DC needs adjusting from :: to N::.
3703 //
3704 // For unqualified declarations, the semantic context *can* change
3705 // along the redeclaration chain (for local extern declarations,
3706 // extern "C" declarations, and friend declarations in particular).
3707 if (!NewD->getQualifier())
3708 return;
3709
3710 // NewD is probably already in the right context.
3711 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3712 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3713 if (NamedDC->Equals(DC: SemaDC))
3714 return;
3715
3716 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3717 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3718 "unexpected context for redeclaration");
3719
3720 auto *LexDC = NewD->getLexicalDeclContext();
3721 auto FixSemaDC = [=](NamedDecl *D) {
3722 if (!D)
3723 return;
3724 D->setDeclContext(SemaDC);
3725 D->setLexicalDeclContext(LexDC);
3726 };
3727
3728 FixSemaDC(NewD);
3729 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3730 FixSemaDC(FD->getDescribedFunctionTemplate());
3731 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3732 FixSemaDC(VD->getDescribedVarTemplate());
3733}
3734
3735bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3736 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3737 // Verify the old decl was also a function.
3738 FunctionDecl *Old = OldD->getAsFunction();
3739 if (!Old) {
3740 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3741 // We don't need to check the using friend pattern from other module unit
3742 // since we should have diagnosed such cases in its unit already.
3743 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3744 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3745 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3746 DiagID: diag::note_using_decl_target);
3747 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3748 << 0;
3749 return true;
3750 }
3751
3752 // Check whether the two declarations might declare the same function or
3753 // function template.
3754 if (FunctionTemplateDecl *NewTemplate =
3755 New->getDescribedFunctionTemplate()) {
3756 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3757 New: NewTemplate))
3758 return true;
3759 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3760 ->getAsFunction();
3761 } else {
3762 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3763 return true;
3764 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3765 }
3766 } else {
3767 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3768 << New->getDeclName();
3769 notePreviousDefinition(Old: OldD, New: New->getLocation());
3770 return true;
3771 }
3772 }
3773
3774 // If the old declaration was found in an inline namespace and the new
3775 // declaration was qualified, update the DeclContext to match.
3776 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3777
3778 // If the old declaration is invalid, just give up here.
3779 if (Old->isInvalidDecl())
3780 return true;
3781
3782 // Disallow redeclaration of some builtins.
3783 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3784 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3785 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3786 << Old << Old->getType();
3787 return true;
3788 }
3789
3790 diag::kind PrevDiag;
3791 SourceLocation OldLocation;
3792 std::tie(args&: PrevDiag, args&: OldLocation) =
3793 getNoteDiagForInvalidRedeclaration(Old, New);
3794
3795 // Don't complain about this if we're in GNU89 mode and the old function
3796 // is an extern inline function.
3797 // Don't complain about specializations. They are not supposed to have
3798 // storage classes.
3799 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3800 New->getStorageClass() == SC_Static &&
3801 Old->hasExternalFormalLinkage() &&
3802 !New->getTemplateSpecializationInfo() &&
3803 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3804 if (getLangOpts().MicrosoftExt) {
3805 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3806 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3807 } else {
3808 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
3809 << New << /*MixedLinkageUB=*/false;
3810 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3811 return true;
3812 }
3813 }
3814
3815 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3816 if (!Old->hasAttr<InternalLinkageAttr>()) {
3817 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3818 << ILA;
3819 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3820 New->dropAttr<InternalLinkageAttr>();
3821 }
3822
3823 if (auto *EA = New->getAttr<ErrorAttr>()) {
3824 if (!Old->hasAttr<ErrorAttr>()) {
3825 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3826 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3827 New->dropAttr<ErrorAttr>();
3828 }
3829 }
3830
3831 if (CheckRedeclarationInModule(New, Old))
3832 return true;
3833
3834 if (!getLangOpts().CPlusPlus) {
3835 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3836 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3837 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3838 << New << OldOvl;
3839
3840 // Try our best to find a decl that actually has the overloadable
3841 // attribute for the note. In most cases (e.g. programs with only one
3842 // broken declaration/definition), this won't matter.
3843 //
3844 // FIXME: We could do this if we juggled some extra state in
3845 // OverloadableAttr, rather than just removing it.
3846 const Decl *DiagOld = Old;
3847 if (OldOvl) {
3848 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3849 const auto *A = D->getAttr<OverloadableAttr>();
3850 return A && !A->isImplicit();
3851 });
3852 // If we've implicitly added *all* of the overloadable attrs to this
3853 // chain, emitting a "previous redecl" note is pointless.
3854 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3855 }
3856
3857 if (DiagOld)
3858 Diag(Loc: DiagOld->getLocation(),
3859 DiagID: diag::note_attribute_overloadable_prev_overload)
3860 << OldOvl;
3861
3862 if (OldOvl)
3863 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3864 else
3865 New->dropAttr<OverloadableAttr>();
3866 }
3867 }
3868
3869 // It is not permitted to redeclare an SME function with different SME
3870 // attributes.
3871 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3872 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3873 << New->getType() << Old->getType();
3874 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3875 return true;
3876 }
3877
3878 // If a function is first declared with a calling convention, but is later
3879 // declared or defined without one, all following decls assume the calling
3880 // convention of the first.
3881 //
3882 // It's OK if a function is first declared without a calling convention,
3883 // but is later declared or defined with the default calling convention.
3884 //
3885 // To test if either decl has an explicit calling convention, we look for
3886 // AttributedType sugar nodes on the type as written. If they are missing or
3887 // were canonicalized away, we assume the calling convention was implicit.
3888 //
3889 // Note also that we DO NOT return at this point, because we still have
3890 // other tests to run.
3891 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3892 QualType NewQType = Context.getCanonicalType(T: New->getType());
3893 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3894 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3895 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3896 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3897 bool RequiresAdjustment = false;
3898
3899 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3900 FunctionDecl *First = Old->getFirstDecl();
3901 const FunctionType *FT =
3902 First->getType().getCanonicalType()->castAs<FunctionType>();
3903 FunctionType::ExtInfo FI = FT->getExtInfo();
3904 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3905 if (!NewCCExplicit) {
3906 // Inherit the CC from the previous declaration if it was specified
3907 // there but not here.
3908 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3909 RequiresAdjustment = true;
3910 } else if (Old->getBuiltinID()) {
3911 // Builtin attribute isn't propagated to the new one yet at this point,
3912 // so we check if the old one is a builtin.
3913
3914 // Calling Conventions on a Builtin aren't really useful and setting a
3915 // default calling convention and cdecl'ing some builtin redeclarations is
3916 // common, so warn and ignore the calling convention on the redeclaration.
3917 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3918 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3919 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3920 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3921 RequiresAdjustment = true;
3922 } else {
3923 // Calling conventions aren't compatible, so complain.
3924 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3925 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3926 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3927 << !FirstCCExplicit
3928 << (!FirstCCExplicit ? "" :
3929 FunctionType::getNameForCallConv(CC: FI.getCC()));
3930
3931 // Put the note on the first decl, since it is the one that matters.
3932 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3933 return true;
3934 }
3935 }
3936
3937 // FIXME: diagnose the other way around?
3938 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3939 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3940 RequiresAdjustment = true;
3941 }
3942
3943 // If the declaration is marked with cfi_unchecked_callee but the definition
3944 // isn't, the definition is also cfi_unchecked_callee.
3945 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3946 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3947 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3948 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3949
3950 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3951 EPI2.CFIUncheckedCallee = true;
3952 NewQType = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
3953 Args: FPT2->getParamTypes(), EPI: EPI2);
3954 NewType = cast<FunctionType>(Val&: NewQType);
3955 New->setType(NewQType);
3956 }
3957 }
3958 }
3959
3960 // Merge regparm attribute.
3961 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3962 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3963 if (NewTypeInfo.getHasRegParm()) {
3964 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
3965 << NewType->getRegParmType()
3966 << OldType->getRegParmType();
3967 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3968 return true;
3969 }
3970
3971 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3972 RequiresAdjustment = true;
3973 }
3974
3975 // Merge ns_returns_retained attribute.
3976 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3977 if (NewTypeInfo.getProducesResult()) {
3978 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
3979 << "'ns_returns_retained'";
3980 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3981 return true;
3982 }
3983
3984 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3985 RequiresAdjustment = true;
3986 }
3987
3988 if (OldTypeInfo.getNoCallerSavedRegs() !=
3989 NewTypeInfo.getNoCallerSavedRegs()) {
3990 if (NewTypeInfo.getNoCallerSavedRegs()) {
3991 AnyX86NoCallerSavedRegistersAttr *Attr =
3992 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3993 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
3994 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3995 return true;
3996 }
3997
3998 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3999 RequiresAdjustment = true;
4000 }
4001
4002 if (RequiresAdjustment) {
4003 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
4004 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
4005 New->setType(QualType(AdjustedType, 0));
4006 NewQType = Context.getCanonicalType(T: New->getType());
4007 }
4008
4009 // If this redeclaration makes the function inline, we may need to add it to
4010 // UndefinedButUsed.
4011 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4012 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
4013 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4014 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4015 y: SourceLocation()));
4016
4017 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4018 // about it.
4019 if (New->hasAttr<GNUInlineAttr>() &&
4020 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4021 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
4022 }
4023
4024 // If pass_object_size params don't match up perfectly, this isn't a valid
4025 // redeclaration.
4026 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4027 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
4028 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
4029 << New->getDeclName();
4030 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4031 return true;
4032 }
4033
4034 QualType OldQTypeForComparison = OldQType;
4035 if (Context.hasAnyFunctionEffects()) {
4036 const auto OldFX = Old->getFunctionEffects();
4037 const auto NewFX = New->getFunctionEffects();
4038 if (OldFX != NewFX) {
4039 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4040 for (const auto &Diff : Diffs) {
4041 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
4042 Diag(Loc: New->getLocation(),
4043 DiagID: diag::warn_mismatched_func_effect_redeclaration)
4044 << Diff.effectName();
4045 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4046 }
4047 }
4048 // Following a warning, we could skip merging effects from the previous
4049 // declaration, but that would trigger an additional "conflicting types"
4050 // error.
4051 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4052 FunctionEffectSet::Conflicts MergeErrs;
4053 FunctionEffectSet MergedFX =
4054 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
4055 if (!MergeErrs.empty())
4056 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
4057 OldLoc: Old->getLocation());
4058
4059 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4060 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4061 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
4062 Args: NewFPT->getParamTypes(), EPI);
4063
4064 New->setType(ModQT);
4065 NewQType = New->getType();
4066
4067 // Revise OldQTForComparison to include the merged effects,
4068 // so as not to fail due to differences later.
4069 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4070 EPI = OldFPT->getExtProtoInfo();
4071 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4072 OldQTypeForComparison = Context.getFunctionType(
4073 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
4074 }
4075 if (OldFX.empty()) {
4076 // A redeclaration may add the attribute to a previously seen function
4077 // body which needs to be verified.
4078 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
4079 }
4080 }
4081 }
4082 }
4083
4084 if (getLangOpts().CPlusPlus) {
4085 OldQType = Context.getCanonicalType(T: Old->getType());
4086 NewQType = Context.getCanonicalType(T: New->getType());
4087
4088 // Go back to the type source info to compare the declared return types,
4089 // per C++1y [dcl.type.auto]p13:
4090 // Redeclarations or specializations of a function or function template
4091 // with a declared return type that uses a placeholder type shall also
4092 // use that placeholder, not a deduced type.
4093 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4094 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4095 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
4096 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
4097 OldT: OldDeclaredReturnType)) {
4098 QualType ResQT;
4099 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4100 OldDeclaredReturnType->isObjCObjectPointerType())
4101 // FIXME: This does the wrong thing for a deduced return type.
4102 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4103 if (ResQT.isNull()) {
4104 if (New->isCXXClassMember() && New->isOutOfLine())
4105 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
4106 << New << New->getReturnTypeSourceRange();
4107 else if (Old->isExternC() && New->isExternC() &&
4108 !Old->hasAttr<OverloadableAttr>() &&
4109 !New->hasAttr<OverloadableAttr>())
4110 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4111 else
4112 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
4113 << New->getReturnTypeSourceRange();
4114 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
4115 << Old->getReturnTypeSourceRange();
4116 return true;
4117 }
4118 else
4119 NewQType = ResQT;
4120 }
4121
4122 QualType OldReturnType = OldType->getReturnType();
4123 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
4124 if (OldReturnType != NewReturnType) {
4125 // If this function has a deduced return type and has already been
4126 // defined, copy the deduced value from the old declaration.
4127 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4128 if (OldAT && OldAT->isDeduced()) {
4129 QualType DT = OldAT->getDeducedType();
4130 if (DT.isNull()) {
4131 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
4132 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
4133 } else {
4134 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
4135 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
4136 }
4137 }
4138 }
4139
4140 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
4141 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
4142 if (OldMethod && NewMethod) {
4143 // Preserve triviality.
4144 NewMethod->setTrivial(OldMethod->isTrivial());
4145
4146 // MSVC allows explicit template specialization at class scope:
4147 // 2 CXXMethodDecls referring to the same function will be injected.
4148 // We don't want a redeclaration error.
4149 bool IsClassScopeExplicitSpecialization =
4150 OldMethod->isFunctionTemplateSpecialization() &&
4151 NewMethod->isFunctionTemplateSpecialization();
4152 bool isFriend = NewMethod->getFriendObjectKind();
4153
4154 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4155 !IsClassScopeExplicitSpecialization) {
4156 // -- Member function declarations with the same name and the
4157 // same parameter types cannot be overloaded if any of them
4158 // is a static member function declaration.
4159 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4160 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4161 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4162 return true;
4163 }
4164
4165 // C++ [class.mem]p1:
4166 // [...] A member shall not be declared twice in the
4167 // member-specification, except that a nested class or member
4168 // class template can be declared and then later defined.
4169 if (!inTemplateInstantiation()) {
4170 unsigned NewDiag;
4171 if (isa<CXXConstructorDecl>(Val: OldMethod))
4172 NewDiag = diag::err_constructor_redeclared;
4173 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4174 NewDiag = diag::err_destructor_redeclared;
4175 else if (isa<CXXConversionDecl>(Val: NewMethod))
4176 NewDiag = diag::err_conv_function_redeclared;
4177 else
4178 NewDiag = diag::err_member_redeclared;
4179
4180 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4181 } else {
4182 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4183 << New << New->getType();
4184 }
4185 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4186 return true;
4187
4188 // Complain if this is an explicit declaration of a special
4189 // member that was initially declared implicitly.
4190 //
4191 // As an exception, it's okay to befriend such methods in order
4192 // to permit the implicit constructor/destructor/operator calls.
4193 } else if (OldMethod->isImplicit()) {
4194 if (isFriend) {
4195 NewMethod->setImplicit();
4196 } else {
4197 Diag(Loc: NewMethod->getLocation(),
4198 DiagID: diag::err_definition_of_implicitly_declared_member)
4199 << New << OldMethod->getSpecialMemberKind();
4200 return true;
4201 }
4202 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4203 Diag(Loc: NewMethod->getLocation(),
4204 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4205 << OldMethod->getSpecialMemberKind();
4206 return true;
4207 }
4208 }
4209
4210 // C++1z [over.load]p2
4211 // Certain function declarations cannot be overloaded:
4212 // -- Function declarations that differ only in the return type,
4213 // the exception specification, or both cannot be overloaded.
4214
4215 // Check the exception specifications match. This may recompute the type of
4216 // both Old and New if it resolved exception specifications, so grab the
4217 // types again after this. Because this updates the type, we do this before
4218 // any of the other checks below, which may update the "de facto" NewQType
4219 // but do not necessarily update the type of New.
4220 if (CheckEquivalentExceptionSpec(Old, New))
4221 return true;
4222
4223 // C++11 [dcl.attr.noreturn]p1:
4224 // The first declaration of a function shall specify the noreturn
4225 // attribute if any declaration of that function specifies the noreturn
4226 // attribute.
4227 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4228 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4229 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4230 << NRA;
4231 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4232 }
4233
4234 // C++11 [dcl.attr.depend]p2:
4235 // The first declaration of a function shall specify the
4236 // carries_dependency attribute for its declarator-id if any declaration
4237 // of the function specifies the carries_dependency attribute.
4238 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4239 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4240 Diag(Loc: CDA->getLocation(),
4241 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4242 Diag(Loc: Old->getFirstDecl()->getLocation(),
4243 DiagID: diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4244 }
4245
4246 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4247 // When a function is declared with SYCL_EXTERNAL, that macro must be
4248 // used on the first declaration of that function in the translation unit.
4249 // Redeclarations of the function in the same translation unit may
4250 // optionally use SYCL_EXTERNAL, but this is not required.
4251 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4252 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4253 Diag(Loc: SEA->getLocation(), DiagID: diag::warn_sycl_external_missing_on_first_decl)
4254 << SEA;
4255 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4256 }
4257
4258 // (C++98 8.3.5p3):
4259 // All declarations for a function shall agree exactly in both the
4260 // return type and the parameter-type-list.
4261 // We also want to respect all the extended bits except noreturn.
4262
4263 // noreturn should now match unless the old type info didn't have it.
4264 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4265 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4266 const FunctionType *OldTypeForComparison
4267 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4268 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4269 assert(OldQTypeForComparison.isCanonical());
4270 }
4271
4272 if (haveIncompatibleLanguageLinkages(Old, New)) {
4273 // As a special case, retain the language linkage from previous
4274 // declarations of a friend function as an extension.
4275 //
4276 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4277 // and is useful because there's otherwise no way to specify language
4278 // linkage within class scope.
4279 //
4280 // Check cautiously as the friend object kind isn't yet complete.
4281 if (New->getFriendObjectKind() != Decl::FOK_None) {
4282 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4283 Diag(Loc: OldLocation, DiagID: PrevDiag);
4284 } else {
4285 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4286 Diag(Loc: OldLocation, DiagID: PrevDiag);
4287 return true;
4288 }
4289 }
4290
4291 // HLSL check parameters for matching ABI specifications.
4292 if (getLangOpts().HLSL) {
4293 if (HLSL().CheckCompatibleParameterABI(New, Old))
4294 return true;
4295
4296 // If no errors are generated when checking parameter ABIs we can check if
4297 // the two declarations have the same type ignoring the ABIs and if so,
4298 // the declarations can be merged. This case for merging is only valid in
4299 // HLSL because there are no valid cases of merging mismatched parameter
4300 // ABIs except the HLSL implicit in and explicit in.
4301 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4302 U: NewQType))
4303 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4304 // Fall through for conflicting redeclarations and redefinitions.
4305 }
4306
4307 // If the function types are compatible, merge the declarations. Ignore the
4308 // exception specifier because it was already checked above in
4309 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4310 // about incompatible types under -fms-compatibility.
4311 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4312 U: NewQType))
4313 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4314
4315 // If the types are imprecise (due to dependent constructs in friends or
4316 // local extern declarations), it's OK if they differ. We'll check again
4317 // during instantiation.
4318 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4319 return false;
4320
4321 // Fall through for conflicting redeclarations and redefinitions.
4322 }
4323
4324 // C: Function types need to be compatible, not identical. This handles
4325 // duplicate function decls like "void f(int); void f(enum X);" properly.
4326 if (!getLangOpts().CPlusPlus) {
4327 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4328 // type is specified by a function definition that contains a (possibly
4329 // empty) identifier list, both shall agree in the number of parameters
4330 // and the type of each parameter shall be compatible with the type that
4331 // results from the application of default argument promotions to the
4332 // type of the corresponding identifier. ...
4333 // This cannot be handled by ASTContext::typesAreCompatible() because that
4334 // doesn't know whether the function type is for a definition or not when
4335 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4336 // we need to cover here is that the number of arguments agree as the
4337 // default argument promotion rules were already checked by
4338 // ASTContext::typesAreCompatible().
4339 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4340 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4341 if (Old->hasInheritedPrototype())
4342 Old = Old->getCanonicalDecl();
4343 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4344 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4345 return true;
4346 }
4347
4348 // If we are merging two functions where only one of them has a prototype,
4349 // we may have enough information to decide to issue a diagnostic that the
4350 // function without a prototype will change behavior in C23. This handles
4351 // cases like:
4352 // void i(); void i(int j);
4353 // void i(int j); void i();
4354 // void i(); void i(int j) {}
4355 // See ActOnFinishFunctionBody() for other cases of the behavior change
4356 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4357 // type without a prototype.
4358 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4359 !New->isImplicit() && !Old->isImplicit()) {
4360 const FunctionDecl *WithProto, *WithoutProto;
4361 if (New->hasWrittenPrototype()) {
4362 WithProto = New;
4363 WithoutProto = Old;
4364 } else {
4365 WithProto = Old;
4366 WithoutProto = New;
4367 }
4368
4369 if (WithProto->getNumParams() != 0) {
4370 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4371 // The one without the prototype will be changing behavior in C23, so
4372 // warn about that one so long as it's a user-visible declaration.
4373 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4374 if (WithoutProto == New)
4375 IsWithoutProtoADef = NewDeclIsDefn;
4376 else
4377 IsWithProtoADef = NewDeclIsDefn;
4378 Diag(Loc: WithoutProto->getLocation(),
4379 DiagID: diag::warn_non_prototype_changes_behavior)
4380 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4381 << (WithoutProto == Old) << IsWithProtoADef;
4382
4383 // The reason the one without the prototype will be changing behavior
4384 // is because of the one with the prototype, so note that so long as
4385 // it's a user-visible declaration. There is one exception to this:
4386 // when the new declaration is a definition without a prototype, the
4387 // old declaration with a prototype is not the cause of the issue,
4388 // and that does not need to be noted because the one with a
4389 // prototype will not change behavior in C23.
4390 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4391 !IsWithoutProtoADef)
4392 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4393 }
4394 }
4395 }
4396
4397 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4398 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4399 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4400 const FunctionProtoType *OldProto = nullptr;
4401 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4402 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4403 // The old declaration provided a function prototype, but the
4404 // new declaration does not. Merge in the prototype.
4405 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4406 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4407 Args: OldProto->getParamTypes(),
4408 EPI: OldProto->getExtProtoInfo());
4409 New->setType(NewQType);
4410 New->setHasInheritedPrototype();
4411
4412 // Synthesize parameters with the same types.
4413 SmallVector<ParmVarDecl *, 16> Params;
4414 for (const auto &ParamType : OldProto->param_types()) {
4415 ParmVarDecl *Param = ParmVarDecl::Create(
4416 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4417 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4418 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4419 Param->setImplicit();
4420 Params.push_back(Elt: Param);
4421 }
4422
4423 New->setParams(Params);
4424 }
4425
4426 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4427 }
4428 }
4429
4430 // Check if the function types are compatible when pointer size address
4431 // spaces are ignored.
4432 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4433 return false;
4434
4435 // GNU C permits a K&R definition to follow a prototype declaration
4436 // if the declared types of the parameters in the K&R definition
4437 // match the types in the prototype declaration, even when the
4438 // promoted types of the parameters from the K&R definition differ
4439 // from the types in the prototype. GCC then keeps the types from
4440 // the prototype.
4441 //
4442 // If a variadic prototype is followed by a non-variadic K&R definition,
4443 // the K&R definition becomes variadic. This is sort of an edge case, but
4444 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4445 // C99 6.9.1p8.
4446 if (!getLangOpts().CPlusPlus &&
4447 Old->hasPrototype() && !New->hasPrototype() &&
4448 New->getType()->getAs<FunctionProtoType>() &&
4449 Old->getNumParams() == New->getNumParams()) {
4450 SmallVector<QualType, 16> ArgTypes;
4451 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4452 const FunctionProtoType *OldProto
4453 = Old->getType()->getAs<FunctionProtoType>();
4454 const FunctionProtoType *NewProto
4455 = New->getType()->getAs<FunctionProtoType>();
4456
4457 // Determine whether this is the GNU C extension.
4458 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4459 NewProto->getReturnType());
4460 bool LooseCompatible = !MergedReturn.isNull();
4461 for (unsigned Idx = 0, End = Old->getNumParams();
4462 LooseCompatible && Idx != End; ++Idx) {
4463 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4464 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4465 if (Context.typesAreCompatible(T1: OldParm->getType(),
4466 T2: NewProto->getParamType(i: Idx))) {
4467 ArgTypes.push_back(Elt: NewParm->getType());
4468 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4469 T2: NewParm->getType(),
4470 /*CompareUnqualified=*/true)) {
4471 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4472 .PromotedType: NewProto->getParamType(i: Idx) };
4473 Warnings.push_back(Elt: Warn);
4474 ArgTypes.push_back(Elt: NewParm->getType());
4475 } else
4476 LooseCompatible = false;
4477 }
4478
4479 if (LooseCompatible) {
4480 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4481 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4482 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4483 << Warnings[Warn].PromotedType
4484 << Warnings[Warn].OldParm->getType();
4485 if (Warnings[Warn].OldParm->getLocation().isValid())
4486 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4487 DiagID: diag::note_previous_declaration);
4488 }
4489
4490 if (MergeTypeWithOld)
4491 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4492 EPI: OldProto->getExtProtoInfo()));
4493 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4494 }
4495
4496 // Fall through to diagnose conflicting types.
4497 }
4498
4499 // A function that has already been declared has been redeclared or
4500 // defined with a different type; show an appropriate diagnostic.
4501
4502 // If the previous declaration was an implicitly-generated builtin
4503 // declaration, then at the very least we should use a specialized note.
4504 unsigned BuiltinID;
4505 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4506 // If it's actually a library-defined builtin function like 'malloc'
4507 // or 'printf', just warn about the incompatible redeclaration.
4508 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4509 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4510 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4511 << Old << Old->getType();
4512 return false;
4513 }
4514
4515 PrevDiag = diag::note_previous_builtin_declaration;
4516 }
4517
4518 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4519 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4520 return true;
4521}
4522
4523bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4524 Scope *S, bool MergeTypeWithOld) {
4525 // Merge the attributes
4526 mergeDeclAttributes(New, Old);
4527
4528 // Merge "pure" flag.
4529 if (Old->isPureVirtual())
4530 New->setIsPureVirtual();
4531
4532 // Merge "used" flag.
4533 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4534 New->setIsUsed();
4535
4536 // Merge attributes from the parameters. These can mismatch with K&R
4537 // declarations.
4538 if (New->getNumParams() == Old->getNumParams())
4539 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4540 ParmVarDecl *NewParam = New->getParamDecl(i);
4541 ParmVarDecl *OldParam = Old->getParamDecl(i);
4542 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4543 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4544 }
4545
4546 if (getLangOpts().CPlusPlus)
4547 return MergeCXXFunctionDecl(New, Old, S);
4548
4549 // Merge the function types so the we get the composite types for the return
4550 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4551 // was visible.
4552 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4553 if (!Merged.isNull() && MergeTypeWithOld)
4554 New->setType(Merged);
4555
4556 return false;
4557}
4558
4559void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4560 ObjCMethodDecl *oldMethod) {
4561 // Merge the attributes, including deprecated/unavailable
4562 AvailabilityMergeKind MergeKind =
4563 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4564 ? (oldMethod->isOptional()
4565 ? AvailabilityMergeKind::OptionalProtocolImplementation
4566 : AvailabilityMergeKind::ProtocolImplementation)
4567 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4568 ? AvailabilityMergeKind::Redeclaration
4569 : AvailabilityMergeKind::Override;
4570
4571 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4572
4573 // Merge attributes from the parameters.
4574 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4575 oe = oldMethod->param_end();
4576 for (ObjCMethodDecl::param_iterator
4577 ni = newMethod->param_begin(), ne = newMethod->param_end();
4578 ni != ne && oi != oe; ++ni, ++oi)
4579 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4580
4581 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4582}
4583
4584static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4585 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4586
4587 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4588 ? diag::err_redefinition_different_type
4589 : diag::err_redeclaration_different_type)
4590 << New->getDeclName() << New->getType() << Old->getType();
4591
4592 diag::kind PrevDiag;
4593 SourceLocation OldLocation;
4594 std::tie(args&: PrevDiag, args&: OldLocation)
4595 = getNoteDiagForInvalidRedeclaration(Old, New);
4596 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4597 New->setInvalidDecl();
4598}
4599
4600void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4601 bool MergeTypeWithOld) {
4602 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4603 return;
4604
4605 QualType MergedT;
4606 if (getLangOpts().CPlusPlus) {
4607 if (New->getType()->isUndeducedType()) {
4608 // We don't know what the new type is until the initializer is attached.
4609 return;
4610 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4611 // These could still be something that needs exception specs checked.
4612 return MergeVarDeclExceptionSpecs(New, Old);
4613 }
4614 // C++ [basic.link]p10:
4615 // [...] the types specified by all declarations referring to a given
4616 // object or function shall be identical, except that declarations for an
4617 // array object can specify array types that differ by the presence or
4618 // absence of a major array bound (8.3.4).
4619 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4620 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4621 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4622
4623 // We are merging a variable declaration New into Old. If it has an array
4624 // bound, and that bound differs from Old's bound, we should diagnose the
4625 // mismatch.
4626 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4627 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4628 PrevVD = PrevVD->getPreviousDecl()) {
4629 QualType PrevVDTy = PrevVD->getType();
4630 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4631 continue;
4632
4633 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4634 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4635 }
4636 }
4637
4638 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4639 if (Context.hasSameType(T1: OldArray->getElementType(),
4640 T2: NewArray->getElementType()))
4641 MergedT = New->getType();
4642 }
4643 // FIXME: Check visibility. New is hidden but has a complete type. If New
4644 // has no array bound, it should not inherit one from Old, if Old is not
4645 // visible.
4646 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4647 if (Context.hasSameType(T1: OldArray->getElementType(),
4648 T2: NewArray->getElementType()))
4649 MergedT = Old->getType();
4650 }
4651 }
4652 else if (New->getType()->isObjCObjectPointerType() &&
4653 Old->getType()->isObjCObjectPointerType()) {
4654 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4655 Old->getType());
4656 }
4657 } else {
4658 // C 6.2.7p2:
4659 // All declarations that refer to the same object or function shall have
4660 // compatible type.
4661 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4662 }
4663 if (MergedT.isNull()) {
4664 // It's OK if we couldn't merge types if either type is dependent, for a
4665 // block-scope variable. In other cases (static data members of class
4666 // templates, variable templates, ...), we require the types to be
4667 // equivalent.
4668 // FIXME: The C++ standard doesn't say anything about this.
4669 if ((New->getType()->isDependentType() ||
4670 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4671 // If the old type was dependent, we can't merge with it, so the new type
4672 // becomes dependent for now. We'll reproduce the original type when we
4673 // instantiate the TypeSourceInfo for the variable.
4674 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4675 New->setType(Context.DependentTy);
4676 return;
4677 }
4678 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4679 }
4680
4681 // Don't actually update the type on the new declaration if the old
4682 // declaration was an extern declaration in a different scope.
4683 if (MergeTypeWithOld)
4684 New->setType(MergedT);
4685}
4686
4687static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4688 LookupResult &Previous) {
4689 // C11 6.2.7p4:
4690 // For an identifier with internal or external linkage declared
4691 // in a scope in which a prior declaration of that identifier is
4692 // visible, if the prior declaration specifies internal or
4693 // external linkage, the type of the identifier at the later
4694 // declaration becomes the composite type.
4695 //
4696 // If the variable isn't visible, we do not merge with its type.
4697 if (Previous.isShadowed())
4698 return false;
4699
4700 if (S.getLangOpts().CPlusPlus) {
4701 // C++11 [dcl.array]p3:
4702 // If there is a preceding declaration of the entity in the same
4703 // scope in which the bound was specified, an omitted array bound
4704 // is taken to be the same as in that earlier declaration.
4705 return NewVD->isPreviousDeclInSameBlockScope() ||
4706 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4707 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4708 } else {
4709 // If the old declaration was function-local, don't merge with its
4710 // type unless we're in the same function.
4711 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4712 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4713 }
4714}
4715
4716void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4717 // If the new decl is already invalid, don't do any other checking.
4718 if (New->isInvalidDecl())
4719 return;
4720
4721 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4722 return;
4723
4724 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4725
4726 // Verify the old decl was also a variable or variable template.
4727 VarDecl *Old = nullptr;
4728 VarTemplateDecl *OldTemplate = nullptr;
4729 if (Previous.isSingleResult()) {
4730 if (NewTemplate) {
4731 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4732 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4733
4734 if (auto *Shadow =
4735 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4736 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4737 return New->setInvalidDecl();
4738 } else {
4739 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4740
4741 if (auto *Shadow =
4742 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4743 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4744 return New->setInvalidDecl();
4745 }
4746 }
4747 if (!Old) {
4748 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4749 << New->getDeclName();
4750 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4751 New: New->getLocation());
4752 return New->setInvalidDecl();
4753 }
4754
4755 // If the old declaration was found in an inline namespace and the new
4756 // declaration was qualified, update the DeclContext to match.
4757 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4758
4759 // Ensure the template parameters are compatible.
4760 if (NewTemplate &&
4761 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4762 Old: OldTemplate->getTemplateParameters(),
4763 /*Complain=*/true, Kind: TPL_TemplateMatch))
4764 return New->setInvalidDecl();
4765
4766 // C++ [class.mem]p1:
4767 // A member shall not be declared twice in the member-specification [...]
4768 //
4769 // Here, we need only consider static data members.
4770 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4771 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4772 << New->getIdentifier();
4773 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4774 New->setInvalidDecl();
4775 }
4776
4777 if (NewTemplate && OldTemplate)
4778 mergeDeclAttributes(New: NewTemplate, Old: OldTemplate);
4779
4780 mergeDeclAttributes(New, Old);
4781
4782 // Warn if an already-defined variable is made a weak_import in a subsequent
4783 // declaration
4784 if (New->hasAttr<WeakImportAttr>())
4785 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4786 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4787 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4788 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4789 // Remove weak_import attribute on new declaration.
4790 New->dropAttr<WeakImportAttr>();
4791 break;
4792 }
4793 }
4794
4795 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4796 if (!Old->hasAttr<InternalLinkageAttr>()) {
4797 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4798 << ILA;
4799 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4800 New->dropAttr<InternalLinkageAttr>();
4801 }
4802
4803 // Merge the types.
4804 VarDecl *MostRecent = Old->getMostRecentDecl();
4805 if (MostRecent != Old) {
4806 MergeVarDeclTypes(New, Old: MostRecent,
4807 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4808 if (New->isInvalidDecl())
4809 return;
4810 }
4811
4812 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4813 if (New->isInvalidDecl())
4814 return;
4815
4816 diag::kind PrevDiag;
4817 SourceLocation OldLocation;
4818 std::tie(args&: PrevDiag, args&: OldLocation) =
4819 getNoteDiagForInvalidRedeclaration(Old, New);
4820
4821 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4822 if (New->getStorageClass() == SC_Static &&
4823 !New->isStaticDataMember() &&
4824 Old->hasExternalFormalLinkage()) {
4825 if (getLangOpts().MicrosoftExt) {
4826 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4827 << New->getDeclName();
4828 Diag(Loc: OldLocation, DiagID: PrevDiag);
4829 } else {
4830 // This is the same internal/external linkage conflict as C2y 6.7.1p7;
4831 // before C2y it was undefined behavior (C11 6.2.2p7), so note that in
4832 // the older C language modes.
4833 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4834 << New->getDeclName()
4835 << (!getLangOpts().CPlusPlus && !getLangOpts().C2y);
4836 Diag(Loc: OldLocation, DiagID: PrevDiag);
4837 return New->setInvalidDecl();
4838 }
4839 }
4840
4841 // C2y 6.7.1p7: an identifier shall not appear with both internal and
4842 // external linkage within a translation unit. Before C2y this was UB
4843 // (C11 6.2.2p7).
4844 //
4845 // In C, a local shadow prevents a block-scope extern from inheriting the
4846 // file-scope static's internal linkage (C2y 6.2.2p6), so it defaults to
4847 // external linkage, creating the conflict.
4848 //
4849 // In C++, block-scope extern declarations target the enclosing namespace
4850 // scope ([dcl.meaning.general]/3.5), bypassing local shadows entirely, so
4851 // the extern always inherits internal linkage. No conflict arises.
4852 if (!getLangOpts().CPlusPlus && New->isLocalVarDecl() &&
4853 New->hasExternalStorage() && Previous.isShadowed() &&
4854 Old->getFormalLinkage() == Linkage::Internal) {
4855 Diag(Loc: New->getLocation(), DiagID: diag::err_internal_extern_mismatch)
4856 << New->getDeclName() << getLangOpts().C2y;
4857 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
4858 return New->setInvalidDecl();
4859 }
4860
4861 // C99 6.2.2p4:
4862 // For an identifier declared with the storage-class specifier
4863 // extern in a scope in which a prior declaration of that
4864 // identifier is visible,23) if the prior declaration specifies
4865 // internal or external linkage, the linkage of the identifier at
4866 // the later declaration is the same as the linkage specified at
4867 // the prior declaration. If no prior declaration is visible, or
4868 // if the prior declaration specifies no linkage, then the
4869 // identifier has external linkage.
4870 if (New->hasExternalStorage() && Old->hasLinkage())
4871 /* Okay */;
4872 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4873 !New->isStaticDataMember() &&
4874 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4875 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4876 Diag(Loc: OldLocation, DiagID: PrevDiag);
4877 return New->setInvalidDecl();
4878 }
4879
4880 // Check if extern is followed by non-extern and vice-versa.
4881 if (New->hasExternalStorage() &&
4882 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4883 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4884 Diag(Loc: OldLocation, DiagID: PrevDiag);
4885 return New->setInvalidDecl();
4886 }
4887 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4888 !New->hasExternalStorage()) {
4889 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4890 Diag(Loc: OldLocation, DiagID: PrevDiag);
4891 return New->setInvalidDecl();
4892 }
4893
4894 if (CheckRedeclarationInModule(New, Old))
4895 return;
4896
4897 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4898
4899 // FIXME: The test for external storage here seems wrong? We still
4900 // need to check for mismatches.
4901 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4902 // Don't complain about out-of-line definitions of static members.
4903 !(Old->getLexicalDeclContext()->isRecord() &&
4904 !New->getLexicalDeclContext()->isRecord())) {
4905 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4906 Diag(Loc: OldLocation, DiagID: PrevDiag);
4907 return New->setInvalidDecl();
4908 }
4909
4910 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4911 if (VarDecl *Def = Old->getDefinition()) {
4912 // C++1z [dcl.fcn.spec]p4:
4913 // If the definition of a variable appears in a translation unit before
4914 // its first declaration as inline, the program is ill-formed.
4915 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4916 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4917 }
4918 }
4919
4920 // If this redeclaration makes the variable inline, we may need to add it to
4921 // UndefinedButUsed.
4922 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4923 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4924 !Old->isInAnotherModuleUnit())
4925 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4926 y: SourceLocation()));
4927
4928 if (New->getTLSKind() != Old->getTLSKind()) {
4929 if (!Old->getTLSKind()) {
4930 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4931 Diag(Loc: OldLocation, DiagID: PrevDiag);
4932 } else if (!New->getTLSKind()) {
4933 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4934 Diag(Loc: OldLocation, DiagID: PrevDiag);
4935 } else {
4936 // Do not allow redeclaration to change the variable between requiring
4937 // static and dynamic initialization.
4938 // FIXME: GCC allows this, but uses the TLS keyword on the first
4939 // declaration to determine the kind. Do we need to be compatible here?
4940 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4941 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4942 Diag(Loc: OldLocation, DiagID: PrevDiag);
4943 }
4944 }
4945
4946 // C++ doesn't have tentative definitions, so go right ahead and check here.
4947 if (getLangOpts().CPlusPlus) {
4948 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4949 Old->getCanonicalDecl()->isConstexpr()) {
4950 // This definition won't be a definition any more once it's been merged.
4951 Diag(Loc: New->getLocation(),
4952 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4953 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4954 VarDecl *Def = Old->getDefinition();
4955 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4956 return;
4957 if (Old->isInvalidDecl())
4958 New->setInvalidDecl();
4959 }
4960 } else {
4961 // C++ may not have a tentative definition rule, but it has a different
4962 // rule about what constitutes a definition in the first place. See
4963 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4964 // contains the extern specifier and doesn't have an initializer, it's fine
4965 // in C++.
4966 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4967 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4968 << New;
4969 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4970 }
4971 }
4972
4973 if (haveIncompatibleLanguageLinkages(Old, New)) {
4974 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4975 Diag(Loc: OldLocation, DiagID: PrevDiag);
4976 New->setInvalidDecl();
4977 return;
4978 }
4979
4980 // Merge "used" flag.
4981 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4982 New->setIsUsed();
4983
4984 // Keep a chain of previous declarations.
4985 New->setPreviousDecl(Old);
4986 if (NewTemplate)
4987 NewTemplate->setPreviousDecl(OldTemplate);
4988
4989 // Inherit access appropriately.
4990 New->setAccess(Old->getAccess());
4991 if (NewTemplate)
4992 NewTemplate->setAccess(New->getAccess());
4993
4994 if (Old->isInline())
4995 New->setImplicitlyInline();
4996}
4997
4998void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4999 SourceManager &SrcMgr = getSourceManager();
5000 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
5001 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
5002 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
5003 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
5004 auto &HSI = PP.getHeaderSearchInfo();
5005 StringRef HdrFilename =
5006 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
5007
5008 auto noteFromModuleOrInclude = [&](Module *Mod,
5009 SourceLocation IncLoc) -> bool {
5010 // Redefinition errors with modules are common with non modular mapped
5011 // headers, example: a non-modular header H in module A that also gets
5012 // included directly in a TU. Pointing twice to the same header/definition
5013 // is confusing, try to get better diagnostics when modules is on.
5014 if (IncLoc.isValid()) {
5015 if (Mod) {
5016 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
5017 << HdrFilename.str() << Mod->getFullModuleName();
5018 if (!Mod->DefinitionLoc.isInvalid())
5019 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
5020 << Mod->getFullModuleName();
5021 } else {
5022 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
5023 << HdrFilename.str();
5024 }
5025 return true;
5026 }
5027
5028 return false;
5029 };
5030
5031 // Is it the same file and same offset? Provide more information on why
5032 // this leads to a redefinition error.
5033 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
5034 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
5035 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
5036 bool EmittedDiag =
5037 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5038 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5039
5040 // If the header has no guards, emit a note suggesting one.
5041 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
5042 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
5043
5044 if (EmittedDiag)
5045 return;
5046 }
5047
5048 // Redefinition coming from different files or couldn't do better above.
5049 if (Old->getLocation().isValid())
5050 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
5051}
5052
5053bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
5054 if (!hasVisibleDefinition(D: Old) &&
5055 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5056 isa<VarTemplateSpecializationDecl>(Val: New) ||
5057 New->getDescribedVarTemplate() ||
5058 !New->getTemplateParameterLists().empty() ||
5059 New->getDeclContext()->isDependentContext() ||
5060 New->hasAttr<SelectAnyAttr>())) {
5061 // The previous definition is hidden, and multiple definitions are
5062 // permitted (in separate TUs). Demote this to a declaration.
5063 New->demoteThisDefinitionToDeclaration();
5064
5065 // Make the canonical definition visible.
5066 if (auto *OldTD = Old->getDescribedVarTemplate())
5067 makeMergedDefinitionVisible(ND: OldTD);
5068 makeMergedDefinitionVisible(ND: Old);
5069 return false;
5070 } else {
5071 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
5072 notePreviousDefinition(Old, New: New->getLocation());
5073 New->setInvalidDecl();
5074 return true;
5075 }
5076}
5077
5078Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5079 DeclSpec &DS,
5080 const ParsedAttributesView &DeclAttrs,
5081 RecordDecl *&AnonRecord) {
5082 return ParsedFreeStandingDeclSpec(
5083 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
5084}
5085
5086// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5087// disambiguate entities defined in different scopes.
5088// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5089// compatibility.
5090// We will pick our mangling number depending on which version of MSVC is being
5091// targeted.
5092static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5093 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
5094 ? S->getMSCurManglingNumber()
5095 : S->getMSLastManglingNumber();
5096}
5097
5098void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5099 if (!Context.getLangOpts().CPlusPlus)
5100 return;
5101
5102 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
5103 // If this tag is the direct child of a class, number it if
5104 // it is anonymous.
5105 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5106 return;
5107 MangleNumberingContext &MCtx =
5108 Context.getManglingNumberContext(DC: Tag->getParent());
5109 Context.setManglingNumber(
5110 ND: Tag, Number: MCtx.getManglingNumber(
5111 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5112 return;
5113 }
5114
5115 // If this tag isn't a direct child of a class, number it if it is local.
5116 MangleNumberingContext *MCtx;
5117 Decl *ManglingContextDecl;
5118 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5119 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
5120 if (MCtx) {
5121 Context.setManglingNumber(
5122 ND: Tag, Number: MCtx->getManglingNumber(
5123 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5124 }
5125}
5126
5127namespace {
5128struct NonCLikeKind {
5129 enum {
5130 None,
5131 BaseClass,
5132 DefaultMemberInit,
5133 Lambda,
5134 Friend,
5135 OtherMember,
5136 Invalid,
5137 } Kind = None;
5138 SourceRange Range;
5139
5140 explicit operator bool() { return Kind != None; }
5141};
5142}
5143
5144/// Determine whether a class is C-like, according to the rules of C++
5145/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5146static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5147 if (RD->isInvalidDecl())
5148 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
5149
5150 // C++ [dcl.typedef]p9: [P1766R1]
5151 // An unnamed class with a typedef name for linkage purposes shall not
5152 //
5153 // -- have any base classes
5154 if (RD->getNumBases())
5155 return {.Kind: NonCLikeKind::BaseClass,
5156 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
5157 RD->bases_end()[-1].getEndLoc())};
5158 bool Invalid = false;
5159 for (Decl *D : RD->decls()) {
5160 // Don't complain about things we already diagnosed.
5161 if (D->isInvalidDecl()) {
5162 Invalid = true;
5163 continue;
5164 }
5165
5166 // -- have any [...] default member initializers
5167 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
5168 if (FD->hasInClassInitializer()) {
5169 auto *Init = FD->getInClassInitializer();
5170 return {.Kind: NonCLikeKind::DefaultMemberInit,
5171 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
5172 }
5173 continue;
5174 }
5175
5176 // FIXME: We don't allow friend declarations. This violates the wording of
5177 // P1766, but not the intent.
5178 if (isa<FriendDecl>(Val: D))
5179 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
5180
5181 // -- declare any members other than non-static data members, member
5182 // enumerations, or member classes,
5183 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
5184 isa<EnumDecl>(Val: D))
5185 continue;
5186 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
5187 if (!MemberRD) {
5188 if (D->isImplicit())
5189 continue;
5190 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
5191 }
5192
5193 // -- contain a lambda-expression,
5194 if (MemberRD->isLambda())
5195 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5196
5197 // and all member classes shall also satisfy these requirements
5198 // (recursively).
5199 if (MemberRD->isThisDeclarationADefinition()) {
5200 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5201 return Kind;
5202 }
5203 }
5204
5205 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5206}
5207
5208void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5209 TypedefNameDecl *NewTD) {
5210 if (TagFromDeclSpec->isInvalidDecl())
5211 return;
5212
5213 // Do nothing if the tag already has a name for linkage purposes.
5214 if (TagFromDeclSpec->hasNameForLinkage())
5215 return;
5216
5217 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5218 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5219
5220 // The type must match the tag exactly; no qualifiers allowed.
5221 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5222 T2: Context.getCanonicalTagType(TD: TagFromDeclSpec))) {
5223 if (getLangOpts().CPlusPlus)
5224 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5225 return;
5226 }
5227
5228 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5229 // An unnamed class with a typedef name for linkage purposes shall [be
5230 // C-like].
5231 //
5232 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5233 // shouldn't happen, but there are constructs that the language rule doesn't
5234 // disallow for which we can't reasonably avoid computing linkage early.
5235 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5236 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5237 : NonCLikeKind();
5238 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5239 if (NonCLike || ChangesLinkage) {
5240 if (NonCLike.Kind == NonCLikeKind::Invalid)
5241 return;
5242
5243 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5244 if (ChangesLinkage) {
5245 // If the linkage changes, we can't accept this as an extension.
5246 if (NonCLike.Kind == NonCLikeKind::None)
5247 DiagID = diag::err_typedef_changes_linkage;
5248 else
5249 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5250 }
5251
5252 SourceLocation FixitLoc =
5253 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5254 llvm::SmallString<40> TextToInsert;
5255 TextToInsert += ' ';
5256 TextToInsert += NewTD->getIdentifier()->getName();
5257
5258 Diag(Loc: FixitLoc, DiagID)
5259 << isa<TypeAliasDecl>(Val: NewTD)
5260 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5261 if (NonCLike.Kind != NonCLikeKind::None) {
5262 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5263 << NonCLike.Kind - 1 << NonCLike.Range;
5264 }
5265 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5266 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5267
5268 if (ChangesLinkage)
5269 return;
5270 }
5271
5272 // Otherwise, set this as the anon-decl typedef for the tag.
5273 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5274
5275 // Now that we have a name for the tag, process API notes again.
5276 ProcessAPINotes(D: TagFromDeclSpec);
5277}
5278
5279static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5280 DeclSpec::TST T = DS.getTypeSpecType();
5281 switch (T) {
5282 case DeclSpec::TST_class:
5283 return 0;
5284 case DeclSpec::TST_struct:
5285 return 1;
5286 case DeclSpec::TST_interface:
5287 return 2;
5288 case DeclSpec::TST_union:
5289 return 3;
5290 case DeclSpec::TST_enum:
5291 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5292 if (ED->isScopedUsingClassTag())
5293 return 5;
5294 if (ED->isScoped())
5295 return 6;
5296 }
5297 return 4;
5298 default:
5299 llvm_unreachable("unexpected type specifier");
5300 }
5301}
5302
5303Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5304 DeclSpec &DS,
5305 const ParsedAttributesView &DeclAttrs,
5306 MultiTemplateParamsArg TemplateParams,
5307 bool IsExplicitInstantiation,
5308 RecordDecl *&AnonRecord,
5309 SourceLocation EllipsisLoc) {
5310 Decl *TagD = nullptr;
5311 TagDecl *Tag = nullptr;
5312 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5313 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5314 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5315 DS.getTypeSpecType() == DeclSpec::TST_union ||
5316 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5317 TagD = DS.getRepAsDecl();
5318
5319 if (!TagD) // We probably had an error
5320 return nullptr;
5321
5322 // Note that the above type specs guarantee that the
5323 // type rep is a Decl, whereas in many of the others
5324 // it's a Type.
5325 if (isa<TagDecl>(Val: TagD))
5326 Tag = cast<TagDecl>(Val: TagD);
5327 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5328 Tag = CTD->getTemplatedDecl();
5329 }
5330
5331 if (Tag) {
5332 handleTagNumbering(Tag, TagScope: S);
5333 Tag->setFreeStanding();
5334 if (Tag->isInvalidDecl())
5335 return Tag;
5336 }
5337
5338 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5339 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5340 // or incomplete types shall not be restrict-qualified."
5341 if (TypeQuals & DeclSpec::TQ_restrict)
5342 Diag(Loc: DS.getRestrictSpecLoc(),
5343 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5344 << DS.getSourceRange();
5345 }
5346
5347 if (DS.isInlineSpecified())
5348 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5349 << getLangOpts().CPlusPlus17;
5350
5351 if (DS.hasConstexprSpecifier()) {
5352 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5353 // and definitions of functions and variables.
5354 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5355 // the declaration of a function or function template
5356 if (Tag)
5357 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5358 << GetDiagnosticTypeSpecifierID(DS)
5359 << static_cast<int>(DS.getConstexprSpecifier());
5360 else if (getLangOpts().C23)
5361 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5362 else
5363 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5364 << static_cast<int>(DS.getConstexprSpecifier());
5365 // Don't emit warnings after this error.
5366 return TagD;
5367 }
5368
5369 DiagnoseFunctionSpecifiers(DS);
5370
5371 if (DS.isFriendSpecified()) {
5372 // If we're dealing with a decl but not a TagDecl, assume that
5373 // whatever routines created it handled the friendship aspect.
5374 if (TagD && !Tag)
5375 return nullptr;
5376 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5377 }
5378
5379 assert(EllipsisLoc.isInvalid() &&
5380 "Friend ellipsis but not friend-specified?");
5381
5382 // Track whether this decl-specifier declares anything.
5383 bool DeclaresAnything = true;
5384
5385 // Handle anonymous struct definitions.
5386 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5387 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5388 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5389 if (getLangOpts().CPlusPlus ||
5390 Record->getDeclContext()->isRecord()) {
5391 // If CurContext is a DeclContext that can contain statements,
5392 // RecursiveASTVisitor won't visit the decls that
5393 // BuildAnonymousStructOrUnion() will put into CurContext.
5394 // Also store them here so that they can be part of the
5395 // DeclStmt that gets created in this case.
5396 // FIXME: Also return the IndirectFieldDecls created by
5397 // BuildAnonymousStructOr union, for the same reason?
5398 if (CurContext->isFunctionOrMethod())
5399 AnonRecord = Record;
5400 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5401 Policy: Context.getPrintingPolicy());
5402 }
5403
5404 DeclaresAnything = false;
5405 }
5406 }
5407
5408 // C11 6.7.2.1p2:
5409 // A struct-declaration that does not declare an anonymous structure or
5410 // anonymous union shall contain a struct-declarator-list.
5411 //
5412 // This rule also existed in C89 and C99; the grammar for struct-declaration
5413 // did not permit a struct-declaration without a struct-declarator-list.
5414 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5415 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5416 // Check for Microsoft C extension: anonymous struct/union member.
5417 // Handle 2 kinds of anonymous struct/union:
5418 // struct STRUCT;
5419 // union UNION;
5420 // and
5421 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5422 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5423 if ((Tag && Tag->getDeclName()) ||
5424 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5425 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Val: Tag)
5426 : DS.getRepAsType().get()->getAsRecordDecl();
5427 if (Record && getLangOpts().MSAnonymousStructs) {
5428 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5429 << Record->isUnion() << DS.getSourceRange();
5430 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5431 }
5432
5433 DeclaresAnything = false;
5434 }
5435 }
5436
5437 // Skip all the checks below if we have a type error.
5438 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5439 (TagD && TagD->isInvalidDecl()))
5440 return TagD;
5441
5442 if (getLangOpts().CPlusPlus &&
5443 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5444 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5445 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5446 !Enum->isInvalidDecl())
5447 DeclaresAnything = false;
5448
5449 if (!DS.isMissingDeclaratorOk()) {
5450 // Customize diagnostic for a typedef missing a name.
5451 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5452 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5453 << DS.getSourceRange();
5454 else
5455 DeclaresAnything = false;
5456 }
5457
5458 if (DS.isModulePrivateSpecified() &&
5459 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5460 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5461 << Tag->getTagKind()
5462 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5463
5464 ActOnDocumentableDecl(D: TagD);
5465
5466 // C 6.7/2:
5467 // A declaration [...] shall declare at least a declarator [...], a tag,
5468 // or the members of an enumeration.
5469 // C++ [dcl.dcl]p3:
5470 // [If there are no declarators], and except for the declaration of an
5471 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5472 // names into the program, or shall redeclare a name introduced by a
5473 // previous declaration.
5474 if (!DeclaresAnything) {
5475 // In C, we allow this as a (popular) extension / bug. Don't bother
5476 // producing further diagnostics for redundant qualifiers after this.
5477 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5478 ? diag::err_no_declarators
5479 : diag::ext_no_declarators)
5480 << DS.getSourceRange();
5481 return TagD;
5482 }
5483
5484 // C++ [dcl.stc]p1:
5485 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5486 // init-declarator-list of the declaration shall not be empty.
5487 // C++ [dcl.fct.spec]p1:
5488 // If a cv-qualifier appears in a decl-specifier-seq, the
5489 // init-declarator-list of the declaration shall not be empty.
5490 //
5491 // Spurious qualifiers here appear to be valid in C.
5492 unsigned DiagID = diag::warn_standalone_specifier;
5493 if (getLangOpts().CPlusPlus)
5494 DiagID = diag::ext_standalone_specifier;
5495
5496 // Note that a linkage-specification sets a storage class, but
5497 // 'extern "C" struct foo;' is actually valid and not theoretically
5498 // useless.
5499 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5500 if (SCS == DeclSpec::SCS_mutable)
5501 // Since mutable is not a viable storage class specifier in C, there is
5502 // no reason to treat it as an extension. Instead, diagnose as an error.
5503 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5504 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5505 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5506 << DeclSpec::getSpecifierName(S: SCS);
5507 }
5508
5509 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5510 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5511 << DeclSpec::getSpecifierName(S: TSCS);
5512 if (DS.getTypeQualifiers()) {
5513 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5514 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5515 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5516 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5517 // Restrict is covered above.
5518 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5519 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5520 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5521 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5522 }
5523
5524 // Warn about ignored type attributes, for example:
5525 // __attribute__((aligned)) struct A;
5526 // Attributes should be placed after tag to apply to type declaration.
5527 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5528 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5529 if (TypeSpecType == DeclSpec::TST_class ||
5530 TypeSpecType == DeclSpec::TST_struct ||
5531 TypeSpecType == DeclSpec::TST_interface ||
5532 TypeSpecType == DeclSpec::TST_union ||
5533 TypeSpecType == DeclSpec::TST_enum) {
5534
5535 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5536 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5537 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5538 DiagnosticId = diag::warn_attribute_ignored;
5539 else if (AL.isRegularKeywordAttribute())
5540 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5541 else
5542 DiagnosticId = diag::warn_declspec_attribute_ignored;
5543 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5544 << AL << GetDiagnosticTypeSpecifierID(DS);
5545 };
5546
5547 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5548 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5549 }
5550 }
5551
5552 return TagD;
5553}
5554
5555/// We are trying to inject an anonymous member into the given scope;
5556/// check if there's an existing declaration that can't be overloaded.
5557///
5558/// \return true if this is a forbidden redeclaration
5559static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5560 DeclContext *Owner,
5561 DeclarationName Name,
5562 SourceLocation NameLoc, bool IsUnion,
5563 StorageClass SC) {
5564 LookupResult R(SemaRef, Name, NameLoc,
5565 Owner->isRecord() ? Sema::LookupMemberName
5566 : Sema::LookupOrdinaryName,
5567 RedeclarationKind::ForVisibleRedeclaration);
5568 if (!SemaRef.LookupName(R, S)) return false;
5569
5570 // Pick a representative declaration.
5571 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5572 assert(PrevDecl && "Expected a non-null Decl");
5573
5574 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5575 return false;
5576
5577 if (SC == StorageClass::SC_None &&
5578 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5579 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5580 if (!Owner->isRecord())
5581 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5582 return false;
5583 }
5584
5585 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5586 << IsUnion << Name;
5587 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5588
5589 return true;
5590}
5591
5592void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5593 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5594 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5595}
5596
5597void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5598 if (!getLangOpts().CPlusPlus)
5599 return;
5600
5601 // This function can be parsed before we have validated the
5602 // structure as an anonymous struct
5603 if (Record->isAnonymousStructOrUnion())
5604 return;
5605
5606 const NamedDecl *First = 0;
5607 for (const Decl *D : Record->decls()) {
5608 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5609 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5610 continue;
5611 if (!First)
5612 First = ND;
5613 else
5614 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5615 }
5616}
5617
5618/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5619/// anonymous struct or union AnonRecord into the owning context Owner
5620/// and scope S. This routine will be invoked just after we realize
5621/// that an unnamed union or struct is actually an anonymous union or
5622/// struct, e.g.,
5623///
5624/// @code
5625/// union {
5626/// int i;
5627/// float f;
5628/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5629/// // f into the surrounding scope.x
5630/// @endcode
5631///
5632/// This routine is recursive, injecting the names of nested anonymous
5633/// structs/unions into the owning context and scope as well.
5634static bool
5635InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5636 RecordDecl *AnonRecord, AccessSpecifier AS,
5637 StorageClass SC,
5638 SmallVectorImpl<NamedDecl *> &Chaining) {
5639 bool Invalid = false;
5640
5641 // Look every FieldDecl and IndirectFieldDecl with a name.
5642 for (auto *D : AnonRecord->decls()) {
5643 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5644 cast<NamedDecl>(Val: D)->getDeclName()) {
5645 ValueDecl *VD = cast<ValueDecl>(Val: D);
5646 // C++ [class.union]p2:
5647 // The names of the members of an anonymous union shall be
5648 // distinct from the names of any other entity in the
5649 // scope in which the anonymous union is declared.
5650
5651 bool FieldInvalid = CheckAnonMemberRedeclaration(
5652 SemaRef, S, Owner, Name: VD->getDeclName(), NameLoc: VD->getLocation(),
5653 IsUnion: AnonRecord->isUnion(), SC);
5654 if (FieldInvalid)
5655 Invalid = true;
5656
5657 // Inject the IndirectFieldDecl even if invalid, because later
5658 // diagnostics may depend on it being present, see findDefaultInitializer.
5659
5660 // C++ [class.union]p2:
5661 // For the purpose of name lookup, after the anonymous union
5662 // definition, the members of the anonymous union are
5663 // considered to have been defined in the scope in which the
5664 // anonymous union is declared.
5665 unsigned OldChainingSize = Chaining.size();
5666 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5667 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5668 else
5669 Chaining.push_back(Elt: VD);
5670
5671 assert(Chaining.size() >= 2);
5672 NamedDecl **NamedChain =
5673 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5674 for (unsigned i = 0; i < Chaining.size(); i++)
5675 NamedChain[i] = Chaining[i];
5676
5677 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5678 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5679 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5680
5681 for (const auto *Attr : VD->attrs())
5682 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5683
5684 IndirectField->setAccess(AS);
5685 IndirectField->setImplicit();
5686 IndirectField->setInvalidDecl(FieldInvalid);
5687 SemaRef.PushOnScopeChains(D: IndirectField, S);
5688
5689 // That includes picking up the appropriate access specifier.
5690 if (AS != AS_none)
5691 IndirectField->setAccess(AS);
5692
5693 Chaining.resize(N: OldChainingSize);
5694 }
5695 }
5696
5697 return Invalid;
5698}
5699
5700/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5701/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5702/// illegal input values are mapped to SC_None.
5703static StorageClass
5704StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5705 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5706 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5707 "Parser allowed 'typedef' as storage class VarDecl.");
5708 switch (StorageClassSpec) {
5709 case DeclSpec::SCS_unspecified: return SC_None;
5710 case DeclSpec::SCS_extern:
5711 if (DS.isExternInLinkageSpec())
5712 return SC_None;
5713 return SC_Extern;
5714 case DeclSpec::SCS_static: return SC_Static;
5715 case DeclSpec::SCS_auto: return SC_Auto;
5716 case DeclSpec::SCS_register: return SC_Register;
5717 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5718 // Illegal SCSs map to None: error reporting is up to the caller.
5719 case DeclSpec::SCS_mutable: // Fall through.
5720 case DeclSpec::SCS_typedef: return SC_None;
5721 }
5722 llvm_unreachable("unknown storage class specifier");
5723}
5724
5725static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5726 assert(Record->hasInClassInitializer());
5727
5728 for (const auto *I : Record->decls()) {
5729 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5730 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5731 FD = IFD->getAnonField();
5732 if (FD && FD->hasInClassInitializer())
5733 return FD->getLocation();
5734 }
5735
5736 llvm_unreachable("couldn't find in-class initializer");
5737}
5738
5739static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5740 SourceLocation DefaultInitLoc) {
5741 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5742 return;
5743
5744 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5745 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5746}
5747
5748static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5749 CXXRecordDecl *AnonUnion) {
5750 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5751 return;
5752
5753 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5754}
5755
5756Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5757 AccessSpecifier AS,
5758 RecordDecl *Record,
5759 const PrintingPolicy &Policy) {
5760 DeclContext *Owner = Record->getDeclContext();
5761
5762 // Diagnose whether this anonymous struct/union is an extension.
5763 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5764 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5765 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5766 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5767 else if (!Record->isUnion() && !getLangOpts().C11)
5768 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5769
5770 // C and C++ require different kinds of checks for anonymous
5771 // structs/unions.
5772 bool Invalid = false;
5773 if (getLangOpts().CPlusPlus) {
5774 const char *PrevSpec = nullptr;
5775 if (Record->isUnion()) {
5776 // C++ [class.union]p6:
5777 // C++17 [class.union.anon]p2:
5778 // Anonymous unions declared in a named namespace or in the
5779 // global namespace shall be declared static.
5780 unsigned DiagID;
5781 DeclContext *OwnerScope = Owner->getRedeclContext();
5782 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5783 (OwnerScope->isTranslationUnit() ||
5784 (OwnerScope->isNamespace() &&
5785 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5786 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5787 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5788
5789 // Recover by adding 'static'.
5790 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5791 PrevSpec, DiagID, Policy);
5792 }
5793 // C++ [class.union]p6:
5794 // A storage class is not allowed in a declaration of an
5795 // anonymous union in a class scope.
5796 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5797 isa<RecordDecl>(Val: Owner)) {
5798 Diag(Loc: DS.getStorageClassSpecLoc(),
5799 DiagID: diag::err_anonymous_union_with_storage_spec)
5800 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5801
5802 // Recover by removing the storage specifier.
5803 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5804 Loc: SourceLocation(),
5805 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5806 }
5807 }
5808
5809 // Ignore const/volatile/restrict qualifiers.
5810 if (DS.getTypeQualifiers()) {
5811 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5812 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5813 << Record->isUnion() << "const"
5814 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5815 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5816 Diag(Loc: DS.getVolatileSpecLoc(),
5817 DiagID: diag::ext_anonymous_struct_union_qualified)
5818 << Record->isUnion() << "volatile"
5819 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5820 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5821 Diag(Loc: DS.getRestrictSpecLoc(),
5822 DiagID: diag::ext_anonymous_struct_union_qualified)
5823 << Record->isUnion() << "restrict"
5824 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5825 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5826 Diag(Loc: DS.getAtomicSpecLoc(),
5827 DiagID: diag::ext_anonymous_struct_union_qualified)
5828 << Record->isUnion() << "_Atomic"
5829 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5830 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5831 Diag(Loc: DS.getUnalignedSpecLoc(),
5832 DiagID: diag::ext_anonymous_struct_union_qualified)
5833 << Record->isUnion() << "__unaligned"
5834 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5835
5836 DS.ClearTypeQualifiers();
5837 }
5838
5839 // C++ [class.union]p2:
5840 // The member-specification of an anonymous union shall only
5841 // define non-static data members. [Note: nested types and
5842 // functions cannot be declared within an anonymous union. ]
5843 for (auto *Mem : Record->decls()) {
5844 // Ignore invalid declarations; we already diagnosed them.
5845 if (Mem->isInvalidDecl())
5846 continue;
5847
5848 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5849 // C++ [class.union]p3:
5850 // An anonymous union shall not have private or protected
5851 // members (clause 11).
5852 assert(FD->getAccess() != AS_none);
5853 if (FD->getAccess() != AS_public) {
5854 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5855 << Record->isUnion() << (FD->getAccess() == AS_protected);
5856 Invalid = true;
5857 }
5858
5859 // C++ [class.union]p1
5860 // An object of a class with a non-trivial constructor, a non-trivial
5861 // copy constructor, a non-trivial destructor, or a non-trivial copy
5862 // assignment operator cannot be a member of a union, nor can an
5863 // array of such objects.
5864 if (CheckNontrivialField(FD))
5865 Invalid = true;
5866 } else if (Mem->isImplicit()) {
5867 // Any implicit members are fine.
5868 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5869 // This is a type that showed up in an
5870 // elaborated-type-specifier inside the anonymous struct or
5871 // union, but which actually declares a type outside of the
5872 // anonymous struct or union. It's okay.
5873 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5874 if (!MemRecord->isAnonymousStructOrUnion() &&
5875 MemRecord->getDeclName()) {
5876 // Visual C++ allows type definition in anonymous struct or union.
5877 if (getLangOpts().MicrosoftExt)
5878 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5879 << Record->isUnion();
5880 else {
5881 // This is a nested type declaration.
5882 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5883 << Record->isUnion();
5884 Invalid = true;
5885 }
5886 } else {
5887 // This is an anonymous type definition within another anonymous type.
5888 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5889 // not part of standard C++.
5890 Diag(Loc: MemRecord->getLocation(),
5891 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5892 << Record->isUnion();
5893 }
5894 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5895 // Any access specifier is fine.
5896 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5897 // In C++1z, static_assert declarations are also fine.
5898 } else {
5899 // We have something that isn't a non-static data
5900 // member. Complain about it.
5901 unsigned DK = diag::err_anonymous_record_bad_member;
5902 if (isa<TypeDecl>(Val: Mem))
5903 DK = diag::err_anonymous_record_with_type;
5904 else if (isa<FunctionDecl>(Val: Mem))
5905 DK = diag::err_anonymous_record_with_function;
5906 else if (isa<VarDecl>(Val: Mem))
5907 DK = diag::err_anonymous_record_with_static;
5908
5909 // Visual C++ allows type definition in anonymous struct or union.
5910 if (getLangOpts().MicrosoftExt &&
5911 DK == diag::err_anonymous_record_with_type)
5912 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5913 << Record->isUnion();
5914 else {
5915 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5916 Invalid = true;
5917 }
5918 }
5919 }
5920
5921 // C++11 [class.union]p8 (DR1460):
5922 // At most one variant member of a union may have a
5923 // brace-or-equal-initializer.
5924 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5925 Owner->isRecord())
5926 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5927 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5928 }
5929
5930 if (!Record->isUnion() && !Owner->isRecord()) {
5931 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5932 << getLangOpts().CPlusPlus;
5933 Invalid = true;
5934 }
5935
5936 // C++ [dcl.dcl]p3:
5937 // [If there are no declarators], and except for the declaration of an
5938 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5939 // names into the program
5940 // C++ [class.mem]p2:
5941 // each such member-declaration shall either declare at least one member
5942 // name of the class or declare at least one unnamed bit-field
5943 //
5944 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5945 if (getLangOpts().CPlusPlus && Record->field_empty())
5946 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5947
5948 // Mock up a declarator.
5949 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5950 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5951 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5952 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5953
5954 // Create a declaration for this anonymous struct/union.
5955 NamedDecl *Anon = nullptr;
5956 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5957 Anon = FieldDecl::Create(
5958 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5959 /*IdentifierInfo=*/Id: nullptr, T: Context.getCanonicalTagType(TD: Record), TInfo,
5960 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5961 /*InitStyle=*/ICIS_NoInit);
5962 Anon->setAccess(AS);
5963 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5964
5965 if (getLangOpts().CPlusPlus)
5966 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5967 } else {
5968 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5969 if (SCSpec == DeclSpec::SCS_mutable) {
5970 // mutable can only appear on non-static class members, so it's always
5971 // an error here
5972 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
5973 Invalid = true;
5974 SC = SC_None;
5975 }
5976
5977 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5978 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5979 T: Context.getCanonicalTagType(TD: Record), TInfo, S: SC);
5980 if (Invalid)
5981 Anon->setInvalidDecl();
5982
5983 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5984
5985 // Default-initialize the implicit variable. This initialization will be
5986 // trivial in almost all cases, except if a union member has an in-class
5987 // initializer:
5988 // union { int n = 0; };
5989 ActOnUninitializedDecl(dcl: Anon);
5990 }
5991 Anon->setImplicit();
5992
5993 // Mark this as an anonymous struct/union type.
5994 Record->setAnonymousStructOrUnion(true);
5995
5996 // Add the anonymous struct/union object to the current
5997 // context. We'll be referencing this object when we refer to one of
5998 // its members.
5999 Owner->addDecl(D: Anon);
6000
6001 // Inject the members of the anonymous struct/union into the owning
6002 // context and into the identifier resolver chain for name lookup
6003 // purposes.
6004 SmallVector<NamedDecl*, 2> Chain;
6005 Chain.push_back(Elt: Anon);
6006
6007 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
6008 Chaining&: Chain))
6009 Invalid = true;
6010
6011 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
6012 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6013 MangleNumberingContext *MCtx;
6014 Decl *ManglingContextDecl;
6015 std::tie(args&: MCtx, args&: ManglingContextDecl) =
6016 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
6017 if (MCtx) {
6018 Context.setManglingNumber(
6019 ND: NewVD, Number: MCtx->getManglingNumber(
6020 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
6021 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
6022 }
6023 }
6024 }
6025
6026 if (Invalid)
6027 Anon->setInvalidDecl();
6028
6029 return Anon;
6030}
6031
6032Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
6033 RecordDecl *Record) {
6034 assert(Record && "expected a record!");
6035
6036 // Mock up a declarator.
6037 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
6038 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
6039 assert(TInfo && "couldn't build declarator info for anonymous struct");
6040
6041 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
6042 CanQualType RecTy = Context.getCanonicalTagType(TD: Record);
6043
6044 // Create a declaration for this anonymous struct.
6045 NamedDecl *Anon =
6046 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
6047 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
6048 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
6049 /*InitStyle=*/ICIS_NoInit);
6050 Anon->setImplicit();
6051
6052 // Add the anonymous struct object to the current context.
6053 CurContext->addDecl(D: Anon);
6054
6055 // Inject the members of the anonymous struct into the current
6056 // context and into the identifier resolver chain for name lookup
6057 // purposes.
6058 SmallVector<NamedDecl*, 2> Chain;
6059 Chain.push_back(Elt: Anon);
6060
6061 RecordDecl *RecordDef = Record->getDefinition();
6062 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
6063 DiagID: diag::err_field_incomplete_or_sizeless) ||
6064 InjectAnonymousStructOrUnionMembers(
6065 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
6066 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
6067 Anon->setInvalidDecl();
6068 ParentDecl->setInvalidDecl();
6069 }
6070
6071 return Anon;
6072}
6073
6074DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
6075 return GetNameFromUnqualifiedId(Name: D.getName());
6076}
6077
6078DeclarationNameInfo
6079Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
6080 DeclarationNameInfo NameInfo;
6081 NameInfo.setLoc(Name.StartLocation);
6082
6083 switch (Name.getKind()) {
6084
6085 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6086 case UnqualifiedIdKind::IK_Identifier:
6087 NameInfo.setName(Name.Identifier);
6088 return NameInfo;
6089
6090 case UnqualifiedIdKind::IK_DeductionGuideName: {
6091 // C++ [temp.deduct.guide]p3:
6092 // The simple-template-id shall name a class template specialization.
6093 // The template-name shall be the same identifier as the template-name
6094 // of the simple-template-id.
6095 // These together intend to imply that the template-name shall name a
6096 // class template.
6097 // FIXME: template<typename T> struct X {};
6098 // template<typename T> using Y = X<T>;
6099 // Y(int) -> Y<int>;
6100 // satisfies these rules but does not name a class template.
6101 TemplateName TN = Name.TemplateName.get().get();
6102 auto *Template = TN.getAsTemplateDecl();
6103 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
6104 Diag(Loc: Name.StartLocation,
6105 DiagID: diag::err_deduction_guide_name_not_class_template)
6106 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
6107 if (Template)
6108 NoteTemplateLocation(Decl: *Template);
6109 return DeclarationNameInfo();
6110 }
6111
6112 NameInfo.setName(
6113 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
6114 return NameInfo;
6115 }
6116
6117 case UnqualifiedIdKind::IK_OperatorFunctionId:
6118 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6119 Op: Name.OperatorFunctionId.Operator));
6120 NameInfo.setCXXOperatorNameRange(SourceRange(
6121 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6122 return NameInfo;
6123
6124 case UnqualifiedIdKind::IK_LiteralOperatorId:
6125 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6126 II: Name.Identifier));
6127 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6128 return NameInfo;
6129
6130 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6131 TypeSourceInfo *TInfo;
6132 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
6133 if (Ty.isNull())
6134 return DeclarationNameInfo();
6135 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6136 Ty: Context.getCanonicalType(T: Ty)));
6137 NameInfo.setNamedTypeInfo(TInfo);
6138 return NameInfo;
6139 }
6140
6141 case UnqualifiedIdKind::IK_ConstructorName: {
6142 TypeSourceInfo *TInfo;
6143 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
6144 if (Ty.isNull())
6145 return DeclarationNameInfo();
6146 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6147 Ty: Context.getCanonicalType(T: Ty)));
6148 NameInfo.setNamedTypeInfo(TInfo);
6149 return NameInfo;
6150 }
6151
6152 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6153 // In well-formed code, we can only have a constructor
6154 // template-id that refers to the current context, so go there
6155 // to find the actual type being constructed.
6156 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
6157 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6158 return DeclarationNameInfo();
6159
6160 // Determine the type of the class being constructed.
6161 CanQualType CurClassType = Context.getCanonicalTagType(TD: CurClass);
6162
6163 // FIXME: Check two things: that the template-id names the same type as
6164 // CurClassType, and that the template-id does not occur when the name
6165 // was qualified.
6166
6167 NameInfo.setName(
6168 Context.DeclarationNames.getCXXConstructorName(Ty: CurClassType));
6169 // FIXME: should we retrieve TypeSourceInfo?
6170 NameInfo.setNamedTypeInfo(nullptr);
6171 return NameInfo;
6172 }
6173
6174 case UnqualifiedIdKind::IK_DestructorName: {
6175 TypeSourceInfo *TInfo;
6176 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6177 if (Ty.isNull())
6178 return DeclarationNameInfo();
6179 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6180 Ty: Context.getCanonicalType(T: Ty)));
6181 NameInfo.setNamedTypeInfo(TInfo);
6182 return NameInfo;
6183 }
6184
6185 case UnqualifiedIdKind::IK_TemplateId: {
6186 TemplateName TName = Name.TemplateId->Template.get();
6187 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6188 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6189 }
6190
6191 } // switch (Name.getKind())
6192
6193 llvm_unreachable("Unknown name kind");
6194}
6195
6196static QualType getCoreType(QualType Ty) {
6197 do {
6198 if (Ty->isPointerOrReferenceType())
6199 Ty = Ty->getPointeeType();
6200 else if (Ty->isArrayType())
6201 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6202 else
6203 return Ty.withoutLocalFastQualifiers();
6204 } while (true);
6205}
6206
6207/// hasSimilarParameters - Determine whether the C++ functions Declaration
6208/// and Definition have "nearly" matching parameters. This heuristic is
6209/// used to improve diagnostics in the case where an out-of-line function
6210/// definition doesn't match any declaration within the class or namespace.
6211/// Also sets Params to the list of indices to the parameters that differ
6212/// between the declaration and the definition. If hasSimilarParameters
6213/// returns true and Params is empty, then all of the parameters match.
6214static bool hasSimilarParameters(ASTContext &Context,
6215 FunctionDecl *Declaration,
6216 FunctionDecl *Definition,
6217 SmallVectorImpl<unsigned> &Params) {
6218 Params.clear();
6219 if (Declaration->param_size() != Definition->param_size())
6220 return false;
6221 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6222 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6223 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6224
6225 // The parameter types are identical
6226 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6227 continue;
6228
6229 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6230 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6231 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6232 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6233
6234 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6235 (DeclTyName && DeclTyName == DefTyName))
6236 Params.push_back(Elt: Idx);
6237 else // The two parameters aren't even close
6238 return false;
6239 }
6240
6241 return true;
6242}
6243
6244/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6245/// declarator needs to be rebuilt in the current instantiation.
6246/// Any bits of declarator which appear before the name are valid for
6247/// consideration here. That's specifically the type in the decl spec
6248/// and the base type in any member-pointer chunks.
6249static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6250 DeclarationName Name) {
6251 // The types we specifically need to rebuild are:
6252 // - typenames, typeofs, and decltypes
6253 // - types which will become injected class names
6254 // Of course, we also need to rebuild any type referencing such a
6255 // type. It's safest to just say "dependent", but we call out a
6256 // few cases here.
6257
6258 DeclSpec &DS = D.getMutableDeclSpec();
6259 switch (DS.getTypeSpecType()) {
6260 case DeclSpec::TST_typename:
6261 case DeclSpec::TST_typeofType:
6262 case DeclSpec::TST_typeof_unqualType:
6263#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6264#include "clang/Basic/BuiltinTraits.inc"
6265 case DeclSpec::TST_atomic: {
6266 // Grab the type from the parser.
6267 TypeSourceInfo *TSI = nullptr;
6268 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6269 if (T.isNull() || !T->isInstantiationDependentType()) break;
6270
6271 // Make sure there's a type source info. This isn't really much
6272 // of a waste; most dependent types should have type source info
6273 // attached already.
6274 if (!TSI)
6275 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6276
6277 // Rebuild the type in the current instantiation.
6278 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6279 if (!TSI) return true;
6280
6281 // Store the new type back in the decl spec.
6282 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6283 DS.UpdateTypeRep(Rep: LocType);
6284 break;
6285 }
6286
6287 case DeclSpec::TST_decltype:
6288 case DeclSpec::TST_typeof_unqualExpr:
6289 case DeclSpec::TST_typeofExpr: {
6290 Expr *E = DS.getRepAsExpr();
6291 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6292 if (Result.isInvalid()) return true;
6293 DS.UpdateExprRep(Rep: Result.get());
6294 break;
6295 }
6296
6297 default:
6298 // Nothing to do for these decl specs.
6299 break;
6300 }
6301
6302 // It doesn't matter what order we do this in.
6303 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6304 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6305
6306 // The only type information in the declarator which can come
6307 // before the declaration name is the base type of a member
6308 // pointer.
6309 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6310 continue;
6311
6312 // Rebuild the scope specifier in-place.
6313 CXXScopeSpec &SS = Chunk.Mem.Scope();
6314 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6315 return true;
6316 }
6317
6318 return false;
6319}
6320
6321/// Returns true if the declaration is declared in a system header or from a
6322/// system macro.
6323static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6324 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6325 SM.isInSystemMacro(loc: D->getLocation());
6326}
6327
6328void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6329 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6330 // of system decl.
6331 if (D->getPreviousDecl() || D->isImplicit())
6332 return;
6333 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6334 if (Status != ReservedIdentifierStatus::NotReserved &&
6335 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6336 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6337 << D << static_cast<int>(Status);
6338 }
6339}
6340
6341Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6342 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6343
6344 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6345 // declaration only if the `bind_to_declaration` extension is set.
6346 SmallVector<FunctionDecl *, 4> Bases;
6347 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6348 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6349 TP: llvm::omp::TraitProperty::
6350 implementation_extension_bind_to_declaration))
6351 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6352 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6353
6354 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6355
6356 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6357 Dcl && Dcl->getDeclContext()->isFileContext())
6358 Dcl->setTopLevelDeclInObjCContainer();
6359
6360 if (!Bases.empty())
6361 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6362 Bases);
6363
6364 return Dcl;
6365}
6366
6367bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6368 DeclarationNameInfo NameInfo) {
6369 DeclarationName Name = NameInfo.getName();
6370
6371 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6372 while (Record && Record->isAnonymousStructOrUnion())
6373 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6374 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6375 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6376 return true;
6377 }
6378
6379 return false;
6380}
6381
6382bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6383 DeclarationName Name,
6384 SourceLocation Loc,
6385 TemplateIdAnnotation *TemplateId,
6386 bool IsMemberSpecialization) {
6387 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6388 "without nested-name-specifier");
6389 DeclContext *Cur = CurContext;
6390 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6391 Cur = Cur->getParent();
6392
6393 // If the user provided a superfluous scope specifier that refers back to the
6394 // class in which the entity is already declared, diagnose and ignore it.
6395 //
6396 // class X {
6397 // void X::f();
6398 // };
6399 //
6400 // Note, it was once ill-formed to give redundant qualification in all
6401 // contexts, but that rule was removed by DR482.
6402 if (Cur->Equals(DC)) {
6403 if (Cur->isRecord()) {
6404 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6405 : diag::err_member_extra_qualification)
6406 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6407 SS.clear();
6408 } else {
6409 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6410 }
6411 return false;
6412 }
6413
6414 // Check whether the qualifying scope encloses the scope of the original
6415 // declaration. For a template-id, we perform the checks in
6416 // CheckTemplateSpecializationScope.
6417 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6418 if (Cur->isRecord())
6419 Diag(Loc, DiagID: diag::err_member_qualification)
6420 << Name << SS.getRange();
6421 else if (isa<TranslationUnitDecl>(Val: DC))
6422 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6423 << Name << SS.getRange();
6424 else if (isa<FunctionDecl>(Val: Cur))
6425 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6426 << Name << SS.getRange();
6427 else if (isa<BlockDecl>(Val: Cur))
6428 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6429 << Name << SS.getRange();
6430 else if (isa<ExportDecl>(Val: Cur)) {
6431 if (!isa<NamespaceDecl>(Val: DC))
6432 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6433 << Name << SS.getRange();
6434 else
6435 // The cases that DC is not NamespaceDecl should be handled in
6436 // CheckRedeclarationExported.
6437 return false;
6438 } else
6439 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6440 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6441
6442 return true;
6443 }
6444
6445 if (Cur->isRecord()) {
6446 // C++26 [temp.expl.spec]p3 (Adopted as a DR in CWG727):
6447 // An explicit specialization may be declared in any scope in which the
6448 // corresponding primary template may be defined.
6449 if (IsMemberSpecialization)
6450 return false;
6451
6452 // Cannot qualify members within a class.
6453 Diag(Loc, DiagID: diag::err_member_qualification)
6454 << Name << SS.getRange();
6455 SS.clear();
6456
6457 // C++ constructors and destructors with incorrect scopes can break
6458 // our AST invariants by having the wrong underlying types. If
6459 // that's the case, then drop this declaration entirely.
6460 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6461 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6462 !Context.hasSameType(
6463 T1: Name.getCXXNameType(),
6464 T2: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: Cur))))
6465 return true;
6466
6467 return false;
6468 }
6469
6470 // C++23 [temp.names]p5:
6471 // The keyword template shall not appear immediately after a declarative
6472 // nested-name-specifier.
6473 //
6474 // First check the template-id (if any), and then check each component of the
6475 // nested-name-specifier in reverse order.
6476 //
6477 // FIXME: nested-name-specifiers in friend declarations are declarative,
6478 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6479 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6480 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6481 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6482
6483 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6484 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6485 TL = std::exchange(obj&: NextTL, new_val: TypeLoc())) {
6486 SourceLocation TemplateKeywordLoc;
6487 switch (TL.getTypeLocClass()) {
6488 case TypeLoc::TemplateSpecialization: {
6489 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6490 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6491 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6492 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6493 << TST.getLocalSourceRange();
6494 break;
6495 }
6496 case TypeLoc::Decltype:
6497 case TypeLoc::PackIndexing: {
6498 const Type *T = TL.getTypePtr();
6499 // C++23 [expr.prim.id.qual]p2:
6500 // [...] A declarative nested-name-specifier shall not have a
6501 // computed-type-specifier.
6502 //
6503 // CWG2858 changed this from 'decltype-specifier' to
6504 // 'computed-type-specifier'.
6505 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6506 << T->isDecltypeType() << TL.getSourceRange();
6507 break;
6508 }
6509 case TypeLoc::DependentName:
6510 NextTL =
6511 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6512 break;
6513 default:
6514 break;
6515 }
6516 if (TemplateKeywordLoc.isValid())
6517 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6518 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6519 }
6520
6521 return false;
6522}
6523
6524NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6525 MultiTemplateParamsArg TemplateParamLists) {
6526 // TODO: consider using NameInfo for diagnostic.
6527 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6528 DeclarationName Name = NameInfo.getName();
6529
6530 // All of these full declarators require an identifier. If it doesn't have
6531 // one, the ParsedFreeStandingDeclSpec action should be used.
6532 if (D.isDecompositionDeclarator()) {
6533 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6534 } else if (!Name) {
6535 if (!D.isInvalidType()) // Reject this if we think it is valid.
6536 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6537 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6538 return nullptr;
6539 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6540 return nullptr;
6541
6542 DeclContext *DC = CurContext;
6543 if (D.getCXXScopeSpec().isInvalid())
6544 D.setInvalidType();
6545 else if (D.getCXXScopeSpec().isSet()) {
6546 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6547 UPPC: UPPC_DeclarationQualifier))
6548 return nullptr;
6549
6550 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6551 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6552 if (!DC || isa<EnumDecl>(Val: DC)) {
6553 // If we could not compute the declaration context, it's because the
6554 // declaration context is dependent but does not refer to a class,
6555 // class template, or class template partial specialization. Complain
6556 // and return early, to avoid the coming semantic disaster.
6557 Diag(Loc: D.getIdentifierLoc(),
6558 DiagID: diag::err_template_qualified_declarator_no_match)
6559 << D.getCXXScopeSpec().getScopeRep()
6560 << D.getCXXScopeSpec().getRange();
6561 return nullptr;
6562 }
6563 bool IsDependentContext = DC->isDependentContext();
6564
6565 if (!IsDependentContext &&
6566 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6567 return nullptr;
6568
6569 // If a class is incomplete, do not parse entities inside it.
6570 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6571 Diag(Loc: D.getIdentifierLoc(),
6572 DiagID: diag::err_member_def_undefined_record)
6573 << Name << DC << D.getCXXScopeSpec().getRange();
6574 return nullptr;
6575 }
6576 if (!D.getDeclSpec().isFriendSpecified()) {
6577 TemplateIdAnnotation *TemplateId =
6578 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6579 ? D.getName().TemplateId
6580 : nullptr;
6581 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6582 Loc: D.getIdentifierLoc(), TemplateId,
6583 /*IsMemberSpecialization=*/false)) {
6584 if (DC->isRecord())
6585 return nullptr;
6586
6587 D.setInvalidType();
6588 } else if (CurContext->isRecord() && !CurContext->Equals(DC)) {
6589 D.setInvalidType();
6590 }
6591 }
6592
6593 // Check whether we need to rebuild the type of the given
6594 // declaration in the current instantiation.
6595 if (EnteringContext && IsDependentContext &&
6596 TemplateParamLists.size() != 0) {
6597 ContextRAII SavedContext(*this, DC);
6598 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6599 D.setInvalidType();
6600 }
6601 }
6602
6603 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6604 QualType R = TInfo->getType();
6605
6606 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6607 UPPC: UPPC_DeclarationType))
6608 D.setInvalidType();
6609
6610 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6611 forRedeclarationInCurContext());
6612
6613 // See if this is a redefinition of a variable in the same scope.
6614 if (!D.getCXXScopeSpec().isSet()) {
6615 bool IsLinkageLookup = false;
6616 bool CreateBuiltins = false;
6617
6618 // If the declaration we're planning to build will be a function
6619 // or object with linkage, then look for another declaration with
6620 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6621 //
6622 // If the declaration we're planning to build will be declared with
6623 // external linkage in the translation unit, create any builtin with
6624 // the same name.
6625 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6626 /* Do nothing*/;
6627 else if (CurContext->isFunctionOrMethod() &&
6628 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6629 R->isFunctionType())) {
6630 IsLinkageLookup = true;
6631 CreateBuiltins =
6632 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6633 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6634 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6635 CreateBuiltins = true;
6636
6637 if (IsLinkageLookup) {
6638 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6639 Previous.setRedeclarationKind(
6640 RedeclarationKind::ForExternalRedeclaration);
6641 }
6642
6643 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6644 } else { // Something like "int foo::x;"
6645 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6646
6647 // C++ [dcl.meaning]p1:
6648 // When the declarator-id is qualified, the declaration shall refer to a
6649 // previously declared member of the class or namespace to which the
6650 // qualifier refers (or, in the case of a namespace, of an element of the
6651 // inline namespace set of that namespace (7.3.1)) or to a specialization
6652 // thereof; [...]
6653 //
6654 // Note that we already checked the context above, and that we do not have
6655 // enough information to make sure that Previous contains the declaration
6656 // we want to match. For example, given:
6657 //
6658 // class X {
6659 // void f();
6660 // void f(float);
6661 // };
6662 //
6663 // void X::f(int) { } // ill-formed
6664 //
6665 // In this case, Previous will point to the overload set
6666 // containing the two f's declared in X, but neither of them
6667 // matches.
6668
6669 RemoveUsingDecls(R&: Previous);
6670 }
6671
6672 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6673 TPD && TPD->isTemplateParameter()) {
6674 // Older versions of clang allowed the names of function/variable templates
6675 // to shadow the names of their template parameters. For the compatibility
6676 // purposes we detect such cases and issue a default-to-error warning that
6677 // can be disabled with -Wno-strict-primary-template-shadow.
6678 if (!D.isInvalidType()) {
6679 bool AllowForCompatibility = false;
6680 if (Scope *DeclParent = S->getDeclParent();
6681 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6682 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6683 TemplateParamParent->isDeclScope(D: TPD);
6684 }
6685 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6686 SupportedForCompatibility: AllowForCompatibility);
6687 }
6688
6689 // Just pretend that we didn't see the previous declaration.
6690 Previous.clear();
6691 }
6692
6693 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6694 // Forget that the previous declaration is the injected-class-name.
6695 Previous.clear();
6696
6697 // In C++, the previous declaration we find might be a tag type
6698 // (class or enum). In this case, the new declaration will hide the
6699 // tag type. Note that this applies to functions, function templates, and
6700 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6701 if (Previous.isSingleTagDecl() &&
6702 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6703 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6704 Previous.clear();
6705
6706 // Check that there are no default arguments other than in the parameters
6707 // of a function declaration (C++ only).
6708 if (getLangOpts().CPlusPlus)
6709 CheckExtraCXXDefaultArguments(D);
6710
6711 /// Get the innermost enclosing declaration scope.
6712 S = S->getDeclParent();
6713
6714 NamedDecl *New;
6715
6716 bool AddToScope = true;
6717 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6718 if (TemplateParamLists.size()) {
6719 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6720 return nullptr;
6721 }
6722
6723 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6724 } else if (R->isFunctionType()) {
6725 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6726 TemplateParamLists,
6727 AddToScope);
6728 } else {
6729 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6730 AddToScope);
6731 }
6732
6733 if (!New)
6734 return nullptr;
6735
6736 warnOnCTypeHiddenInCPlusPlus(D: New);
6737
6738 // If this has an identifier and is not a function template specialization,
6739 // add it to the scope stack.
6740 if (New->getDeclName() && AddToScope)
6741 PushOnScopeChains(D: New, S);
6742
6743 if (OpenMP().isInOpenMPDeclareTargetContext())
6744 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6745
6746 return New;
6747}
6748
6749/// Helper method to turn variable array types into constant array
6750/// types in certain situations which would otherwise be errors (for
6751/// GCC compatibility).
6752static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6753 ASTContext &Context,
6754 bool &SizeIsNegative,
6755 llvm::APSInt &Oversized) {
6756 // This method tries to turn a variable array into a constant
6757 // array even when the size isn't an ICE. This is necessary
6758 // for compatibility with code that depends on gcc's buggy
6759 // constant expression folding, like struct {char x[(int)(char*)2];}
6760 SizeIsNegative = false;
6761 Oversized = 0;
6762
6763 if (T->isDependentType())
6764 return QualType();
6765
6766 QualifierCollector Qs;
6767 const Type *Ty = Qs.strip(type: T);
6768
6769 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6770 QualType Pointee = PTy->getPointeeType();
6771 QualType FixedType =
6772 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6773 Oversized);
6774 if (FixedType.isNull()) return FixedType;
6775 FixedType = Context.getPointerType(T: FixedType);
6776 return Qs.apply(Context, QT: FixedType);
6777 }
6778 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6779 QualType Inner = PTy->getInnerType();
6780 QualType FixedType =
6781 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6782 Oversized);
6783 if (FixedType.isNull()) return FixedType;
6784 FixedType = Context.getParenType(NamedType: FixedType);
6785 return Qs.apply(Context, QT: FixedType);
6786 }
6787
6788 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6789 if (!VLATy)
6790 return QualType();
6791
6792 QualType ElemTy = VLATy->getElementType();
6793 if (ElemTy->isVariablyModifiedType()) {
6794 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6795 SizeIsNegative, Oversized);
6796 if (ElemTy.isNull())
6797 return QualType();
6798 }
6799
6800 Expr::EvalResult Result;
6801 if (!VLATy->getSizeExpr() ||
6802 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6803 return QualType();
6804
6805 llvm::APSInt Res = Result.Val.getInt();
6806
6807 // Check whether the array size is negative.
6808 if (Res.isSigned() && Res.isNegative()) {
6809 SizeIsNegative = true;
6810 return QualType();
6811 }
6812
6813 // Check whether the array is too large to be addressed.
6814 unsigned ActiveSizeBits =
6815 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6816 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6817 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6818 : Res.getActiveBits();
6819 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6820 Oversized = std::move(Res);
6821 return QualType();
6822 }
6823
6824 QualType FoldedArrayType = Context.getConstantArrayType(
6825 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6826 return Qs.apply(Context, QT: FoldedArrayType);
6827}
6828
6829static void
6830FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6831 SrcTL = SrcTL.getUnqualifiedLoc();
6832 DstTL = DstTL.getUnqualifiedLoc();
6833 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6834 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6835 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6836 DstTL: DstPTL.getPointeeLoc());
6837 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6838 return;
6839 }
6840 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6841 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6842 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6843 DstTL: DstPTL.getInnerLoc());
6844 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6845 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6846 return;
6847 }
6848 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6849 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6850 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6851 TypeLoc DstElemTL = DstATL.getElementLoc();
6852 if (VariableArrayTypeLoc SrcElemATL =
6853 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6854 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6855 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6856 } else {
6857 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6858 }
6859 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6860 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6861 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6862}
6863
6864/// Helper method to turn variable array types into constant array
6865/// types in certain situations which would otherwise be errors (for
6866/// GCC compatibility).
6867static TypeSourceInfo*
6868TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6869 ASTContext &Context,
6870 bool &SizeIsNegative,
6871 llvm::APSInt &Oversized) {
6872 QualType FixedTy
6873 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6874 SizeIsNegative, Oversized);
6875 if (FixedTy.isNull())
6876 return nullptr;
6877 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6878 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6879 DstTL: FixedTInfo->getTypeLoc());
6880 return FixedTInfo;
6881}
6882
6883bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6884 QualType &T, SourceLocation Loc,
6885 unsigned FailedFoldDiagID) {
6886 bool SizeIsNegative;
6887 llvm::APSInt Oversized;
6888 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6889 TInfo, Context, SizeIsNegative, Oversized);
6890 if (FixedTInfo) {
6891 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6892 TInfo = FixedTInfo;
6893 T = FixedTInfo->getType();
6894 return true;
6895 }
6896
6897 if (SizeIsNegative)
6898 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6899 else if (Oversized.getBoolValue())
6900 Diag(Loc, DiagID: diag::err_array_too_large) << toString(
6901 I: Oversized, Radix: 10, Signed: Oversized.isSigned(), /*formatAsCLiteral=*/false,
6902 /*UpperCase=*/false, /*InsertSeparators=*/true);
6903 else if (FailedFoldDiagID)
6904 Diag(Loc, DiagID: FailedFoldDiagID);
6905 return false;
6906}
6907
6908void
6909Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6910 if (!getLangOpts().CPlusPlus &&
6911 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6912 // Don't need to track declarations in the TU in C.
6913 return;
6914
6915 // Note that we have a locally-scoped external with this name.
6916 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6917}
6918
6919NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6920 // FIXME: We can have multiple results via __attribute__((overloadable)).
6921 auto Result = Context.getExternCContextDecl()->lookup(Name);
6922 return Result.empty() ? nullptr : *Result.begin();
6923}
6924
6925void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6926 // FIXME: We should probably indicate the identifier in question to avoid
6927 // confusion for constructs like "virtual int a(), b;"
6928 if (DS.isVirtualSpecified())
6929 Diag(Loc: DS.getVirtualSpecLoc(),
6930 DiagID: diag::err_virtual_non_function);
6931
6932 if (DS.hasExplicitSpecifier())
6933 Diag(Loc: DS.getExplicitSpecLoc(),
6934 DiagID: diag::err_explicit_non_function);
6935
6936 if (DS.isNoreturnSpecified())
6937 Diag(Loc: DS.getNoreturnSpecLoc(),
6938 DiagID: diag::err_noreturn_non_function);
6939}
6940
6941NamedDecl*
6942Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6943 TypeSourceInfo *TInfo, LookupResult &Previous) {
6944 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6945 if (D.getCXXScopeSpec().isSet()) {
6946 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6947 << D.getCXXScopeSpec().getRange();
6948 D.setInvalidType();
6949 // Pretend we didn't see the scope specifier.
6950 DC = CurContext;
6951 Previous.clear();
6952 }
6953
6954 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6955
6956 if (D.getDeclSpec().isInlineSpecified())
6957 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6958 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6959 ? diag::warn_ms_inline_non_function
6960 : diag::err_inline_non_function)
6961 << getLangOpts().CPlusPlus17;
6962 if (D.getDeclSpec().hasConstexprSpecifier())
6963 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6964 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6965
6966 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6967 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6968 Diag(Loc: D.getName().StartLocation,
6969 DiagID: diag::err_deduction_guide_invalid_specifier)
6970 << "typedef";
6971 else
6972 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
6973 << D.getName().getSourceRange();
6974 return nullptr;
6975 }
6976
6977 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6978 if (!NewTD) return nullptr;
6979
6980 // Handle attributes prior to checking for duplicates in MergeVarDecl
6981 ProcessDeclAttributes(S, D: NewTD, PD: D);
6982
6983 CheckTypedefForVariablyModifiedType(S, D: NewTD);
6984
6985 bool Redeclaration = D.isRedeclaration();
6986 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
6987 D.setRedeclaration(Redeclaration);
6988 return ND;
6989}
6990
6991void
6992Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6993 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6994 // then it shall have block scope.
6995 // Note that variably modified types must be fixed before merging the decl so
6996 // that redeclarations will match.
6997 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6998 QualType T = TInfo->getType();
6999 if (T->isVariablyModifiedType()) {
7000 setFunctionHasBranchProtectedScope();
7001
7002 if (S->getFnParent() == nullptr) {
7003 bool SizeIsNegative;
7004 llvm::APSInt Oversized;
7005 TypeSourceInfo *FixedTInfo =
7006 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7007 SizeIsNegative,
7008 Oversized);
7009 if (FixedTInfo) {
7010 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
7011 NewTD->setTypeSourceInfo(FixedTInfo);
7012 } else {
7013 if (SizeIsNegative)
7014 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
7015 else if (T->isVariableArrayType())
7016 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
7017 else if (Oversized.getBoolValue())
7018 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
7019 << toString(I: Oversized, Radix: 10);
7020 else
7021 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
7022 NewTD->setInvalidDecl();
7023 }
7024 }
7025 }
7026}
7027
7028NamedDecl*
7029Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
7030 LookupResult &Previous, bool &Redeclaration) {
7031
7032 // Find the shadowed declaration before filtering for scope.
7033 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
7034
7035 // Merge the decl with the existing one if appropriate. If the decl is
7036 // in an outer scope, it isn't the same thing.
7037 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
7038 /*AllowInlineNamespace*/false);
7039 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
7040 if (!Previous.empty()) {
7041 Redeclaration = true;
7042 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
7043 } else {
7044 inferGslPointerAttribute(TD: NewTD);
7045 }
7046
7047 if (ShadowedDecl && !Redeclaration)
7048 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
7049
7050 // If this is the C FILE type, notify the AST context.
7051 if (IdentifierInfo *II = NewTD->getIdentifier())
7052 if (!NewTD->isInvalidDecl() &&
7053 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7054 switch (II->getNotableIdentifierID()) {
7055 case tok::NotableIdentifierKind::FILE:
7056 Context.setFILEDecl(NewTD);
7057 break;
7058 case tok::NotableIdentifierKind::jmp_buf:
7059 Context.setjmp_bufDecl(NewTD);
7060 break;
7061 case tok::NotableIdentifierKind::sigjmp_buf:
7062 Context.setsigjmp_bufDecl(NewTD);
7063 break;
7064 case tok::NotableIdentifierKind::ucontext_t:
7065 Context.setucontext_tDecl(NewTD);
7066 break;
7067 case tok::NotableIdentifierKind::float_t:
7068 case tok::NotableIdentifierKind::double_t:
7069 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
7070 break;
7071 default:
7072 break;
7073 }
7074 }
7075
7076 return NewTD;
7077}
7078
7079/// Determines whether the given declaration is an out-of-scope
7080/// previous declaration.
7081///
7082/// This routine should be invoked when name lookup has found a
7083/// previous declaration (PrevDecl) that is not in the scope where a
7084/// new declaration by the same name is being introduced. If the new
7085/// declaration occurs in a local scope, previous declarations with
7086/// linkage may still be considered previous declarations (C99
7087/// 6.2.2p4-5, C++ [basic.link]p6).
7088///
7089/// \param PrevDecl the previous declaration found by name
7090/// lookup
7091///
7092/// \param DC the context in which the new declaration is being
7093/// declared.
7094///
7095/// \returns true if PrevDecl is an out-of-scope previous declaration
7096/// for a new delcaration with the same name.
7097static bool
7098isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7099 ASTContext &Context) {
7100 if (!PrevDecl)
7101 return false;
7102
7103 if (!PrevDecl->hasLinkage())
7104 return false;
7105
7106 if (Context.getLangOpts().CPlusPlus) {
7107 // C++ [basic.link]p6:
7108 // If there is a visible declaration of an entity with linkage
7109 // having the same name and type, ignoring entities declared
7110 // outside the innermost enclosing namespace scope, the block
7111 // scope declaration declares that same entity and receives the
7112 // linkage of the previous declaration.
7113 DeclContext *OuterContext = DC->getRedeclContext();
7114 if (!OuterContext->isFunctionOrMethod())
7115 // This rule only applies to block-scope declarations.
7116 return false;
7117
7118 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7119 if (PrevOuterContext->isRecord())
7120 // We found a member function: ignore it.
7121 return false;
7122
7123 // Find the innermost enclosing namespace for the new and
7124 // previous declarations.
7125 OuterContext = OuterContext->getEnclosingNamespaceContext();
7126 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7127
7128 // The previous declaration is in a different namespace, so it
7129 // isn't the same function.
7130 if (!OuterContext->Equals(DC: PrevOuterContext))
7131 return false;
7132 }
7133
7134 return true;
7135}
7136
7137static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7138 CXXScopeSpec &SS = D.getCXXScopeSpec();
7139 if (!SS.isSet()) return;
7140 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
7141}
7142
7143void Sema::deduceOpenCLAddressSpace(VarDecl *Var) {
7144 LangAS ImplAS = LangAS::opencl_private;
7145 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7146 // __opencl_c_program_scope_global_variables feature, the address space
7147 // for a variable at program scope or a static or extern variable inside
7148 // a function are inferred to be __global.
7149 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7150 Var->hasGlobalStorage())
7151 ImplAS = LangAS::opencl_global;
7152 Var->assignAddressSpace(Ctxt: Context, AS: ImplAS);
7153}
7154
7155static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7156 // 'weak' only applies to declarations with external linkage.
7157 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7158 if (!ND.isExternallyVisible()) {
7159 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
7160 ND.dropAttr<WeakAttr>();
7161 }
7162 }
7163}
7164
7165static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7166 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7167 if (ND.isExternallyVisible()) {
7168 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
7169 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7170 }
7171 }
7172}
7173
7174static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7175 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7176 if (VD->hasInit()) {
7177 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7178 assert(VD->isThisDeclarationADefinition() &&
7179 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7180 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
7181 VD->dropAttr<AliasAttr>();
7182 }
7183 }
7184 }
7185}
7186
7187static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7188 // 'selectany' only applies to externally visible variable declarations.
7189 // It does not apply to functions.
7190 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7191 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7192 S.Diag(Loc: Attr->getLocation(),
7193 DiagID: diag::err_attribute_selectany_non_extern_data);
7194 ND.dropAttr<SelectAnyAttr>();
7195 }
7196 }
7197}
7198
7199static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7200 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7201 if (!ND.isExternallyVisible())
7202 S.Diag(Loc: Attr->getLocation(),
7203 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7204 }
7205}
7206
7207static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7208 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7209 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7210 bool IsAnonymousNS = false;
7211 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7212 if (VD) {
7213 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7214 while (NS && !IsAnonymousNS) {
7215 IsAnonymousNS = NS->isAnonymousNamespace();
7216 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7217 }
7218 }
7219 // dll attributes require external linkage. Static locals may have external
7220 // linkage but still cannot be explicitly imported or exported.
7221 // In Microsoft mode, a variable defined in anonymous namespace must have
7222 // external linkage in order to be exported.
7223 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7224 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7225 (!AnonNSInMicrosoftMode &&
7226 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7227 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7228 << &ND << Attr;
7229 ND.setInvalidDecl();
7230 }
7231 }
7232}
7233
7234static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7235 // Check the attributes on the function type and function params, if any.
7236 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7237 FD = FD->getMostRecentDecl();
7238 // Don't declare this variable in the second operand of the for-statement;
7239 // GCC miscompiles that by ending its lifetime before evaluating the
7240 // third operand. See gcc.gnu.org/PR86769.
7241 AttributedTypeLoc ATL;
7242 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7243 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7244 TL = ATL.getModifiedLoc()) {
7245 // The [[lifetimebound]] attribute can be applied to the implicit object
7246 // parameter of a non-static member function (other than a ctor or dtor)
7247 // by applying it to the function type.
7248 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7249 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7250 int NoImplicitObjectError = -1;
7251 if (!MD)
7252 NoImplicitObjectError = 0;
7253 else if (MD->isStatic())
7254 NoImplicitObjectError = 1;
7255 else if (MD->isExplicitObjectMemberFunction())
7256 NoImplicitObjectError = 2;
7257 if (NoImplicitObjectError != -1) {
7258 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7259 << NoImplicitObjectError << A->getRange();
7260 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7261 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7262 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7263 } else if (MD->getReturnType()->isVoidType()) {
7264 S.Diag(
7265 Loc: MD->getLocation(),
7266 DiagID: diag::
7267 err_lifetimebound_implicit_object_parameter_void_return_type);
7268 }
7269 }
7270 }
7271
7272 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7273 const ParmVarDecl *P = FD->getParamDecl(i: I);
7274
7275 // The [[lifetimebound]] attribute can be applied to a function parameter
7276 // only if the function returns a value.
7277 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7278 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7279 S.Diag(Loc: A->getLocation(),
7280 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7281 }
7282 }
7283 }
7284 }
7285}
7286
7287static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7288 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7289 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_modular_format_attribute_no_format);
7290}
7291
7292static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7293 // Ensure that an auto decl is deduced otherwise the checks below might cache
7294 // the wrong linkage.
7295 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7296
7297 checkWeakAttr(S, ND);
7298 checkWeakRefAttr(S, ND);
7299 checkAliasAttr(S, ND);
7300 checkSelectAnyAttr(S, ND);
7301 checkHybridPatchableAttr(S, ND);
7302 checkInheritableAttr(S, ND);
7303 checkLifetimeBoundAttr(S, ND);
7304}
7305
7306static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7307 NamedDecl *NewDecl,
7308 bool IsSpecialization,
7309 bool IsDefinition) {
7310 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7311 return;
7312
7313 bool IsTemplate = false;
7314 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7315 OldDecl = OldTD->getTemplatedDecl();
7316 IsTemplate = true;
7317 if (!IsSpecialization)
7318 IsDefinition = false;
7319 }
7320 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7321 NewDecl = NewTD->getTemplatedDecl();
7322 IsTemplate = true;
7323 }
7324
7325 if (!OldDecl || !NewDecl)
7326 return;
7327
7328 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7329 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7330 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7331 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7332
7333 // dllimport and dllexport are inheritable attributes so we have to exclude
7334 // inherited attribute instances.
7335 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7336 (NewExportAttr && !NewExportAttr->isInherited());
7337
7338 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7339 // the only exception being explicit specializations.
7340 // Implicitly generated declarations are also excluded for now because there
7341 // is no other way to switch these to use dllimport or dllexport.
7342 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7343
7344 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7345 // Allow with a warning for free functions and global variables.
7346 bool JustWarn = false;
7347 if (!OldDecl->isCXXClassMember()) {
7348 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7349 if (VD && !VD->getDescribedVarTemplate())
7350 JustWarn = true;
7351 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7352 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7353 JustWarn = true;
7354 }
7355
7356 // We cannot change a declaration that's been used because IR has already
7357 // been emitted. Dllimported functions will still work though (modulo
7358 // address equality) as they can use the thunk.
7359 if (OldDecl->isUsed())
7360 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7361 JustWarn = false;
7362
7363 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7364 : diag::err_attribute_dll_redeclaration;
7365 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7366 << NewDecl
7367 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7368 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7369 if (!JustWarn) {
7370 NewDecl->setInvalidDecl();
7371 return;
7372 }
7373 }
7374
7375 // A redeclaration is not allowed to drop a dllimport attribute, the only
7376 // exceptions being inline function definitions (except for function
7377 // templates), local extern declarations, qualified friend declarations or
7378 // special MSVC extension: in the last case, the declaration is treated as if
7379 // it were marked dllexport.
7380 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7381 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7382 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7383 // Ignore static data because out-of-line definitions are diagnosed
7384 // separately.
7385 IsStaticDataMember = VD->isStaticDataMember();
7386 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7387 VarDecl::DeclarationOnly;
7388 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7389 IsInline = FD->isInlined();
7390 IsQualifiedFriend = FD->getQualifier() &&
7391 FD->getFriendObjectKind() == Decl::FOK_Declared;
7392 }
7393
7394 if (OldImportAttr && !HasNewAttr &&
7395 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7396 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7397 if (IsMicrosoftABI && IsDefinition) {
7398 if (IsSpecialization) {
7399 S.Diag(
7400 Loc: NewDecl->getLocation(),
7401 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7402 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7403 NewDecl->dropAttr<DLLImportAttr>();
7404 } else {
7405 S.Diag(Loc: NewDecl->getLocation(),
7406 DiagID: diag::warn_redeclaration_without_import_attribute)
7407 << NewDecl;
7408 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7409 NewDecl->dropAttr<DLLImportAttr>();
7410 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7411 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7412 }
7413 } else if (IsMicrosoftABI && IsSpecialization) {
7414 assert(!IsDefinition);
7415 // MSVC allows this. Keep the inherited attribute.
7416 } else {
7417 S.Diag(Loc: NewDecl->getLocation(),
7418 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7419 << NewDecl << OldImportAttr;
7420 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7421 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7422 OldDecl->dropAttr<DLLImportAttr>();
7423 NewDecl->dropAttr<DLLImportAttr>();
7424 }
7425 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7426 // In MinGW, seeing a function declared inline drops the dllimport
7427 // attribute.
7428 OldDecl->dropAttr<DLLImportAttr>();
7429 NewDecl->dropAttr<DLLImportAttr>();
7430 S.Diag(Loc: NewDecl->getLocation(),
7431 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7432 << NewDecl << OldImportAttr;
7433 }
7434
7435 // A specialization of a class template member function is processed here
7436 // since it's a redeclaration. If the parent class is dllexport, the
7437 // specialization inherits that attribute. This doesn't happen automatically
7438 // since the parent class isn't instantiated until later.
7439 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7440 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7441 !NewImportAttr && !NewExportAttr) {
7442 if (const DLLExportAttr *ParentExportAttr =
7443 MD->getParent()->getAttr<DLLExportAttr>()) {
7444 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7445 NewAttr->setInherited(true);
7446 NewDecl->addAttr(A: NewAttr);
7447 }
7448 }
7449 }
7450}
7451
7452/// Given that we are within the definition of the given function,
7453/// will that definition behave like C99's 'inline', where the
7454/// definition is discarded except for optimization purposes?
7455static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7456 // Try to avoid calling GetGVALinkageForFunction.
7457
7458 // All cases of this require the 'inline' keyword.
7459 if (!FD->isInlined()) return false;
7460
7461 // This is only possible in C++ with the gnu_inline attribute.
7462 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7463 return false;
7464
7465 // Okay, go ahead and call the relatively-more-expensive function.
7466 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7467}
7468
7469/// Determine whether a variable is extern "C" prior to attaching
7470/// an initializer. We can't just call isExternC() here, because that
7471/// will also compute and cache whether the declaration is externally
7472/// visible, which might change when we attach the initializer.
7473///
7474/// This can only be used if the declaration is known to not be a
7475/// redeclaration of an internal linkage declaration.
7476///
7477/// For instance:
7478///
7479/// auto x = []{};
7480///
7481/// Attaching the initializer here makes this declaration not externally
7482/// visible, because its type has internal linkage.
7483///
7484/// FIXME: This is a hack.
7485template<typename T>
7486static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7487 if (S.getLangOpts().CPlusPlus) {
7488 // In C++, the overloadable attribute negates the effects of extern "C".
7489 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7490 return false;
7491
7492 // So do CUDA's host/device attributes.
7493 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7494 D->template hasAttr<CUDAHostAttr>()))
7495 return false;
7496 }
7497 return D->isExternC();
7498}
7499
7500static bool shouldConsiderLinkage(const VarDecl *VD) {
7501 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7502 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7503 isa<OMPDeclareMapperDecl>(Val: DC))
7504 return VD->hasExternalStorage();
7505 if (DC->isFileContext())
7506 return true;
7507 if (DC->isRecord())
7508 return false;
7509 if (DC->getDeclKind() == Decl::HLSLBuffer)
7510 return false;
7511
7512 if (isa<RequiresExprBodyDecl, CXXExpansionStmtDecl>(Val: DC))
7513 return false;
7514 llvm_unreachable("Unexpected context");
7515}
7516
7517static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7518 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7519 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7520 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7521 return true;
7522 if (DC->isRecord() || isa<CXXExpansionStmtDecl>(Val: DC))
7523 return false;
7524 llvm_unreachable("Unexpected context");
7525}
7526
7527static bool hasParsedAttr(Scope *S, const Declarator &PD,
7528 ParsedAttr::Kind Kind) {
7529 // Check decl attributes on the DeclSpec.
7530 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7531 return true;
7532
7533 // Walk the declarator structure, checking decl attributes that were in a type
7534 // position to the decl itself.
7535 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7536 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7537 return true;
7538 }
7539
7540 // Finally, check attributes on the decl itself.
7541 return PD.getAttributes().hasAttribute(K: Kind) ||
7542 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7543}
7544
7545bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7546 if (!DC->getEnclosingNonExpansionStatementContext()->isFunctionOrMethod())
7547 return false;
7548
7549 // If this is a local extern function or variable declared within a function
7550 // template, don't add it into the enclosing namespace scope until it is
7551 // instantiated; it might have a dependent type right now.
7552 if (DC->isDependentContext())
7553 return true;
7554
7555 // C++11 [basic.link]p7:
7556 // When a block scope declaration of an entity with linkage is not found to
7557 // refer to some other declaration, then that entity is a member of the
7558 // innermost enclosing namespace.
7559 //
7560 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7561 // semantically-enclosing namespace, not a lexically-enclosing one.
7562 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7563 DC = DC->getParent();
7564 return true;
7565}
7566
7567/// Returns true if given declaration has external C language linkage.
7568static bool isDeclExternC(const Decl *D) {
7569 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7570 return FD->isExternC();
7571 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7572 return VD->isExternC();
7573
7574 llvm_unreachable("Unknown type of decl!");
7575}
7576
7577/// Returns true if there hasn't been any invalid type diagnosed.
7578static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7579 DeclContext *DC = NewVD->getDeclContext();
7580 QualType R = NewVD->getType();
7581
7582 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7583 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7584 // argument.
7585 if (R->isImageType() || R->isPipeType()) {
7586 Se.Diag(Loc: NewVD->getLocation(),
7587 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7588 << R;
7589 NewVD->setInvalidDecl();
7590 return false;
7591 }
7592
7593 // OpenCL v1.2 s6.9.r:
7594 // The event type cannot be used to declare a program scope variable.
7595 // OpenCL v2.0 s6.9.q:
7596 // The clk_event_t and reserve_id_t types cannot be declared in program
7597 // scope.
7598 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7599 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7600 Se.Diag(Loc: NewVD->getLocation(),
7601 DiagID: diag::err_invalid_type_for_program_scope_var)
7602 << R;
7603 NewVD->setInvalidDecl();
7604 return false;
7605 }
7606 }
7607
7608 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7609 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7610 LO: Se.getLangOpts())) {
7611 QualType NR = R.getCanonicalType();
7612 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7613 NR->isReferenceType()) {
7614 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7615 NR->isFunctionReferenceType()) {
7616 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7617 << NR->isReferenceType();
7618 NewVD->setInvalidDecl();
7619 return false;
7620 }
7621 NR = NR->getPointeeType();
7622 }
7623 }
7624
7625 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7626 LO: Se.getLangOpts())) {
7627 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7628 // half array type (unless the cl_khr_fp16 extension is enabled).
7629 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7630 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7631 NewVD->setInvalidDecl();
7632 return false;
7633 }
7634 }
7635
7636 // OpenCL v1.2 s6.9.r:
7637 // The event type cannot be used with the __local, __constant and __global
7638 // address space qualifiers.
7639 if (R->isEventT()) {
7640 if (R.getAddressSpace() != LangAS::opencl_private) {
7641 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7642 NewVD->setInvalidDecl();
7643 return false;
7644 }
7645 }
7646
7647 if (R->isSamplerT()) {
7648 // OpenCL v1.2 s6.9.b p4:
7649 // The sampler type cannot be used with the __local and __global address
7650 // space qualifiers.
7651 if (R.getAddressSpace() == LangAS::opencl_local ||
7652 R.getAddressSpace() == LangAS::opencl_global) {
7653 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7654 NewVD->setInvalidDecl();
7655 }
7656
7657 // OpenCL v1.2 s6.12.14.1:
7658 // A global sampler must be declared with either the constant address
7659 // space qualifier or with the const qualifier.
7660 if (DC->isTranslationUnit() &&
7661 !(R.getAddressSpace() == LangAS::opencl_constant ||
7662 R.isConstQualified())) {
7663 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7664 NewVD->setInvalidDecl();
7665 }
7666 if (NewVD->isInvalidDecl())
7667 return false;
7668 }
7669
7670 return true;
7671}
7672
7673template <typename AttrTy>
7674static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7675 const TypedefNameDecl *TND = TT->getDecl();
7676 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7677 AttrTy *Clone = Attribute->clone(S.Context);
7678 Clone->setInherited(true);
7679 D->addAttr(A: Clone);
7680 }
7681}
7682
7683// This function emits warning and a corresponding note based on the
7684// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7685// declarations of an annotated type must be const qualified.
7686static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7687 QualType VarType = VD->getType().getCanonicalType();
7688
7689 // Ignore local declarations (for now) and those with const qualification.
7690 // TODO: Local variables should not be allowed if their type declaration has
7691 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7692 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7693 return;
7694
7695 if (VarType->isArrayType()) {
7696 // Retrieve element type for array declarations.
7697 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7698 }
7699
7700 const RecordDecl *RD = VarType->getAsRecordDecl();
7701
7702 // Check if the record declaration is present and if it has any attributes.
7703 if (RD == nullptr)
7704 return;
7705
7706 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7707 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7708 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7709 return;
7710 }
7711}
7712
7713void Sema::ProcessPragmaExport(DeclaratorDecl *NewD) {
7714 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7715 "NewD is not a function or variable");
7716
7717 if (PendingExportedNames.empty())
7718 return;
7719 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: NewD)) {
7720 if (getLangOpts().CPlusPlus && !FD->isExternC())
7721 return;
7722 }
7723 IdentifierInfo *IdentName = NewD->getIdentifier();
7724 if (IdentName == nullptr)
7725 return;
7726 auto PendingName = PendingExportedNames.find(Val: IdentName);
7727 if (PendingName != PendingExportedNames.end()) {
7728 auto &Label = PendingName->second;
7729 if (!Label.Used) {
7730 Label.Used = true;
7731 if (NewD->hasExternalFormalLinkage())
7732 mergeVisibilityType(D: NewD, Loc: Label.NameLoc, Type: VisibilityAttr::Default);
7733 else
7734 Diag(Loc: Label.NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << NewD;
7735 }
7736 }
7737}
7738
7739// Checks if VD is declared at global scope or with C language linkage.
7740static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7741 return Name.getAsIdentifierInfo() &&
7742 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7743 !VD->getDescribedVarTemplate() &&
7744 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7745 VD->isExternC());
7746}
7747
7748void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7749 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7750
7751 // Quickly return if the function does not have an `asm` attribute.
7752 if (E == nullptr)
7753 return;
7754
7755 // The parser guarantees this is a string.
7756 StringLiteral *SE = cast<StringLiteral>(Val: E);
7757 StringRef Label = SE->getString();
7758 QualType R = TInfo->getType();
7759 if (S->getFnParent() != nullptr) {
7760 switch (SC) {
7761 case SC_None:
7762 case SC_Auto:
7763 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
7764 break;
7765 case SC_Register:
7766 // Local Named register
7767 if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) &&
7768 DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl()))
7769 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7770 break;
7771 case SC_Static:
7772 case SC_Extern:
7773 case SC_PrivateExtern:
7774 break;
7775 }
7776 } else if (SC == SC_Register) {
7777 // Global Named register
7778 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
7779 const auto &TI = Context.getTargetInfo();
7780 bool HasSizeMismatch;
7781
7782 if (!TI.isValidGCCRegisterName(Name: Label))
7783 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7784 else if (!TI.validateGlobalRegisterVariable(RegName: Label, RegSize: Context.getTypeSize(T: R),
7785 HasSizeMismatch))
7786 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
7787 else if (HasSizeMismatch)
7788 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
7789 }
7790
7791 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
7792 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
7793 DiagID: diag::err_asm_unsupported_register_type)
7794 << TInfo->getTypeLoc().getSourceRange();
7795 NewVD->setInvalidDecl(true);
7796 }
7797 }
7798}
7799
7800NamedDecl *Sema::ActOnVariableDeclarator(
7801 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7802 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7803 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7804 QualType R = TInfo->getType();
7805 DeclarationName Name = GetNameForDeclarator(D).getName();
7806
7807 IdentifierInfo *II = Name.getAsIdentifierInfo();
7808 bool IsPlaceholderVariable = false;
7809
7810 if (D.isDecompositionDeclarator()) {
7811 // Take the name of the first declarator as our name for diagnostic
7812 // purposes.
7813 auto &Decomp = D.getDecompositionDeclarator();
7814 if (!Decomp.bindings().empty()) {
7815 II = Decomp.bindings()[0].Name;
7816 Name = II;
7817 }
7818 } else if (!II) {
7819 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7820 return nullptr;
7821 }
7822
7823
7824 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7825 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7826 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7827 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7828
7829 IsPlaceholderVariable = true;
7830
7831 if (!Previous.empty()) {
7832 NamedDecl *PrevDecl = *Previous.begin();
7833 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7834 DC: DC->getRedeclContext());
7835 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7836 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7837 if (IsPlaceholderVariable)
7838 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7839 }
7840 }
7841 }
7842
7843 // dllimport globals without explicit storage class are treated as extern. We
7844 // have to change the storage class this early to get the right DeclContext.
7845 if (SC == SC_None && !DC->isRecord() &&
7846 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7847 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7848 SC = SC_Extern;
7849
7850 DeclContext *OriginalDC = DC;
7851 bool IsLocalExternDecl = SC == SC_Extern &&
7852 adjustContextForLocalExternDecl(DC);
7853
7854 if (SCSpec == DeclSpec::SCS_mutable) {
7855 // mutable can only appear on non-static class members, so it's always
7856 // an error here
7857 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7858 D.setInvalidType();
7859 SC = SC_None;
7860 }
7861
7862 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7863 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7864 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7865 // In C++11, the 'register' storage class specifier is deprecated.
7866 // Suppress the warning in system macros, it's used in macros in some
7867 // popular C system headers, such as in glibc's htonl() macro.
7868 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7869 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7870 : diag::warn_deprecated_register)
7871 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7872 }
7873
7874 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7875
7876 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7877 // C99 6.9p2: The storage-class specifiers auto and register shall not
7878 // appear in the declaration specifiers in an external declaration.
7879 // Global Register+Asm is a GNU extension we support.
7880 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7881 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7882 D.setInvalidType();
7883 }
7884 }
7885
7886 // If this variable has a VLA type and an initializer, try to
7887 // fold to a constant-sized type. This is otherwise invalid.
7888 if (D.hasInitializer() && R->isVariableArrayType())
7889 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7890 /*DiagID=*/FailedFoldDiagID: 0);
7891
7892 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7893 const AutoType *AT = TL.getTypePtr();
7894 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7895 }
7896
7897 bool IsMemberSpecialization = false;
7898 bool IsVariableTemplateSpecialization = false;
7899 bool IsPartialSpecialization = false;
7900 bool IsVariableTemplate = false;
7901 VarDecl *NewVD = nullptr;
7902 VarTemplateDecl *NewTemplate = nullptr;
7903 TemplateParameterList *TemplateParams = nullptr;
7904 if (!getLangOpts().CPlusPlus) {
7905 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7906 Id: II, T: R, TInfo, S: SC);
7907
7908 if (R->getContainedDeducedType())
7909 ParsingInitForAutoVars.insert(Ptr: NewVD);
7910
7911 if (D.isInvalidType())
7912 NewVD->setInvalidDecl();
7913
7914 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7915 NewVD->hasLocalStorage())
7916 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7917 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7918 } else {
7919 bool Invalid = false;
7920 // Match up the template parameter lists with the scope specifier, then
7921 // determine whether we have a template or a template specialization.
7922 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7923 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7924 SS: D.getCXXScopeSpec(),
7925 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7926 ? D.getName().TemplateId
7927 : nullptr,
7928 ParamLists: TemplateParamLists,
7929 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7930
7931 if (TemplateParams) {
7932 if (DC->isDependentContext()) {
7933 ContextRAII SavedContext(*this, DC);
7934 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7935 Invalid = true;
7936 }
7937
7938 if (!TemplateParams->size() &&
7939 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7940 // There is an extraneous 'template<>' for this variable. Complain
7941 // about it, but allow the declaration of the variable.
7942 Diag(Loc: TemplateParams->getTemplateLoc(),
7943 DiagID: diag::err_template_variable_noparams)
7944 << II
7945 << SourceRange(TemplateParams->getTemplateLoc(),
7946 TemplateParams->getRAngleLoc());
7947 TemplateParams = nullptr;
7948 } else {
7949 // Check that we can declare a template here.
7950 if (CheckTemplateDeclScope(S, TemplateParams))
7951 return nullptr;
7952
7953 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7954 // This is an explicit specialization or a partial specialization.
7955 IsVariableTemplateSpecialization = true;
7956 IsPartialSpecialization = TemplateParams->size() > 0;
7957 } else { // if (TemplateParams->size() > 0)
7958 // This is a template declaration.
7959 IsVariableTemplate = true;
7960
7961 // Only C++1y supports variable templates (N3651).
7962 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
7963 }
7964 }
7965 } else {
7966 // Check that we can declare a member specialization here.
7967 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7968 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7969 return nullptr;
7970 assert((Invalid ||
7971 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7972 "should have a 'template<>' for this decl");
7973 }
7974
7975 bool IsExplicitSpecialization =
7976 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7977
7978 // C++ [temp.expl.spec]p2:
7979 // The declaration in an explicit-specialization shall not be an
7980 // export-declaration. An explicit specialization shall not use a
7981 // storage-class-specifier other than thread_local.
7982 //
7983 // We use the storage-class-specifier from DeclSpec because we may have
7984 // added implicit 'extern' for declarations with __declspec(dllimport)!
7985 if (SCSpec != DeclSpec::SCS_unspecified &&
7986 (IsExplicitSpecialization || IsMemberSpecialization)) {
7987 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7988 DiagID: diag::ext_explicit_specialization_storage_class)
7989 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7990 }
7991
7992 if (CurContext->isRecord()) {
7993 if (SC == SC_Static) {
7994 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7995 // Walk up the enclosing DeclContexts to check for any that are
7996 // incompatible with static data members.
7997 const DeclContext *FunctionOrMethod = nullptr;
7998 const CXXRecordDecl *AnonStruct = nullptr;
7999 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
8000 if (Ctxt->isFunctionOrMethod()) {
8001 FunctionOrMethod = Ctxt;
8002 break;
8003 }
8004 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
8005 if (ParentDecl && !ParentDecl->getDeclName()) {
8006 AnonStruct = ParentDecl;
8007 break;
8008 }
8009 }
8010 if (FunctionOrMethod) {
8011 // C++ [class.static.data]p5: A local class shall not have static
8012 // data members.
8013 Diag(Loc: D.getIdentifierLoc(),
8014 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
8015 << Name << RD->getDeclName() << RD->getTagKind();
8016 Invalid = true;
8017 } else if (AnonStruct) {
8018 // C++ [class.static.data]p4: Unnamed classes and classes contained
8019 // directly or indirectly within unnamed classes shall not contain
8020 // static data members.
8021 Diag(Loc: D.getIdentifierLoc(),
8022 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
8023 << Name << AnonStruct->getTagKind();
8024 Invalid = true;
8025 } else if (RD->isUnion()) {
8026 // C++98 [class.union]p1: If a union contains a static data member,
8027 // the program is ill-formed. C++11 drops this restriction.
8028 DiagCompat(Loc: D.getIdentifierLoc(),
8029 CompatDiagId: diag_compat::static_data_member_in_union)
8030 << Name;
8031 }
8032 }
8033 } else if (IsVariableTemplate || IsPartialSpecialization) {
8034 // There is no such thing as a member field template.
8035 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
8036 << II << TemplateParams->getSourceRange();
8037 // Recover by pretending this is a static data member template.
8038 SC = SC_Static;
8039 }
8040 } else if (DC->isRecord()) {
8041 // This is an out-of-line definition of a static data member.
8042 switch (SC) {
8043 case SC_None:
8044 break;
8045 case SC_Static:
8046 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8047 DiagID: diag::err_static_out_of_line)
8048 << FixItHint::CreateRemoval(
8049 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8050 break;
8051 case SC_Auto:
8052 case SC_Register:
8053 case SC_Extern:
8054 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8055 // to names of variables declared in a block or to function parameters.
8056 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8057 // of class members
8058
8059 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8060 DiagID: diag::err_storage_class_for_static_member)
8061 << FixItHint::CreateRemoval(
8062 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8063 break;
8064 case SC_PrivateExtern:
8065 llvm_unreachable("C storage class in c++!");
8066 }
8067 }
8068
8069 if (IsVariableTemplateSpecialization) {
8070 SourceLocation TemplateKWLoc =
8071 TemplateParamLists.size() > 0
8072 ? TemplateParamLists[0]->getTemplateLoc()
8073 : SourceLocation();
8074 DeclResult Res = ActOnVarTemplateSpecialization(
8075 S, D, TSI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8076 IsPartialSpecialization);
8077 if (Res.isInvalid())
8078 return nullptr;
8079 NewVD = cast<VarDecl>(Val: Res.get());
8080 AddToScope = false;
8081 } else if (D.isDecompositionDeclarator()) {
8082 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8083 LSquareLoc: D.getIdentifierLoc(), RSquareLoc: D.getEndLoc(), T: R,
8084 TInfo, S: SC, Bindings);
8085 } else
8086 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8087 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
8088
8089 // If this is supposed to be a variable template, create it as such.
8090 if (IsVariableTemplate) {
8091 NewTemplate =
8092 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
8093 Params: TemplateParams, Decl: NewVD);
8094 NewVD->setDescribedVarTemplate(NewTemplate);
8095 }
8096
8097 // If this decl has an auto type in need of deduction, make a note of the
8098 // Decl so we can diagnose uses of it in its own initializer.
8099 if (R->getContainedDeducedType())
8100 ParsingInitForAutoVars.insert(Ptr: NewVD);
8101
8102 if (D.isInvalidType() || Invalid) {
8103 NewVD->setInvalidDecl();
8104 if (NewTemplate)
8105 NewTemplate->setInvalidDecl();
8106 }
8107
8108 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
8109
8110 // If we have any template parameter lists that don't directly belong to
8111 // the variable (matching the scope specifier), store them.
8112 // An explicit variable template specialization does not own any template
8113 // parameter lists.
8114 unsigned VDTemplateParamLists =
8115 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8116 if (TemplateParamLists.size() > VDTemplateParamLists)
8117 NewVD->setTemplateParameterListsInfo(
8118 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
8119 }
8120
8121 if (D.getDeclSpec().isInlineSpecified()) {
8122 if (!getLangOpts().CPlusPlus) {
8123 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
8124 << 0;
8125 } else if (CurContext->isFunctionOrMethod()) {
8126 // 'inline' is not allowed on block scope variable declaration.
8127 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8128 DiagID: diag::err_inline_declaration_block_scope) << Name
8129 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
8130 } else {
8131 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8132 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8133 : diag::compat_pre_cxx17_inline_variable);
8134 NewVD->setInlineSpecified();
8135 }
8136 }
8137
8138 // Set the lexical context. If the declarator has a C++ scope specifier, the
8139 // lexical context will be different from the semantic context.
8140 NewVD->setLexicalDeclContext(CurContext);
8141 if (NewTemplate)
8142 NewTemplate->setLexicalDeclContext(CurContext);
8143
8144 if (IsLocalExternDecl) {
8145 if (D.isDecompositionDeclarator())
8146 for (auto *B : Bindings)
8147 B->setLocalExternDecl();
8148 else
8149 NewVD->setLocalExternDecl();
8150 }
8151
8152 bool EmitTLSUnsupportedError = false;
8153 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8154 // C++11 [dcl.stc]p4:
8155 // When thread_local is applied to a variable of block scope the
8156 // storage-class-specifier static is implied if it does not appear
8157 // explicitly.
8158 // Core issue: 'static' is not implied if the variable is declared
8159 // 'extern'.
8160 if (NewVD->hasLocalStorage() &&
8161 (SCSpec != DeclSpec::SCS_unspecified ||
8162 TSCS != DeclSpec::TSCS_thread_local ||
8163 !DC->isFunctionOrMethod()))
8164 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8165 DiagID: diag::err_thread_non_global)
8166 << DeclSpec::getSpecifierName(S: TSCS);
8167 else if (!Context.getTargetInfo().isTLSSupported()) {
8168 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8169 // Postpone error emission until we've collected attributes required to
8170 // figure out whether it's a host or device variable and whether the
8171 // error should be ignored.
8172 EmitTLSUnsupportedError = true;
8173 // We still need to mark the variable as TLS so it shows up in AST with
8174 // proper storage class for other tools to use even if we're not going
8175 // to emit any code for it.
8176 NewVD->setTSCSpec(TSCS);
8177 } else
8178 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8179 DiagID: diag::err_thread_unsupported);
8180 } else
8181 NewVD->setTSCSpec(TSCS);
8182 }
8183
8184 switch (D.getDeclSpec().getConstexprSpecifier()) {
8185 case ConstexprSpecKind::Unspecified:
8186 break;
8187
8188 case ConstexprSpecKind::Consteval:
8189 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8190 DiagID: diag::err_constexpr_wrong_decl_kind)
8191 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8192 [[fallthrough]];
8193
8194 case ConstexprSpecKind::Constexpr:
8195 NewVD->setConstexpr(true);
8196 // C++1z [dcl.spec.constexpr]p1:
8197 // A static data member declared with the constexpr specifier is
8198 // implicitly an inline variable.
8199 if (NewVD->isStaticDataMember() &&
8200 (getLangOpts().CPlusPlus17 ||
8201 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8202 NewVD->setImplicitlyInline();
8203 break;
8204
8205 case ConstexprSpecKind::Constinit:
8206 if (!NewVD->hasGlobalStorage())
8207 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8208 DiagID: diag::err_constinit_local_variable);
8209 else
8210 NewVD->addAttr(
8211 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
8212 S: ConstInitAttr::Keyword_constinit));
8213 break;
8214 }
8215
8216 // C99 6.7.4p3
8217 // An inline definition of a function with external linkage shall
8218 // not contain a definition of a modifiable object with static or
8219 // thread storage duration...
8220 // We only apply this when the function is required to be defined
8221 // elsewhere, i.e. when the function is not 'extern inline'. Note
8222 // that a local variable with thread storage duration still has to
8223 // be marked 'static'. Also note that it's possible to get these
8224 // semantics in C++ using __attribute__((gnu_inline)).
8225 if (SC == SC_Static && S->getFnParent() != nullptr &&
8226 !NewVD->getType().isConstQualified()) {
8227 FunctionDecl *CurFD = getCurFunctionDecl();
8228 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
8229 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8230 DiagID: diag::warn_static_local_in_extern_inline);
8231 MaybeSuggestAddingStaticToDecl(D: CurFD);
8232 }
8233 }
8234
8235 if (D.getDeclSpec().isModulePrivateSpecified()) {
8236 if (IsVariableTemplateSpecialization)
8237 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8238 << (IsPartialSpecialization ? 1 : 0)
8239 << FixItHint::CreateRemoval(
8240 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8241 else if (IsMemberSpecialization)
8242 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8243 << 2
8244 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8245 else if (NewVD->hasLocalStorage())
8246 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
8247 << 0 << NewVD
8248 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8249 << FixItHint::CreateRemoval(
8250 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8251 else {
8252 NewVD->setModulePrivate();
8253 if (NewTemplate)
8254 NewTemplate->setModulePrivate();
8255 for (auto *B : Bindings)
8256 B->setModulePrivate();
8257 }
8258 }
8259
8260 if (getLangOpts().OpenCL) {
8261 deduceOpenCLAddressSpace(Var: NewVD);
8262
8263 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8264 if (TSC != TSCS_unspecified) {
8265 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8266 DiagID: diag::err_opencl_unknown_type_specifier)
8267 << getLangOpts().getOpenCLVersionString()
8268 << DeclSpec::getSpecifierName(S: TSC) << 1;
8269 NewVD->setInvalidDecl();
8270 }
8271 }
8272
8273 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8274 // address space if the table has local storage (semantic checks elsewhere
8275 // will produce an error anyway).
8276 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8277 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8278 !NewVD->hasLocalStorage()) {
8279 QualType Type = Context.getAddrSpaceQualType(
8280 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8281 NewVD->setType(Type);
8282 }
8283 }
8284
8285 LoadExternalExtnameUndeclaredIdentifiers();
8286
8287 if (Expr *E = D.getAsmLabel()) {
8288 // The parser guarantees this is a string.
8289 StringLiteral *SE = cast<StringLiteral>(Val: E);
8290 StringRef Label = SE->getString();
8291
8292 // Insert the asm attribute.
8293 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, Range: SE->getStrTokenLoc(TokNum: 0)));
8294 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8295 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8296 ExtnameUndeclaredIdentifiers.find(Key: NewVD->getIdentifier());
8297 if (I != ExtnameUndeclaredIdentifiers.end()) {
8298 if (isDeclExternC(D: NewVD)) {
8299 NewVD->addAttr(A: I->second);
8300 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
8301 } else if (NewVD->getDeclContext()
8302 ->getRedeclContext()
8303 ->isTranslationUnit())
8304 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8305 << /*Variable*/ 1 << NewVD;
8306 }
8307 }
8308
8309 // Handle attributes prior to checking for duplicates in MergeVarDecl
8310 ProcessDeclAttributes(S, D: NewVD, PD: D);
8311
8312 if (getLangOpts().HLSL)
8313 HLSL().ActOnVariableDeclarator(VD: NewVD);
8314
8315 if (getLangOpts().OpenACC)
8316 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8317
8318 // FIXME: This is probably the wrong location to be doing this and we should
8319 // probably be doing this for more attributes (especially for function
8320 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8321 // the code to copy attributes would be generated by TableGen.
8322 if (R->isFunctionPointerType())
8323 if (const auto *TT = R->getAs<TypedefType>())
8324 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8325
8326 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8327 if (EmitTLSUnsupportedError &&
8328 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8329 (getLangOpts().OpenMPIsTargetDevice &&
8330 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8331 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8332 DiagID: diag::err_thread_unsupported);
8333
8334 if (EmitTLSUnsupportedError &&
8335 (LangOpts.SYCLIsDevice ||
8336 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8337 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8338 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8339 // storage [duration]."
8340 if (SC == SC_None && S->getFnParent() != nullptr &&
8341 (NewVD->hasAttr<CUDASharedAttr>() ||
8342 NewVD->hasAttr<CUDAConstantAttr>())) {
8343 NewVD->setStorageClass(SC_Static);
8344 }
8345 }
8346
8347 // Ensure that dllimport globals without explicit storage class are treated as
8348 // extern. The storage class is set above using parsed attributes. Now we can
8349 // check the VarDecl itself.
8350 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8351 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8352 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8353
8354 // In auto-retain/release, infer strong retension for variables of
8355 // retainable type.
8356 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8357 NewVD->setInvalidDecl();
8358
8359 // Check the ASM label here, as we need to know all other attributes of the
8360 // Decl first. Otherwise, we can't know if the asm label refers to the
8361 // host or device in a CUDA context. The device has other registers than
8362 // host and we must know where the function will be placed.
8363 CheckAsmLabel(S, E: D.getAsmLabel(), SC, TInfo, NewVD);
8364
8365 // Find the shadowed declaration before filtering for scope.
8366 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8367 ? getShadowedDeclaration(D: NewVD, R: Previous)
8368 : nullptr;
8369
8370 // Don't consider existing declarations that are in a different
8371 // scope and are out-of-semantic-context declarations (if the new
8372 // declaration has linkage).
8373 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8374 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8375 IsMemberSpecialization ||
8376 IsVariableTemplateSpecialization);
8377
8378 // Check whether the previous declaration is in the same block scope. This
8379 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8380 if (getLangOpts().CPlusPlus &&
8381 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8382 NewVD->setPreviousDeclInSameBlockScope(
8383 Previous.isSingleResult() && !Previous.isShadowed() &&
8384 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8385
8386 if (!getLangOpts().CPlusPlus) {
8387 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8388 } else {
8389 // If this is an explicit specialization of a static data member, check it.
8390 if (IsMemberSpecialization && !IsVariableTemplate &&
8391 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8392 CheckMemberSpecialization(Member: NewVD, Previous))
8393 NewVD->setInvalidDecl();
8394
8395 // Merge the decl with the existing one if appropriate.
8396 if (!Previous.empty()) {
8397 if (Previous.isSingleResult() &&
8398 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8399 D.getCXXScopeSpec().isSet()) {
8400 // The user tried to define a non-static data member
8401 // out-of-line (C++ [dcl.meaning]p1).
8402 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8403 << D.getCXXScopeSpec().getRange();
8404 Previous.clear();
8405 NewVD->setInvalidDecl();
8406 }
8407 } else if (D.getCXXScopeSpec().isSet() &&
8408 !IsVariableTemplateSpecialization) {
8409 // No previous declaration in the qualifying scope.
8410 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8411 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8412 << D.getCXXScopeSpec().getRange();
8413 NewVD->setInvalidDecl();
8414
8415 // if this is a member specialization, we don't have any primary template
8416 // to be instantiated from. We set ourselves to a 'fake' clone of this so
8417 // that anything that attempts to refer to this invalid declaration can
8418 // act as if there IS a primary instantiation.
8419 if (NewTemplate && IsMemberSpecialization) {
8420 VarDecl *FakeVD =
8421 VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
8422 Id: II, T: R, TInfo, S: SC);
8423 FakeVD->setInvalidDecl();
8424 VarTemplateDecl *FakeInstantiatedFrom = VarTemplateDecl::Create(
8425 C&: Context, DC, L: D.getIdentifierLoc(), Name, Params: TemplateParams, Decl: FakeVD);
8426 FakeInstantiatedFrom->setInvalidDecl();
8427 NewTemplate->setInstantiatedFromMemberTemplate(FakeInstantiatedFrom);
8428 }
8429 }
8430
8431 if (!IsPlaceholderVariable)
8432 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8433
8434 // CheckVariableDeclaration will set NewVD as invalid if something is in
8435 // error like WebAssembly tables being declared as arrays with a non-zero
8436 // size, but then parsing continues and emits further errors on that line.
8437 // To avoid that we check here if it happened and return nullptr.
8438 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8439 return nullptr;
8440
8441 if (NewTemplate) {
8442 VarTemplateDecl *PrevVarTemplate =
8443 NewVD->getPreviousDecl()
8444 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8445 : nullptr;
8446
8447 // Check the template parameter list of this declaration, possibly
8448 // merging in the template parameter list from the previous variable
8449 // template declaration.
8450 if (CheckTemplateParameterList(
8451 NewParams: TemplateParams,
8452 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8453 : nullptr,
8454 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8455 DC->isDependentContext())
8456 ? TPC_ClassTemplateMember
8457 : TPC_Other))
8458 NewVD->setInvalidDecl();
8459 }
8460 }
8461
8462 if (IsMemberSpecialization) {
8463 if (NewTemplate && NewVD->getPreviousDecl()) {
8464 NewTemplate->setMemberSpecialization();
8465 } else if (IsPartialSpecialization) {
8466 cast<VarTemplatePartialSpecializationDecl>(Val: NewVD)
8467 ->setMemberSpecialization();
8468 }
8469 }
8470
8471 // Diagnose shadowed variables iff this isn't a redeclaration.
8472 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8473 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8474
8475 ProcessPragmaWeak(S, D: NewVD);
8476 ProcessPragmaExport(NewD: NewVD);
8477
8478 // If this is the first declaration of an extern C variable, update
8479 // the map of such variables.
8480 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8481 isIncompleteDeclExternC(S&: *this, D: NewVD))
8482 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8483
8484 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8485 MangleNumberingContext *MCtx;
8486 Decl *ManglingContextDecl;
8487 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8488 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8489 if (MCtx) {
8490 Context.setManglingNumber(
8491 ND: NewVD, Number: MCtx->getManglingNumber(
8492 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8493 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8494 }
8495 }
8496
8497 // Special handling of variable named 'main'.
8498 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8499 // C++ [basic.start.main]p3:
8500 // A program that declares
8501 // - a variable main at global scope, or
8502 // - an entity named main with C language linkage (in any namespace)
8503 // is ill-formed
8504 if (getLangOpts().CPlusPlus)
8505 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8506 << NewVD->isExternC();
8507
8508 // In C, and external-linkage variable named main results in undefined
8509 // behavior.
8510 else if (NewVD->hasExternalFormalLinkage())
8511 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8512 }
8513
8514 if (D.isRedeclaration() && !Previous.empty()) {
8515 NamedDecl *Prev = Previous.getRepresentativeDecl();
8516 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8517 IsDefinition: D.isFunctionDefinition());
8518 }
8519
8520 if (NewTemplate) {
8521 if (NewVD->isInvalidDecl())
8522 NewTemplate->setInvalidDecl();
8523 ActOnDocumentableDecl(D: NewTemplate);
8524 return NewTemplate;
8525 }
8526
8527 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8528 CompleteMemberSpecialization(Member: NewVD, Previous);
8529
8530 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8531
8532 return NewVD;
8533}
8534
8535/// Enum describing the %select options in diag::warn_decl_shadow.
8536enum ShadowedDeclKind {
8537 SDK_Local,
8538 SDK_Global,
8539 SDK_StaticMember,
8540 SDK_Field,
8541 SDK_Typedef,
8542 SDK_Using,
8543 SDK_StructuredBinding
8544};
8545
8546/// Determine what kind of declaration we're shadowing.
8547static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8548 const DeclContext *OldDC) {
8549 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8550 return SDK_Using;
8551 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8552 return SDK_Typedef;
8553 else if (isa<BindingDecl>(Val: ShadowedDecl))
8554 return SDK_StructuredBinding;
8555 else if (isa<RecordDecl>(Val: OldDC))
8556 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8557
8558 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8559}
8560
8561/// Return the location of the capture if the given lambda captures the given
8562/// variable \p VD, or an invalid source location otherwise.
8563static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8564 const ValueDecl *VD) {
8565 for (const Capture &Capture : LSI->Captures) {
8566 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8567 return Capture.getLocation();
8568 }
8569 return SourceLocation();
8570}
8571
8572static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8573 const LookupResult &R) {
8574 // Only diagnose if we're shadowing an unambiguous field or variable.
8575 if (R.getResultKind() != LookupResultKind::Found)
8576 return false;
8577
8578 // Return false if warning is ignored.
8579 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8580}
8581
8582NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8583 const LookupResult &R) {
8584 if (!shouldWarnIfShadowedDecl(Diags, R))
8585 return nullptr;
8586
8587 // Don't diagnose declarations at file scope.
8588 if (D->hasGlobalStorage() && !D->isStaticLocal())
8589 return nullptr;
8590
8591 NamedDecl *ShadowedDecl = R.getFoundDecl();
8592 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8593 : nullptr;
8594}
8595
8596NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8597 const LookupResult &R) {
8598 // Don't warn if typedef declaration is part of a class
8599 if (D->getDeclContext()->isRecord())
8600 return nullptr;
8601
8602 if (!shouldWarnIfShadowedDecl(Diags, R))
8603 return nullptr;
8604
8605 NamedDecl *ShadowedDecl = R.getFoundDecl();
8606 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8607}
8608
8609NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8610 const LookupResult &R) {
8611 if (!shouldWarnIfShadowedDecl(Diags, R))
8612 return nullptr;
8613
8614 NamedDecl *ShadowedDecl = R.getFoundDecl();
8615 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8616 : nullptr;
8617}
8618
8619void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8620 const LookupResult &R) {
8621 DeclContext *NewDC = D->getDeclContext();
8622
8623 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8624 if (const auto *MD =
8625 dyn_cast<CXXMethodDecl>(Val: getFunctionLevelDeclContext())) {
8626 // Fields aren't shadowed in C++ static members or in member functions
8627 // with an explicit object parameter.
8628 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8629 return;
8630 }
8631 // Fields shadowed by constructor parameters are a special case. Usually
8632 // the constructor initializes the field with the parameter.
8633 if (isa<CXXConstructorDecl>(Val: NewDC))
8634 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8635 // Remember that this was shadowed so we can either warn about its
8636 // modification or its existence depending on warning settings.
8637 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8638 return;
8639 }
8640 }
8641
8642 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8643 if (shadowedVar->isExternC()) {
8644 // For shadowing external vars, make sure that we point to the global
8645 // declaration, not a locally scoped extern declaration.
8646 for (auto *I : shadowedVar->redecls())
8647 if (I->isFileVarDecl()) {
8648 ShadowedDecl = I;
8649 break;
8650 }
8651 }
8652
8653 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8654
8655 unsigned WarningDiag = diag::warn_decl_shadow;
8656 SourceLocation CaptureLoc;
8657 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8658 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8659 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8660 // Handle both VarDecl and BindingDecl in lambda contexts
8661 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8662 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8663 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8664 if (RD->getLambdaCaptureDefault() == LCD_None) {
8665 // Try to avoid warnings for lambdas with an explicit capture
8666 // list. Warn only when the lambda captures the shadowed decl
8667 // explicitly.
8668 CaptureLoc = getCaptureLocation(LSI, VD);
8669 if (CaptureLoc.isInvalid())
8670 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8671 } else {
8672 // Remember that this was shadowed so we can avoid the warning if
8673 // the shadowed decl isn't captured and the warning settings allow
8674 // it.
8675 cast<LambdaScopeInfo>(Val: getCurFunction())
8676 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8677 return;
8678 }
8679 }
8680 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8681 // If lambda can capture this, then emit default shadowing warning,
8682 // Otherwise it is not really a shadowing case since field is not
8683 // available in lambda's body.
8684 // At this point we don't know that lambda can capture this, so
8685 // remember that this was shadowed and delay until we know.
8686 cast<LambdaScopeInfo>(Val: getCurFunction())
8687 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8688 return;
8689 }
8690 }
8691 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8692 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8693 bool HasLocalStorage = false;
8694 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl))
8695 HasLocalStorage = VD->hasLocalStorage();
8696 else if (const auto *BD = dyn_cast<BindingDecl>(Val: ShadowedDecl))
8697 HasLocalStorage =
8698 cast<VarDecl>(Val: BD->getDecomposedDecl())->hasLocalStorage();
8699
8700 if (HasLocalStorage) {
8701 // A variable can't shadow a local variable or binding in an enclosing
8702 // scope, if they are separated by a non-capturing declaration
8703 // context.
8704 for (DeclContext *ParentDC = NewDC;
8705 ParentDC && !ParentDC->Equals(DC: OldDC);
8706 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8707 // Only block literals, captured statements, and lambda expressions
8708 // can capture; other scopes don't.
8709 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8710 !isLambdaCallOperator(DC: ParentDC))
8711 return;
8712 }
8713 }
8714 }
8715 }
8716 }
8717
8718 // Never warn about shadowing a placeholder variable.
8719 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8720 return;
8721
8722 // Only warn about certain kinds of shadowing for class members.
8723 if (NewDC) {
8724 // In particular, don't warn about shadowing non-class members.
8725 if (NewDC->isRecord() && !OldDC->isRecord())
8726 return;
8727
8728 // Skip shadowing check if we're in a class scope, dealing with an enum
8729 // constant in a different context.
8730 DeclContext *ReDC = NewDC->getRedeclContext();
8731 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8732 return;
8733
8734 // TODO: should we warn about static data members shadowing
8735 // static data members from base classes?
8736
8737 // TODO: don't diagnose for inaccessible shadowed members.
8738 // This is hard to do perfectly because we might friend the
8739 // shadowing context, but that's just a false negative.
8740 }
8741
8742 DeclarationName Name = R.getLookupName();
8743
8744 // Emit warning and note.
8745 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8746 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8747 if (!CaptureLoc.isInvalid())
8748 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8749 << Name << /*explicitly*/ 1;
8750 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8751}
8752
8753void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8754 for (const auto &Shadow : LSI->ShadowingDecls) {
8755 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8756 // Try to avoid the warning when the shadowed decl isn't captured.
8757 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8758 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8759 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8760 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8761 Diag(Loc: Shadow.VD->getLocation(),
8762 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8763 : diag::warn_decl_shadow)
8764 << Shadow.VD->getDeclName()
8765 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8766 if (CaptureLoc.isValid())
8767 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8768 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8769 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8770 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8771 Diag(Loc: Shadow.VD->getLocation(),
8772 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8773 : diag::warn_decl_shadow_uncaptured_local)
8774 << Shadow.VD->getDeclName()
8775 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8776 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8777 }
8778 }
8779}
8780
8781void Sema::CheckShadow(Scope *S, VarDecl *D) {
8782 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8783 return;
8784
8785 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8786 Sema::LookupOrdinaryName,
8787 RedeclarationKind::ForVisibleRedeclaration);
8788 LookupName(R, S);
8789 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8790 CheckShadow(D, ShadowedDecl, R);
8791}
8792
8793/// Check if 'E', which is an expression that is about to be modified, refers
8794/// to a constructor parameter that shadows a field.
8795void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8796 // Quickly ignore expressions that can't be shadowing ctor parameters.
8797 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8798 return;
8799 E = E->IgnoreParenImpCasts();
8800 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8801 if (!DRE)
8802 return;
8803 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8804 auto I = ShadowingDecls.find(Val: D);
8805 if (I == ShadowingDecls.end())
8806 return;
8807 const NamedDecl *ShadowedDecl = I->second;
8808 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8809 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8810 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8811 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8812
8813 // Avoid issuing multiple warnings about the same decl.
8814 ShadowingDecls.erase(I);
8815}
8816
8817/// Check for conflict between this global or extern "C" declaration and
8818/// previous global or extern "C" declarations. This is only used in C++.
8819template<typename T>
8820static bool checkGlobalOrExternCConflict(
8821 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8822 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8823 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8824
8825 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8826 // The common case: this global doesn't conflict with any extern "C"
8827 // declaration.
8828 return false;
8829 }
8830
8831 if (Prev) {
8832 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8833 // Both the old and new declarations have C language linkage. This is a
8834 // redeclaration.
8835 Previous.clear();
8836 Previous.addDecl(D: Prev);
8837 return true;
8838 }
8839
8840 // This is a global, non-extern "C" declaration, and there is a previous
8841 // non-global extern "C" declaration. Diagnose if this is a variable
8842 // declaration.
8843 if (!isa<VarDecl>(ND))
8844 return false;
8845 } else {
8846 // The declaration is extern "C". Check for any declaration in the
8847 // translation unit which might conflict.
8848 if (IsGlobal) {
8849 // We have already performed the lookup into the translation unit.
8850 IsGlobal = false;
8851 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8852 I != E; ++I) {
8853 if (isa<VarDecl>(Val: *I)) {
8854 Prev = *I;
8855 break;
8856 }
8857 }
8858 } else {
8859 DeclContext::lookup_result R =
8860 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8861 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8862 I != E; ++I) {
8863 if (isa<VarDecl>(Val: *I)) {
8864 Prev = *I;
8865 break;
8866 }
8867 // FIXME: If we have any other entity with this name in global scope,
8868 // the declaration is ill-formed, but that is a defect: it breaks the
8869 // 'stat' hack, for instance. Only variables can have mangled name
8870 // clashes with extern "C" declarations, so only they deserve a
8871 // diagnostic.
8872 }
8873 }
8874
8875 if (!Prev)
8876 return false;
8877 }
8878
8879 // Use the first declaration's location to ensure we point at something which
8880 // is lexically inside an extern "C" linkage-spec.
8881 assert(Prev && "should have found a previous declaration to diagnose");
8882 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8883 Prev = FD->getFirstDecl();
8884 else
8885 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8886
8887 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8888 << IsGlobal << ND;
8889 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8890 << IsGlobal;
8891 return false;
8892}
8893
8894/// Apply special rules for handling extern "C" declarations. Returns \c true
8895/// if we have found that this is a redeclaration of some prior entity.
8896///
8897/// Per C++ [dcl.link]p6:
8898/// Two declarations [for a function or variable] with C language linkage
8899/// with the same name that appear in different scopes refer to the same
8900/// [entity]. An entity with C language linkage shall not be declared with
8901/// the same name as an entity in global scope.
8902template<typename T>
8903static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8904 LookupResult &Previous) {
8905 if (!S.getLangOpts().CPlusPlus) {
8906 // In C, when declaring a global variable, look for a corresponding 'extern'
8907 // variable declared in function scope. We don't need this in C++, because
8908 // we find local extern decls in the surrounding file-scope DeclContext.
8909 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8910 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8911 Previous.clear();
8912 Previous.addDecl(D: Prev);
8913 return true;
8914 }
8915 }
8916 return false;
8917 }
8918
8919 // A declaration in the translation unit can conflict with an extern "C"
8920 // declaration.
8921 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8922 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8923
8924 // An extern "C" declaration can conflict with a declaration in the
8925 // translation unit or can be a redeclaration of an extern "C" declaration
8926 // in another scope.
8927 if (isIncompleteDeclExternC(S,ND))
8928 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8929
8930 // Neither global nor extern "C": nothing to do.
8931 return false;
8932}
8933
8934static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8935 QualType T) {
8936 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8937 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8938 // any of its members, even recursively, shall not have an atomic type, or a
8939 // variably modified type, or a type that is volatile or restrict qualified.
8940 if (CanonT->isVariablyModifiedType()) {
8941 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8942 return true;
8943 }
8944
8945 // Arrays are qualified by their element type, so get the base type (this
8946 // works on non-arrays as well).
8947 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8948
8949 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8950 CanonT.isRestrictQualified()) {
8951 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8952 return true;
8953 }
8954
8955 if (CanonT->isRecordType()) {
8956 const RecordDecl *RD = CanonT->getAsRecordDecl();
8957 if (!RD->isInvalidDecl() &&
8958 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8959 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
8960 }))
8961 return true;
8962 }
8963
8964 return false;
8965}
8966
8967void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8968 // If the decl is already known invalid, don't check it.
8969 if (NewVD->isInvalidDecl())
8970 return;
8971
8972 QualType T = NewVD->getType();
8973
8974 // Defer checking an 'auto' type until its initializer is attached.
8975 if (T->isUndeducedType())
8976 return;
8977
8978 if (NewVD->hasAttrs())
8979 CheckAlignasUnderalignment(D: NewVD);
8980
8981 if (T->isObjCObjectType()) {
8982 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
8983 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
8984 T = Context.getObjCObjectPointerType(OIT: T);
8985 NewVD->setType(T);
8986 }
8987
8988 // Emit an error if an address space was applied to decl with local storage.
8989 // This includes arrays of objects with address space qualifiers, but not
8990 // automatic variables that point to other address spaces.
8991 // ISO/IEC TR 18037 S5.1.2
8992 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8993 T.getAddressSpace() != LangAS::Default) {
8994 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
8995 NewVD->setInvalidDecl();
8996 return;
8997 }
8998
8999 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
9000 // scope.
9001 if (getLangOpts().OpenCLVersion == 120 &&
9002 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
9003 LO: getLangOpts()) &&
9004 NewVD->isStaticLocal()) {
9005 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
9006 NewVD->setInvalidDecl();
9007 return;
9008 }
9009
9010 if (getLangOpts().OpenCL) {
9011 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
9012 return;
9013
9014 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
9015 if (NewVD->hasAttr<BlocksAttr>()) {
9016 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
9017 return;
9018 }
9019
9020 if (T->isBlockPointerType()) {
9021 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
9022 // can't use 'extern' storage class.
9023 if (!T.isConstQualified()) {
9024 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
9025 << 0 /*const*/;
9026 NewVD->setInvalidDecl();
9027 return;
9028 }
9029 if (NewVD->hasExternalStorage()) {
9030 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
9031 NewVD->setInvalidDecl();
9032 return;
9033 }
9034 }
9035
9036 // FIXME: Adding local AS in C++ for OpenCL might make sense.
9037 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
9038 NewVD->hasExternalStorage()) {
9039 if (!T->isSamplerT() && !T->isDependentType() &&
9040 !(T.getAddressSpace() == LangAS::opencl_constant ||
9041 (T.getAddressSpace() == LangAS::opencl_global &&
9042 getOpenCLOptions().areProgramScopeVariablesSupported(
9043 Opts: getLangOpts())))) {
9044 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
9045 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
9046 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9047 << Scope << "global or constant";
9048 else
9049 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
9050 << Scope << "constant";
9051 NewVD->setInvalidDecl();
9052 return;
9053 }
9054 } else {
9055 if (T.getAddressSpace() == LangAS::opencl_global) {
9056 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9057 << 1 /*is any function*/ << "global";
9058 NewVD->setInvalidDecl();
9059 return;
9060 }
9061 // When this extension is enabled, 'local' variables are permitted in
9062 // non-kernel functions and within nested scopes of kernel functions,
9063 // bypassing standard OpenCL address space restrictions.
9064 bool AllowFunctionScopeLocalVariables =
9065 T.getAddressSpace() == LangAS::opencl_local &&
9066 getOpenCLOptions().isAvailableOption(
9067 Ext: "__cl_clang_function_scope_local_variables", LO: getLangOpts());
9068 if (AllowFunctionScopeLocalVariables) {
9069 // Direct pass: No further diagnostics needed for this specific case.
9070 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9071 T.getAddressSpace() == LangAS::opencl_local) {
9072 FunctionDecl *FD = getCurFunctionDecl();
9073 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9074 // in functions.
9075 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9076 if (T.getAddressSpace() == LangAS::opencl_constant)
9077 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9078 << 0 /*non-kernel only*/ << "constant";
9079 else
9080 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
9081 << 0 /*non-kernel only*/ << "local";
9082 NewVD->setInvalidDecl();
9083 return;
9084 }
9085 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9086 // in the outermost scope of a kernel function.
9087 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9088 if (!getCurScope()->isFunctionScope()) {
9089 if (T.getAddressSpace() == LangAS::opencl_constant)
9090 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9091 << "constant";
9092 else
9093 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9094 << "local";
9095 NewVD->setInvalidDecl();
9096 return;
9097 }
9098 }
9099 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9100 // If we are parsing a template we didn't deduce an addr
9101 // space yet.
9102 T.getAddressSpace() != LangAS::Default) {
9103 // Do not allow other address spaces on automatic variable.
9104 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
9105 NewVD->setInvalidDecl();
9106 return;
9107 }
9108 }
9109 }
9110
9111 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9112 && !NewVD->hasAttr<BlocksAttr>()) {
9113 if (getLangOpts().getGC() != LangOptions::NonGC)
9114 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
9115 else {
9116 assert(!getLangOpts().ObjCAutoRefCount);
9117 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
9118 }
9119 }
9120
9121 // WebAssembly tables must be static with a zero length and can't be
9122 // declared within functions.
9123 if (T->isWebAssemblyTableType()) {
9124 if (getCurScope()->getParent()) { // Parent is null at top-level
9125 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
9126 NewVD->setInvalidDecl();
9127 return;
9128 }
9129 if (NewVD->getStorageClass() != SC_Static) {
9130 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
9131 NewVD->setInvalidDecl();
9132 return;
9133 }
9134 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
9135 if (!ATy || ATy->getZExtSize() != 0) {
9136 Diag(Loc: NewVD->getLocation(),
9137 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
9138 NewVD->setInvalidDecl();
9139 return;
9140 }
9141 }
9142
9143 // zero sized static arrays are not allowed in HIP device functions
9144 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9145 if (FunctionDecl *FD = getCurFunctionDecl();
9146 FD &&
9147 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9148 if (const ConstantArrayType *ArrayT =
9149 getASTContext().getAsConstantArrayType(T);
9150 ArrayT && ArrayT->isZeroSize()) {
9151 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
9152 }
9153 }
9154 }
9155
9156 bool isVM = T->isVariablyModifiedType();
9157 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9158 NewVD->hasAttr<BlocksAttr>())
9159 setFunctionHasBranchProtectedScope();
9160
9161 if ((isVM && NewVD->hasLinkage()) ||
9162 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9163 bool SizeIsNegative;
9164 llvm::APSInt Oversized;
9165 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9166 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9167 QualType FixedT;
9168 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9169 FixedT = FixedTInfo->getType();
9170 else if (FixedTInfo) {
9171 // Type and type-as-written are canonically different. We need to fix up
9172 // both types separately.
9173 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9174 Oversized);
9175 }
9176 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9177 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9178 // FIXME: This won't give the correct result for
9179 // int a[10][n];
9180 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9181
9182 if (NewVD->isFileVarDecl())
9183 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
9184 << SizeRange;
9185 else if (NewVD->isStaticLocal())
9186 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
9187 << SizeRange;
9188 else
9189 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
9190 << SizeRange;
9191 NewVD->setInvalidDecl();
9192 return;
9193 }
9194
9195 if (!FixedTInfo) {
9196 if (NewVD->isFileVarDecl())
9197 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
9198 else
9199 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
9200 NewVD->setInvalidDecl();
9201 return;
9202 }
9203
9204 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
9205 NewVD->setType(FixedT);
9206 NewVD->setTypeSourceInfo(FixedTInfo);
9207 }
9208
9209 if (T->isVoidType()) {
9210 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9211 // of objects and functions.
9212 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9213 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
9214 << T;
9215 NewVD->setInvalidDecl();
9216 return;
9217 }
9218 }
9219
9220 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9221 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9222 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
9223 NewVD->setInvalidDecl();
9224 return;
9225 }
9226
9227 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9228 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_not_allowed_on)
9229 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9230 NewVD->setInvalidDecl();
9231 return;
9232 }
9233
9234 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9235 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
9236 NewVD->setInvalidDecl();
9237 return;
9238 }
9239
9240 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9241 !T->isDependentType() &&
9242 RequireLiteralType(Loc: NewVD->getLocation(), T,
9243 DiagID: diag::err_constexpr_var_non_literal)) {
9244 NewVD->setInvalidDecl();
9245 return;
9246 }
9247
9248 // PPC MMA non-pointer types are not allowed as non-local variable types.
9249 if (Context.getTargetInfo().getTriple().isPPC64() &&
9250 !NewVD->isLocalVarDecl() &&
9251 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
9252 NewVD->setInvalidDecl();
9253 return;
9254 }
9255
9256 // Check that SVE types are only used in functions with SVE available.
9257 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9258 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9259 llvm::StringMap<bool> CallerFeatureMap;
9260 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9261 if (ARM().checkSVETypeSupport(Ty: T, Loc: NewVD->getLocation(), FD,
9262 FeatureMap: CallerFeatureMap)) {
9263 NewVD->setInvalidDecl();
9264 return;
9265 }
9266 }
9267
9268 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9269 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9270 llvm::StringMap<bool> CallerFeatureMap;
9271 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9272 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9273 FeatureMap: CallerFeatureMap);
9274 }
9275
9276 if (Context.getTargetInfo().hasAMDGPUTypes()) {
9277 if (!AMDGPU().checkAMDGPUTypeSupport(Ty: T, Loc: NewVD->getLocation())) {
9278 NewVD->setInvalidDecl();
9279 return;
9280 }
9281 }
9282
9283 if (T.hasAddressSpace() &&
9284 !CheckVarDeclSizeAddressSpace(VD: NewVD, AS: T.getAddressSpace())) {
9285 NewVD->setInvalidDecl();
9286 return;
9287 }
9288}
9289
9290bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9291 CheckVariableDeclarationType(NewVD);
9292
9293 // If the decl is already known invalid, don't check it.
9294 if (NewVD->isInvalidDecl())
9295 return false;
9296
9297 // If we did not find anything by this name, look for a non-visible
9298 // extern "C" declaration with the same name.
9299 if (Previous.empty() &&
9300 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9301 Previous.setShadowed();
9302
9303 if (!Previous.empty()) {
9304 MergeVarDecl(New: NewVD, Previous);
9305 return true;
9306 }
9307 return false;
9308}
9309
9310bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9311 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9312
9313 // Look for methods in base classes that this method might override.
9314 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9315 /*DetectVirtual=*/false);
9316 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9317 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9318 DeclarationName Name = MD->getDeclName();
9319
9320 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9321 // We really want to find the base class destructor here.
9322 Name = Context.DeclarationNames.getCXXDestructorName(
9323 Ty: Context.getCanonicalTagType(TD: BaseRecord));
9324 }
9325
9326 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9327 CXXMethodDecl *BaseMD =
9328 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9329 if (!BaseMD || !BaseMD->isVirtual() ||
9330 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9331 /*ConsiderCudaAttrs=*/true))
9332 continue;
9333 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9334 continue;
9335 if (Overridden.insert(Ptr: BaseMD).second) {
9336 MD->addOverriddenMethod(MD: BaseMD);
9337 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9338 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9339 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9340 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9341 }
9342
9343 // A method can only override one function from each base class. We
9344 // don't track indirectly overridden methods from bases of bases.
9345 return true;
9346 }
9347
9348 return false;
9349 };
9350
9351 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9352 return !Overridden.empty();
9353}
9354
9355namespace {
9356 // Struct for holding all of the extra arguments needed by
9357 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9358 struct ActOnFDArgs {
9359 Scope *S;
9360 Declarator &D;
9361 MultiTemplateParamsArg TemplateParamLists;
9362 bool AddToScope;
9363 };
9364} // end anonymous namespace
9365
9366namespace {
9367
9368// Callback to only accept typo corrections that have a non-zero edit distance.
9369// Also only accept corrections that have the same parent decl.
9370class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9371 public:
9372 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9373 CXXRecordDecl *Parent)
9374 : Context(Context), OriginalFD(TypoFD),
9375 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9376
9377 bool ValidateCandidate(const TypoCorrection &candidate) override {
9378 if (candidate.getEditDistance() == 0)
9379 return false;
9380
9381 SmallVector<unsigned, 1> MismatchedParams;
9382 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9383 CDeclEnd = candidate.end();
9384 CDecl != CDeclEnd; ++CDecl) {
9385 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9386
9387 if (FD && !FD->hasBody() &&
9388 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9389 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9390 CXXRecordDecl *Parent = MD->getParent();
9391 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9392 return true;
9393 } else if (!ExpectedParent) {
9394 return true;
9395 }
9396 }
9397 }
9398
9399 return false;
9400 }
9401
9402 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9403 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9404 }
9405
9406 private:
9407 ASTContext &Context;
9408 FunctionDecl *OriginalFD;
9409 CXXRecordDecl *ExpectedParent;
9410};
9411
9412} // end anonymous namespace
9413
9414void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9415 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9416}
9417
9418/// Generate diagnostics for an invalid function redeclaration.
9419///
9420/// This routine handles generating the diagnostic messages for an invalid
9421/// function redeclaration, including finding possible similar declarations
9422/// or performing typo correction if there are no previous declarations with
9423/// the same name.
9424///
9425/// Returns a NamedDecl iff typo correction was performed and substituting in
9426/// the new declaration name does not cause new errors.
9427static NamedDecl *DiagnoseInvalidRedeclaration(
9428 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9429 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9430 DeclarationName Name = NewFD->getDeclName();
9431 DeclContext *NewDC = NewFD->getDeclContext();
9432 SmallVector<unsigned, 1> MismatchedParams;
9433 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9434 TypoCorrection Correction;
9435 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9436 unsigned DiagMsg =
9437 IsLocalFriend ? diag::err_no_matching_local_friend :
9438 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9439 diag::err_member_decl_does_not_match;
9440 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9441 IsLocalFriend ? Sema::LookupLocalFriendName
9442 : Sema::LookupOrdinaryName,
9443 RedeclarationKind::ForVisibleRedeclaration);
9444
9445 NewFD->setInvalidDecl();
9446 if (IsLocalFriend)
9447 SemaRef.LookupName(R&: Prev, S);
9448 else
9449 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9450 assert(!Prev.isAmbiguous() &&
9451 "Cannot have an ambiguity in previous-declaration lookup");
9452 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9453 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9454 MD ? MD->getParent() : nullptr);
9455 if (!Prev.empty()) {
9456 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9457 Func != FuncEnd; ++Func) {
9458 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9459 if (FD &&
9460 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9461 // Add 1 to the index so that 0 can mean the mismatch didn't
9462 // involve a parameter
9463 unsigned ParamNum =
9464 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9465 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9466 }
9467 }
9468 // If the qualified name lookup yielded nothing, try typo correction
9469 } else if ((Correction = SemaRef.CorrectTypo(
9470 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9471 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9472 Mode: CorrectTypoKind::ErrorRecovery,
9473 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9474 // Set up everything for the call to ActOnFunctionDeclarator
9475 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9476 IdLoc: ExtraArgs.D.getIdentifierLoc());
9477 Previous.clear();
9478 Previous.setLookupName(Correction.getCorrection());
9479 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9480 CDeclEnd = Correction.end();
9481 CDecl != CDeclEnd; ++CDecl) {
9482 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9483 if (FD && !FD->hasBody() &&
9484 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9485 Previous.addDecl(D: FD);
9486 }
9487 }
9488 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9489
9490 NamedDecl *Result;
9491 // Retry building the function declaration with the new previous
9492 // declarations, and with errors suppressed.
9493 {
9494 // Trap errors.
9495 Sema::SFINAETrap Trap(SemaRef);
9496
9497 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9498 // pieces need to verify the typo-corrected C++ declaration and hopefully
9499 // eliminate the need for the parameter pack ExtraArgs.
9500 Result = SemaRef.ActOnFunctionDeclarator(
9501 S: ExtraArgs.S, D&: ExtraArgs.D,
9502 DC: Correction.getCorrectionDecl()->getDeclContext(),
9503 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9504 AddToScope&: ExtraArgs.AddToScope);
9505
9506 if (Trap.hasErrorOccurred())
9507 Result = nullptr;
9508 }
9509
9510 if (Result) {
9511 // Determine which correction we picked.
9512 Decl *Canonical = Result->getCanonicalDecl();
9513 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9514 I != E; ++I)
9515 if ((*I)->getCanonicalDecl() == Canonical)
9516 Correction.setCorrectionDecl(*I);
9517
9518 // Let Sema know about the correction.
9519 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9520 SemaRef.diagnoseTypo(
9521 Correction,
9522 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9523 ? diag::err_no_matching_local_friend_suggest
9524 : diag::err_member_decl_does_not_match_suggest)
9525 << Name << NewDC << IsDefinition);
9526 return Result;
9527 }
9528
9529 // Pretend the typo correction never occurred
9530 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9531 IdLoc: ExtraArgs.D.getIdentifierLoc());
9532 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9533 Previous.clear();
9534 Previous.setLookupName(Name);
9535 }
9536
9537 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9538 << Name << NewDC << IsDefinition << NewFD->getLocation();
9539
9540 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9541 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9542 CXXRecordDecl *RD = NewMD->getParent();
9543 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9544 << RD->getName() << RD->getLocation();
9545 }
9546
9547 bool NewFDisConst = NewMD && NewMD->isConst();
9548
9549 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9550 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9551 NearMatch != NearMatchEnd; ++NearMatch) {
9552 FunctionDecl *FD = NearMatch->first;
9553 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9554 bool FDisConst = MD && MD->isConst();
9555 bool IsMember = MD || !IsLocalFriend;
9556
9557 // FIXME: These notes are poorly worded for the local friend case.
9558 if (unsigned Idx = NearMatch->second) {
9559 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9560 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9561 if (Loc.isInvalid()) Loc = FD->getLocation();
9562 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9563 : diag::note_local_decl_close_param_match)
9564 << Idx << FDParam->getType()
9565 << NewFD->getParamDecl(i: Idx - 1)->getType();
9566 } else if (FDisConst != NewFDisConst) {
9567 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9568 DiagID: diag::note_member_def_close_const_match)
9569 << NewFDisConst << FD->getSourceRange().getEnd();
9570 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9571 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9572 Code: " const");
9573 else if (FTI.hasMethodTypeQualifiers() &&
9574 FTI.getConstQualifierLoc().isValid())
9575 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9576 } else {
9577 SemaRef.Diag(Loc: FD->getLocation(),
9578 DiagID: IsMember ? diag::note_member_def_close_match
9579 : diag::note_local_decl_close_match);
9580 }
9581 }
9582 return nullptr;
9583}
9584
9585static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9586 switch (D.getDeclSpec().getStorageClassSpec()) {
9587 default: llvm_unreachable("Unknown storage class!");
9588 case DeclSpec::SCS_auto:
9589 case DeclSpec::SCS_register:
9590 case DeclSpec::SCS_mutable:
9591 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9592 DiagID: diag::err_typecheck_sclass_func);
9593 D.getMutableDeclSpec().ClearStorageClassSpecs();
9594 D.setInvalidType();
9595 break;
9596 case DeclSpec::SCS_unspecified: break;
9597 case DeclSpec::SCS_extern:
9598 if (D.getDeclSpec().isExternInLinkageSpec())
9599 return SC_None;
9600 return SC_Extern;
9601 case DeclSpec::SCS_static: {
9602 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9603 // C99 6.7.1p5:
9604 // The declaration of an identifier for a function that has
9605 // block scope shall have no explicit storage-class specifier
9606 // other than extern
9607 // See also (C++ [dcl.stc]p4).
9608 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9609 DiagID: diag::err_static_block_func);
9610 break;
9611 } else
9612 return SC_Static;
9613 }
9614 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9615 }
9616
9617 // No explicit storage class has already been returned
9618 return SC_None;
9619}
9620
9621static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9622 DeclContext *DC, QualType &R,
9623 TypeSourceInfo *TInfo,
9624 StorageClass SC,
9625 bool &IsVirtualOkay) {
9626 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9627 DeclarationName Name = NameInfo.getName();
9628
9629 FunctionDecl *NewFD = nullptr;
9630 bool isInline = D.getDeclSpec().isInlineSpecified();
9631
9632 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9633 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9634 (SemaRef.getLangOpts().C23 &&
9635 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9636
9637 if (SemaRef.getLangOpts().C23)
9638 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9639 DiagID: diag::err_c23_constexpr_not_variable);
9640 else
9641 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9642 DiagID: diag::err_constexpr_wrong_decl_kind)
9643 << static_cast<int>(ConstexprKind);
9644 ConstexprKind = ConstexprSpecKind::Unspecified;
9645 D.getMutableDeclSpec().ClearConstexprSpec();
9646 }
9647
9648 if (!SemaRef.getLangOpts().CPlusPlus) {
9649 // Determine whether the function was written with a prototype. This is
9650 // true when:
9651 // - there is a prototype in the declarator, or
9652 // - the type R of the function is some kind of typedef or other non-
9653 // attributed reference to a type name (which eventually refers to a
9654 // function type). Note, we can't always look at the adjusted type to
9655 // check this case because attributes may cause a non-function
9656 // declarator to still have a function type. e.g.,
9657 // typedef void func(int a);
9658 // __attribute__((noreturn)) func other_func; // This has a prototype
9659 bool HasPrototype =
9660 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9661 (D.getDeclSpec().isTypeRep() &&
9662 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9663 ->isFunctionProtoType()) ||
9664 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9665 assert(
9666 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9667 "Strict prototypes are required");
9668
9669 NewFD = FunctionDecl::Create(
9670 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9671 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9672 ConstexprKind: ConstexprSpecKind::Unspecified,
9673 /*TrailingRequiresClause=*/{});
9674 if (D.isInvalidType())
9675 NewFD->setInvalidDecl();
9676
9677 return NewFD;
9678 }
9679
9680 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9681 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9682
9683 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9684
9685 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9686 // This is a C++ constructor declaration.
9687 assert(DC->isRecord() &&
9688 "Constructors can only be declared in a member context");
9689
9690 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9691 return CXXConstructorDecl::Create(
9692 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9693 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9694 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9695 Inherited: InheritedConstructor(), TrailingRequiresClause);
9696
9697 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9698 // This is a C++ destructor declaration.
9699 if (DC->isRecord()) {
9700 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9701 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9702 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9703 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9704 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9705 /*isImplicitlyDeclared=*/false, ConstexprKind,
9706 TrailingRequiresClause);
9707 // User defined destructors start as not selected if the class definition is still
9708 // not done.
9709 if (Record->isBeingDefined())
9710 NewDD->setIneligibleOrNotSelected(true);
9711
9712 // If the destructor needs an implicit exception specification, set it
9713 // now. FIXME: It'd be nice to be able to create the right type to start
9714 // with, but the type needs to reference the destructor declaration.
9715 if (SemaRef.getLangOpts().CPlusPlus11)
9716 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9717
9718 IsVirtualOkay = true;
9719 return NewDD;
9720
9721 } else {
9722 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9723 D.setInvalidType();
9724
9725 // Create a FunctionDecl to satisfy the function definition parsing
9726 // code path.
9727 return FunctionDecl::Create(
9728 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9729 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9730 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9731 }
9732
9733 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9734 if (!DC->isRecord()) {
9735 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9736 DiagID: diag::err_conv_function_not_member);
9737 return nullptr;
9738 }
9739
9740 SemaRef.CheckConversionDeclarator(D, R, SC);
9741 if (D.isInvalidType())
9742 return nullptr;
9743
9744 IsVirtualOkay = true;
9745 return CXXConversionDecl::Create(
9746 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9747 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9748 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9749 TrailingRequiresClause);
9750
9751 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9752 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9753 return nullptr;
9754 return CXXDeductionGuideDecl::Create(
9755 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9756 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9757 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9758 } else if (DC->isRecord()) {
9759 // If the name of the function is the same as the name of the record,
9760 // then this must be an invalid constructor that has a return type.
9761 // (The parser checks for a return type and makes the declarator a
9762 // constructor if it has no return type).
9763 if (Name.getAsIdentifierInfo() &&
9764 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9765 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9766 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9767 << SourceRange(D.getIdentifierLoc());
9768 return nullptr;
9769 }
9770
9771 // This is a C++ method declaration.
9772 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9773 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9774 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9775 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9776 IsVirtualOkay = !Ret->isStatic();
9777 return Ret;
9778 } else {
9779 bool isFriend =
9780 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9781 if (!isFriend && SemaRef.CurContext->isRecord())
9782 return nullptr;
9783
9784 // Determine whether the function was written with a
9785 // prototype. This true when:
9786 // - we're in C++ (where every function has a prototype),
9787 return FunctionDecl::Create(
9788 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9789 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9790 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9791 }
9792}
9793
9794enum OpenCLParamType {
9795 ValidKernelParam,
9796 PtrPtrKernelParam,
9797 PtrKernelParam,
9798 InvalidAddrSpacePtrKernelParam,
9799 InvalidKernelParam,
9800 RecordKernelParam
9801};
9802
9803static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9804 // Size dependent types are just typedefs to normal integer types
9805 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9806 // integers other than by their names.
9807 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9808
9809 // Remove typedefs one by one until we reach a typedef
9810 // for a size dependent type.
9811 QualType DesugaredTy = Ty;
9812 do {
9813 ArrayRef<StringRef> Names(SizeTypeNames);
9814 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9815 if (Names.end() != Match)
9816 return true;
9817
9818 Ty = DesugaredTy;
9819 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9820 } while (DesugaredTy != Ty);
9821
9822 return false;
9823}
9824
9825static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9826 if (PT->isDependentType())
9827 return InvalidKernelParam;
9828
9829 if (PT->isPointerOrReferenceType()) {
9830 QualType PointeeType = PT->getPointeeType();
9831 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9832 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9833 PointeeType.getAddressSpace() == LangAS::Default)
9834 return InvalidAddrSpacePtrKernelParam;
9835
9836 if (PointeeType->isPointerType()) {
9837 // This is a pointer to pointer parameter.
9838 // Recursively check inner type.
9839 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9840 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9841 ParamKind == InvalidKernelParam)
9842 return ParamKind;
9843
9844 // OpenCL v3.0 s6.11.a:
9845 // A restriction to pass pointers to pointers only applies to OpenCL C
9846 // v1.2 or below.
9847 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9848 return ValidKernelParam;
9849
9850 return PtrPtrKernelParam;
9851 }
9852
9853 // C++ for OpenCL v1.0 s2.4:
9854 // Moreover the types used in parameters of the kernel functions must be:
9855 // Standard layout types for pointer parameters. The same applies to
9856 // reference if an implementation supports them in kernel parameters.
9857 if (S.getLangOpts().OpenCLCPlusPlus &&
9858 !S.getOpenCLOptions().isAvailableOption(
9859 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9860 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9861 bool IsStandardLayoutType = true;
9862 if (CXXRec) {
9863 // If template type is not ODR-used its definition is only available
9864 // in the template definition not its instantiation.
9865 // FIXME: This logic doesn't work for types that depend on template
9866 // parameter (PR58590).
9867 if (!CXXRec->hasDefinition())
9868 CXXRec = CXXRec->getTemplateInstantiationPattern();
9869 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9870 IsStandardLayoutType = false;
9871 }
9872 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9873 !IsStandardLayoutType)
9874 return InvalidKernelParam;
9875 }
9876
9877 // OpenCL v1.2 s6.9.p:
9878 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9879 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9880 return ValidKernelParam;
9881
9882 return PtrKernelParam;
9883 }
9884
9885 // OpenCL v1.2 s6.9.k:
9886 // Arguments to kernel functions in a program cannot be declared with the
9887 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9888 // uintptr_t or a struct and/or union that contain fields declared to be one
9889 // of these built-in scalar types.
9890 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9891 return InvalidKernelParam;
9892
9893 if (PT->isImageType())
9894 return PtrKernelParam;
9895
9896 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9897 return InvalidKernelParam;
9898
9899 // OpenCL extension spec v1.2 s9.5:
9900 // This extension adds support for half scalar and vector types as built-in
9901 // types that can be used for arithmetic operations, conversions etc.
9902 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9903 PT->isHalfType())
9904 return InvalidKernelParam;
9905
9906 // Look into an array argument to check if it has a forbidden type.
9907 if (PT->isArrayType()) {
9908 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9909 // Call ourself to check an underlying type of an array. Since the
9910 // getPointeeOrArrayElementType returns an innermost type which is not an
9911 // array, this recursive call only happens once.
9912 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9913 }
9914
9915 // C++ for OpenCL v1.0 s2.4:
9916 // Moreover the types used in parameters of the kernel functions must be:
9917 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9918 // types) for parameters passed by value;
9919 if (S.getLangOpts().OpenCLCPlusPlus &&
9920 !S.getOpenCLOptions().isAvailableOption(
9921 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9922 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9923 return InvalidKernelParam;
9924
9925 if (PT->isRecordType())
9926 return RecordKernelParam;
9927
9928 return ValidKernelParam;
9929}
9930
9931static void checkIsValidOpenCLKernelParameter(
9932 Sema &S,
9933 Declarator &D,
9934 ParmVarDecl *Param,
9935 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9936 QualType PT = Param->getType();
9937
9938 // Cache the valid types we encounter to avoid rechecking structs that are
9939 // used again
9940 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9941 return;
9942
9943 switch (getOpenCLKernelParameterType(S, PT)) {
9944 case PtrPtrKernelParam:
9945 // OpenCL v3.0 s6.11.a:
9946 // A kernel function argument cannot be declared as a pointer to a pointer
9947 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9948 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
9949 D.setInvalidType();
9950 return;
9951
9952 case InvalidAddrSpacePtrKernelParam:
9953 // OpenCL v1.0 s6.5:
9954 // __kernel function arguments declared to be a pointer of a type can point
9955 // to one of the following address spaces only : __global, __local or
9956 // __constant.
9957 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
9958 D.setInvalidType();
9959 return;
9960
9961 // OpenCL v1.2 s6.9.k:
9962 // Arguments to kernel functions in a program cannot be declared with the
9963 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9964 // uintptr_t or a struct and/or union that contain fields declared to be
9965 // one of these built-in scalar types.
9966
9967 case InvalidKernelParam:
9968 // OpenCL v1.2 s6.8 n:
9969 // A kernel function argument cannot be declared
9970 // of event_t type.
9971 // Do not diagnose half type since it is diagnosed as invalid argument
9972 // type for any function elsewhere.
9973 if (!PT->isHalfType()) {
9974 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9975
9976 // Explain what typedefs are involved.
9977 const TypedefType *Typedef = nullptr;
9978 while ((Typedef = PT->getAs<TypedefType>())) {
9979 SourceLocation Loc = Typedef->getDecl()->getLocation();
9980 // SourceLocation may be invalid for a built-in type.
9981 if (Loc.isValid())
9982 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
9983 PT = Typedef->desugar();
9984 }
9985 }
9986
9987 D.setInvalidType();
9988 return;
9989
9990 case PtrKernelParam:
9991 case ValidKernelParam:
9992 ValidTypes.insert(Ptr: PT.getTypePtr());
9993 return;
9994
9995 case RecordKernelParam:
9996 break;
9997 }
9998
9999 // Track nested structs we will inspect
10000 SmallVector<const Decl *, 4> VisitStack;
10001
10002 // Track where we are in the nested structs. Items will migrate from
10003 // VisitStack to HistoryStack as we do the DFS for bad field.
10004 SmallVector<const FieldDecl *, 4> HistoryStack;
10005 HistoryStack.push_back(Elt: nullptr);
10006
10007 // At this point we already handled everything except of a RecordType.
10008 assert(PT->isRecordType() && "Unexpected type.");
10009 const auto *PD = PT->castAsRecordDecl();
10010 VisitStack.push_back(Elt: PD);
10011 assert(VisitStack.back() && "First decl null?");
10012
10013 do {
10014 const Decl *Next = VisitStack.pop_back_val();
10015 if (!Next) {
10016 assert(!HistoryStack.empty());
10017 // Found a marker, we have gone up a level
10018 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
10019 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
10020
10021 continue;
10022 }
10023
10024 // Adds everything except the original parameter declaration (which is not a
10025 // field itself) to the history stack.
10026 const RecordDecl *RD;
10027 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
10028 HistoryStack.push_back(Elt: Field);
10029
10030 QualType FieldTy = Field->getType();
10031 // Other field types (known to be valid or invalid) are handled while we
10032 // walk around RecordDecl::fields().
10033 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
10034 "Unexpected type.");
10035 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
10036
10037 RD = FieldRecTy->castAsRecordDecl();
10038 } else {
10039 RD = cast<RecordDecl>(Val: Next);
10040 }
10041
10042 // Add a null marker so we know when we've gone back up a level
10043 VisitStack.push_back(Elt: nullptr);
10044
10045 for (const auto *FD : RD->fields()) {
10046 QualType QT = FD->getType();
10047
10048 if (ValidTypes.count(Ptr: QT.getTypePtr()))
10049 continue;
10050
10051 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
10052 if (ParamType == ValidKernelParam)
10053 continue;
10054
10055 if (ParamType == RecordKernelParam) {
10056 VisitStack.push_back(Elt: FD);
10057 continue;
10058 }
10059
10060 // OpenCL v1.2 s6.9.p:
10061 // Arguments to kernel functions that are declared to be a struct or union
10062 // do not allow OpenCL objects to be passed as elements of the struct or
10063 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10064 // of SVM.
10065 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10066 ParamType == InvalidAddrSpacePtrKernelParam) {
10067 S.Diag(Loc: Param->getLocation(),
10068 DiagID: diag::err_record_with_pointers_kernel_param)
10069 << PT->isUnionType()
10070 << PT;
10071 } else {
10072 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
10073 }
10074
10075 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
10076 << PD->getDeclName();
10077
10078 // We have an error, now let's go back up through history and show where
10079 // the offending field came from
10080 for (ArrayRef<const FieldDecl *>::const_iterator
10081 I = HistoryStack.begin() + 1,
10082 E = HistoryStack.end();
10083 I != E; ++I) {
10084 const FieldDecl *OuterField = *I;
10085 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
10086 << OuterField->getType();
10087 }
10088
10089 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
10090 << QT->isPointerType()
10091 << QT;
10092 D.setInvalidType();
10093 return;
10094 }
10095 } while (!VisitStack.empty());
10096}
10097
10098/// Find the DeclContext in which a tag is implicitly declared if we see an
10099/// elaborated type specifier in the specified context, and lookup finds
10100/// nothing.
10101static DeclContext *getTagInjectionContext(DeclContext *DC) {
10102 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10103 DC = DC->getParent();
10104 return DC;
10105}
10106
10107/// Find the Scope in which a tag is implicitly declared if we see an
10108/// elaborated type specifier in the specified context, and lookup finds
10109/// nothing.
10110static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10111 while (S->isClassScope() ||
10112 (LangOpts.CPlusPlus &&
10113 S->isFunctionPrototypeScope()) ||
10114 ((S->getFlags() & Scope::DeclScope) == 0) ||
10115 (S->getEntity() && S->getEntity()->isTransparentContext()))
10116 S = S->getParent();
10117 return S;
10118}
10119
10120/// Determine whether a declaration matches a known function in namespace std.
10121static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10122 unsigned BuiltinID) {
10123 switch (BuiltinID) {
10124 case Builtin::BI__GetExceptionInfo:
10125 // No type checking whatsoever.
10126 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10127
10128 case Builtin::BIaddressof:
10129 case Builtin::BI__addressof:
10130 case Builtin::BIforward:
10131 case Builtin::BIforward_like:
10132 case Builtin::BImove:
10133 case Builtin::BImove_if_noexcept:
10134 case Builtin::BIas_const: {
10135 // Ensure that we don't treat the algorithm
10136 // OutputIt std::move(InputIt, InputIt, OutputIt)
10137 // as the builtin std::move.
10138 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10139 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10140 }
10141
10142 default:
10143 return false;
10144 }
10145}
10146
10147void Sema::addImplicitCallingConvAbiTag(FunctionDecl *FD) {
10148 const auto *FT = FD->getType()->getAs<FunctionType>();
10149 if (!FT)
10150 return;
10151
10152 StringRef Tag;
10153 switch (FT->getCallConv()) {
10154#define CC_VLS_CASE(ABI_VLEN) \
10155 case CC_RISCVVLSCall_##ABI_VLEN: \
10156 Tag = "riscv_vls_cc_" #ABI_VLEN; \
10157 break;
10158 CC_VLS_CASE(32)
10159 CC_VLS_CASE(64)
10160 CC_VLS_CASE(128)
10161 CC_VLS_CASE(256)
10162 CC_VLS_CASE(512)
10163 CC_VLS_CASE(1024)
10164 CC_VLS_CASE(2048)
10165 CC_VLS_CASE(4096)
10166 CC_VLS_CASE(8192)
10167 CC_VLS_CASE(16384)
10168 CC_VLS_CASE(32768)
10169 CC_VLS_CASE(65536)
10170#undef CC_VLS_CASE
10171 default:
10172 return;
10173 }
10174
10175 SmallVector<AbiTagAttr *, 2> Existing(FD->specific_attrs<AbiTagAttr>());
10176 AbiTagAttr *Old = Existing.empty() ? nullptr : Existing.front();
10177
10178 SmallVector<StringRef, 4> Tags;
10179 if (Old)
10180 llvm::append_range(C&: Tags, R: Old->tags());
10181 if (llvm::is_contained(Range&: Tags, Element: Tag))
10182 return;
10183 Tags.push_back(Elt: Tag);
10184
10185 AbiTagAttr *Merged =
10186 Old ? AbiTagAttr::Create(Ctx&: Context, Tags: Tags.data(), TagsSize: Tags.size(), CommonInfo: *Old)
10187 : AbiTagAttr::CreateImplicit(Ctx&: Context, Tags: Tags.data(), TagsSize: Tags.size(),
10188 Range: FD->getLocation());
10189 FD->dropAttr<AbiTagAttr>();
10190 FD->addAttr(A: Merged);
10191 for (size_t I = 1, E = Existing.size(); I < E; ++I)
10192 FD->addAttr(A: Existing[I]);
10193}
10194
10195NamedDecl*
10196Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10197 TypeSourceInfo *TInfo, LookupResult &Previous,
10198 MultiTemplateParamsArg TemplateParamListsRef,
10199 bool &AddToScope) {
10200 QualType R = TInfo->getType();
10201
10202 assert(R->isFunctionType());
10203 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10204 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
10205
10206 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10207 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
10208 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10209 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10210 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10211 TemplateParamLists.back() = Invented;
10212 else
10213 TemplateParamLists.push_back(Elt: Invented);
10214 }
10215
10216 // TODO: consider using NameInfo for diagnostic.
10217 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10218 DeclarationName Name = NameInfo.getName();
10219 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
10220
10221 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10222 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
10223 DiagID: diag::err_invalid_thread)
10224 << DeclSpec::getSpecifierName(S: TSCS);
10225
10226 if (D.isFirstDeclarationOfMember())
10227 adjustMemberFunctionCC(
10228 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10229 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
10230
10231 bool isFriend = false;
10232 FunctionTemplateDecl *FunctionTemplate = nullptr;
10233 bool isMemberSpecialization = false;
10234 bool isFunctionTemplateSpecialization = false;
10235
10236 bool HasExplicitTemplateArgs = false;
10237 TemplateArgumentListInfo TemplateArgs;
10238
10239 bool isVirtualOkay = false;
10240
10241 DeclContext *OriginalDC = DC;
10242 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10243
10244 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
10245 IsVirtualOkay&: isVirtualOkay);
10246 if (!NewFD) return nullptr;
10247
10248 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10249 NewFD->setTopLevelDeclInObjCContainer();
10250
10251 // Set the lexical context. If this is a function-scope declaration, or has a
10252 // C++ scope specifier, or is the object of a friend declaration, the lexical
10253 // context will be different from the semantic context.
10254 NewFD->setLexicalDeclContext(CurContext);
10255
10256 if (IsLocalExternDecl)
10257 NewFD->setLocalExternDecl();
10258
10259 if (getLangOpts().CPlusPlus) {
10260 // The rules for implicit inlines changed in C++20 for methods and friends
10261 // with an in-class definition (when such a definition is not attached to
10262 // the global module). This does not affect declarations that are already
10263 // inline (whether explicitly or implicitly by being declared constexpr,
10264 // consteval, etc).
10265 // FIXME: We need a better way to separate C++ standard and clang modules.
10266 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10267 !NewFD->getOwningModule() ||
10268 NewFD->isFromGlobalModule() ||
10269 NewFD->getOwningModule()->isHeaderLikeModule();
10270 bool isInline = D.getDeclSpec().isInlineSpecified();
10271 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10272 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10273 isFriend = D.getDeclSpec().isFriendSpecified();
10274 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10275 // Pre-C++20 [class.friend]p5
10276 // A function can be defined in a friend declaration of a
10277 // class . . . . Such a function is implicitly inline.
10278 // Post C++20 [class.friend]p7
10279 // Such a function is implicitly an inline function if it is attached
10280 // to the global module.
10281 NewFD->setImplicitlyInline();
10282 }
10283
10284 // If this is a method defined in an __interface, and is not a constructor
10285 // or an overloaded operator, then set the pure flag (isVirtual will already
10286 // return true).
10287 if (const CXXRecordDecl *Parent =
10288 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
10289 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
10290 NewFD->setIsPureVirtual(true);
10291
10292 // C++ [class.union]p2
10293 // A union can have member functions, but not virtual functions.
10294 if (isVirtual && Parent->isUnion()) {
10295 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
10296 NewFD->setInvalidDecl();
10297 }
10298 if ((Parent->isClass() || Parent->isStruct()) &&
10299 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10300 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10301 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10302 if (auto *Def = Parent->getDefinition())
10303 Def->setInitMethod(true);
10304 }
10305 }
10306
10307 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
10308 isMemberSpecialization = false;
10309 isFunctionTemplateSpecialization = false;
10310 if (D.isInvalidType())
10311 NewFD->setInvalidDecl();
10312
10313 // Match up the template parameter lists with the scope specifier, then
10314 // determine whether we have a template or a template specialization.
10315 bool Invalid = false;
10316 TemplateIdAnnotation *TemplateId =
10317 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10318 ? D.getName().TemplateId
10319 : nullptr;
10320 TemplateParameterList *TemplateParams =
10321 MatchTemplateParametersToScopeSpecifier(
10322 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10323 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10324 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10325 if (TemplateParams) {
10326 // Check that we can declare a template here.
10327 if (CheckTemplateDeclScope(S, TemplateParams))
10328 NewFD->setInvalidDecl();
10329
10330 if (TemplateParams->size() > 0) {
10331 // This is a function template
10332
10333 // A destructor cannot be a template.
10334 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10335 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10336 NewFD->setInvalidDecl();
10337 // Function template with explicit template arguments.
10338 } else if (TemplateId) {
10339 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10340 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10341 NewFD->setInvalidDecl();
10342 }
10343
10344 // If we're adding a template to a dependent context, we may need to
10345 // rebuilding some of the types used within the template parameter list,
10346 // now that we know what the current instantiation is.
10347 if (DC->isDependentContext()) {
10348 ContextRAII SavedContext(*this, DC);
10349 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10350 Invalid = true;
10351 }
10352
10353 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10354 L: NewFD->getLocation(),
10355 Name, Params: TemplateParams,
10356 Decl: NewFD);
10357 FunctionTemplate->setLexicalDeclContext(CurContext);
10358 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10359
10360 // For source fidelity, store the other template param lists.
10361 if (TemplateParamLists.size() > 1) {
10362 NewFD->setTemplateParameterListsInfo(Context,
10363 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10364 .drop_back(N: 1));
10365 }
10366 } else {
10367 // This is a function template specialization.
10368 isFunctionTemplateSpecialization = true;
10369 // For source fidelity, store all the template param lists.
10370 if (TemplateParamLists.size() > 0)
10371 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10372
10373 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10374 if (isFriend) {
10375 // We want to remove the "template<>", found here.
10376 SourceRange RemoveRange = TemplateParams->getSourceRange();
10377
10378 // If we remove the template<> and the name is not a
10379 // template-id, we're actually silently creating a problem:
10380 // the friend declaration will refer to an untemplated decl,
10381 // and clearly the user wants a template specialization. So
10382 // we need to insert '<>' after the name.
10383 SourceLocation InsertLoc;
10384 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10385 InsertLoc = D.getName().getSourceRange().getEnd();
10386 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10387 }
10388
10389 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10390 << Name << RemoveRange
10391 << FixItHint::CreateRemoval(RemoveRange)
10392 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10393 Invalid = true;
10394
10395 // Recover by faking up an empty template argument list.
10396 HasExplicitTemplateArgs = true;
10397 TemplateArgs.setLAngleLoc(InsertLoc);
10398 TemplateArgs.setRAngleLoc(InsertLoc);
10399 }
10400 }
10401 } else {
10402 // Check that we can declare a template here.
10403 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10404 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10405 NewFD->setInvalidDecl();
10406
10407 // All template param lists were matched against the scope specifier:
10408 // this is NOT (an explicit specialization of) a template.
10409 if (TemplateParamLists.size() > 0)
10410 // For source fidelity, store all the template param lists.
10411 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10412
10413 // "friend void foo<>(int);" is an implicit specialization decl.
10414 if (isFriend && TemplateId)
10415 isFunctionTemplateSpecialization = true;
10416 }
10417
10418 // If this is a function template specialization and the unqualified-id of
10419 // the declarator-id is a template-id, convert the template argument list
10420 // into our AST format and check for unexpanded packs.
10421 if (isFunctionTemplateSpecialization && TemplateId) {
10422 HasExplicitTemplateArgs = true;
10423
10424 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10425 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10426 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10427 TemplateId->NumArgs);
10428 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10429
10430 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10431 // declaration of a function template partial specialization? Should we
10432 // consider the unexpanded pack context to be a partial specialization?
10433 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10434 if (DiagnoseUnexpandedParameterPack(
10435 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10436 : UPPC_ExplicitSpecialization))
10437 NewFD->setInvalidDecl();
10438 }
10439 }
10440
10441 if (Invalid) {
10442 NewFD->setInvalidDecl();
10443 if (FunctionTemplate)
10444 FunctionTemplate->setInvalidDecl();
10445 }
10446
10447 // C++ [dcl.fct.spec]p5:
10448 // The virtual specifier shall only be used in declarations of
10449 // nonstatic class member functions that appear within a
10450 // member-specification of a class declaration; see 10.3.
10451 //
10452 if (isVirtual && !NewFD->isInvalidDecl()) {
10453 if (!isVirtualOkay) {
10454 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10455 DiagID: diag::err_virtual_non_function);
10456 } else if (!CurContext->isRecord()) {
10457 // 'virtual' was specified outside of the class.
10458 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10459 DiagID: diag::err_virtual_out_of_class)
10460 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10461 } else if (NewFD->getDescribedFunctionTemplate()) {
10462 // C++ [temp.mem]p3:
10463 // A member function template shall not be virtual.
10464 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10465 DiagID: diag::err_virtual_member_function_template)
10466 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10467 } else {
10468 // Okay: Add virtual to the method.
10469 NewFD->setVirtualAsWritten(true);
10470 }
10471
10472 if (getLangOpts().CPlusPlus14 &&
10473 NewFD->getReturnType()->isUndeducedType())
10474 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10475 }
10476
10477 // C++ [dcl.fct.spec]p3:
10478 // The inline specifier shall not appear on a block scope function
10479 // declaration.
10480 if (isInline && !NewFD->isInvalidDecl()) {
10481 if (CurContext->isFunctionOrMethod()) {
10482 // 'inline' is not allowed on block scope function declaration.
10483 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10484 DiagID: diag::err_inline_declaration_block_scope) << Name
10485 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10486 }
10487 }
10488
10489 // C++ [dcl.fct.spec]p6:
10490 // The explicit specifier shall be used only in the declaration of a
10491 // constructor or conversion function within its class definition;
10492 // see 12.3.1 and 12.3.2.
10493 if (hasExplicit && !NewFD->isInvalidDecl() &&
10494 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10495 if (!CurContext->isRecord()) {
10496 // 'explicit' was specified outside of the class.
10497 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10498 DiagID: diag::err_explicit_out_of_class)
10499 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10500 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10501 !isa<CXXConversionDecl>(Val: NewFD)) {
10502 // 'explicit' was specified on a function that wasn't a constructor
10503 // or conversion function.
10504 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10505 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10506 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10507 }
10508 }
10509
10510 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10511 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10512 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10513 // are implicitly inline.
10514 NewFD->setImplicitlyInline();
10515
10516 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10517 // be either constructors or to return a literal type. Therefore,
10518 // destructors cannot be declared constexpr.
10519 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10520 (!getLangOpts().CPlusPlus20 ||
10521 ConstexprKind == ConstexprSpecKind::Consteval)) {
10522 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10523 << static_cast<int>(ConstexprKind);
10524 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10525 ? ConstexprSpecKind::Unspecified
10526 : ConstexprSpecKind::Constexpr);
10527 }
10528 // C++20 [dcl.constexpr]p2: An allocation function, or a
10529 // deallocation function shall not be declared with the consteval
10530 // specifier.
10531 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10532 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10533 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10534 DiagID: diag::err_invalid_consteval_decl_kind)
10535 << NewFD;
10536 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10537 }
10538 }
10539
10540 // If __module_private__ was specified, mark the function accordingly.
10541 if (D.getDeclSpec().isModulePrivateSpecified()) {
10542 if (isFunctionTemplateSpecialization) {
10543 SourceLocation ModulePrivateLoc
10544 = D.getDeclSpec().getModulePrivateSpecLoc();
10545 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10546 << 0
10547 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10548 } else {
10549 NewFD->setModulePrivate();
10550 if (FunctionTemplate)
10551 FunctionTemplate->setModulePrivate();
10552 }
10553 }
10554
10555 if (isFriend) {
10556 if (FunctionTemplate) {
10557 FunctionTemplate->setObjectOfFriendDecl();
10558 FunctionTemplate->setAccess(AS_public);
10559 }
10560 NewFD->setObjectOfFriendDecl();
10561 NewFD->setAccess(AS_public);
10562 }
10563
10564 // If a function is defined as defaulted or deleted, mark it as such now.
10565 // We'll do the relevant checks on defaulted / deleted functions later.
10566 switch (D.getFunctionDefinitionKind()) {
10567 case FunctionDefinitionKind::Declaration:
10568 case FunctionDefinitionKind::Definition:
10569 break;
10570
10571 case FunctionDefinitionKind::Defaulted:
10572 NewFD->setDefaulted();
10573 break;
10574
10575 case FunctionDefinitionKind::Deleted:
10576 NewFD->setDeletedAsWritten();
10577 break;
10578 }
10579
10580 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10581 D.isFunctionDefinition()) {
10582 // Pre C++20 [class.mfct]p2:
10583 // A member function may be defined (8.4) in its class definition, in
10584 // which case it is an inline member function (7.1.2)
10585 // Post C++20 [class.mfct]p1:
10586 // If a member function is attached to the global module and is defined
10587 // in its class definition, it is inline.
10588 NewFD->setImplicitlyInline();
10589 }
10590
10591 if (!isFriend && SC != SC_None) {
10592 // C++ [temp.expl.spec]p2:
10593 // The declaration in an explicit-specialization shall not be an
10594 // export-declaration. An explicit specialization shall not use a
10595 // storage-class-specifier other than thread_local.
10596 //
10597 // We diagnose friend declarations with storage-class-specifiers
10598 // elsewhere.
10599 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10600 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10601 DiagID: diag::ext_explicit_specialization_storage_class)
10602 << FixItHint::CreateRemoval(
10603 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10604 }
10605
10606 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10607 assert(isa<CXXMethodDecl>(NewFD) &&
10608 "Out-of-line member function should be a CXXMethodDecl");
10609 // C++ [class.static]p1:
10610 // A data or function member of a class may be declared static
10611 // in a class definition, in which case it is a static member of
10612 // the class.
10613
10614 // Complain about the 'static' specifier if it's on an out-of-line
10615 // member function definition.
10616
10617 // MSVC permits the use of a 'static' storage specifier on an
10618 // out-of-line member function template declaration and class member
10619 // template declaration (MSVC versions before 2015), warn about this.
10620 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10621 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10622 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10623 (getLangOpts().MSVCCompat &&
10624 NewFD->getDescribedFunctionTemplate()))
10625 ? diag::ext_static_out_of_line
10626 : diag::err_static_out_of_line)
10627 << FixItHint::CreateRemoval(
10628 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10629 }
10630 }
10631
10632 // C++11 [except.spec]p15:
10633 // A deallocation function with no exception-specification is treated
10634 // as if it were specified with noexcept(true).
10635 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10636 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10637 !FPT->hasExceptionSpec())
10638 NewFD->setType(Context.getFunctionType(
10639 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10640 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10641
10642 // C++20 [dcl.inline]/7
10643 // If an inline function or variable that is attached to a named module
10644 // is declared in a definition domain, it shall be defined in that
10645 // domain.
10646 // So, if the current declaration does not have a definition, we must
10647 // check at the end of the TU (or when the PMF starts) to see that we
10648 // have a definition at that point.
10649 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10650 NewFD->isInNamedModule()) {
10651 PendingInlineFuncDecls.insert(Ptr: NewFD);
10652 }
10653 }
10654
10655 // Filter out previous declarations that don't match the scope.
10656 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10657 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10658 isMemberSpecialization ||
10659 isFunctionTemplateSpecialization);
10660
10661 LoadExternalExtnameUndeclaredIdentifiers();
10662
10663 // Handle GNU asm-label extension (encoded as an attribute).
10664 if (Expr *E = D.getAsmLabel()) {
10665 // The parser guarantees this is a string.
10666 StringLiteral *SE = cast<StringLiteral>(Val: E);
10667 NewFD->addAttr(
10668 A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), Range: SE->getStrTokenLoc(TokNum: 0)));
10669 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10670 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10671 ExtnameUndeclaredIdentifiers.find(Key: NewFD->getIdentifier());
10672 if (I != ExtnameUndeclaredIdentifiers.end()) {
10673 if (isDeclExternC(D: NewFD)) {
10674 NewFD->addAttr(A: I->second);
10675 ExtnameUndeclaredIdentifiers.erase(Iterator: I);
10676 } else if (NewFD->getDeclContext()
10677 ->getRedeclContext()
10678 ->isTranslationUnit())
10679 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10680 << /*Variable*/0 << NewFD;
10681 }
10682 }
10683
10684 // Copy the parameter declarations from the declarator D to the function
10685 // declaration NewFD, if they are available. First scavenge them into Params.
10686 SmallVector<ParmVarDecl*, 16> Params;
10687 unsigned FTIIdx;
10688 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10689 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10690
10691 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10692 // function that takes no arguments, not a function that takes a
10693 // single void argument.
10694 // We let through "const void" here because Sema::GetTypeForDeclarator
10695 // already checks for that case.
10696 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10697 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10698 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10699 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10700 Param->setDeclContext(NewFD);
10701 Params.push_back(Elt: Param);
10702
10703 if (Param->isInvalidDecl())
10704 NewFD->setInvalidDecl();
10705 }
10706 }
10707
10708 if (!getLangOpts().CPlusPlus) {
10709 // In C, find all the tag declarations from the prototype and move them
10710 // into the function DeclContext. Remove them from the surrounding tag
10711 // injection context of the function, which is typically but not always
10712 // the TU.
10713 DeclContext *PrototypeTagContext =
10714 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10715 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10716 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10717
10718 // We don't want to reparent enumerators. Look at their parent enum
10719 // instead.
10720 if (!TD) {
10721 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10722 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10723 }
10724 if (!TD)
10725 continue;
10726 DeclContext *TagDC = TD->getLexicalDeclContext();
10727 if (!TagDC->containsDecl(D: TD))
10728 continue;
10729 TagDC->removeDecl(D: TD);
10730 TD->setDeclContext(NewFD);
10731 NewFD->addDecl(D: TD);
10732
10733 // Preserve the lexical DeclContext if it is not the surrounding tag
10734 // injection context of the FD. In this example, the semantic context of
10735 // E will be f and the lexical context will be S, while both the
10736 // semantic and lexical contexts of S will be f:
10737 // void f(struct S { enum E { a } f; } s);
10738 if (TagDC != PrototypeTagContext)
10739 TD->setLexicalDeclContext(TagDC);
10740 }
10741 }
10742 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10743 // When we're declaring a function with a typedef, typeof, etc as in the
10744 // following example, we'll need to synthesize (unnamed)
10745 // parameters for use in the declaration.
10746 //
10747 // @code
10748 // typedef void fn(int);
10749 // fn f;
10750 // @endcode
10751
10752 // Synthesize a parameter for each argument type.
10753 for (const auto &AI : FT->param_types()) {
10754 ParmVarDecl *Param =
10755 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10756 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10757 Params.push_back(Elt: Param);
10758 }
10759 } else {
10760 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10761 "Should not need args for typedef of non-prototype fn");
10762 }
10763
10764 // Finally, we know we have the right number of parameters, install them.
10765 NewFD->setParams(Params);
10766
10767 // If this declarator is a declaration and not a definition, its parameters
10768 // will not be pushed onto a scope chain. That means we will not issue any
10769 // reserved identifier warnings for the declaration, but we will for the
10770 // definition. Handle those here.
10771 if (!D.isFunctionDefinition()) {
10772 for (const ParmVarDecl *PVD : Params)
10773 warnOnReservedIdentifier(D: PVD);
10774 }
10775
10776 if (D.getDeclSpec().isNoreturnSpecified())
10777 NewFD->addAttr(
10778 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10779
10780 // Functions returning a variably modified type violate C99 6.7.5.2p2
10781 // because all functions have linkage.
10782 if (!NewFD->isInvalidDecl() &&
10783 NewFD->getReturnType()->isVariablyModifiedType()) {
10784 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10785 NewFD->setInvalidDecl();
10786 }
10787
10788 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10789 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10790 !NewFD->hasAttr<SectionAttr>())
10791 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10792 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10793 Range: PragmaClangTextSection.PragmaLocation));
10794
10795 // Apply an implicit SectionAttr if #pragma code_seg is active.
10796 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10797 !NewFD->hasAttr<SectionAttr>()) {
10798 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10799 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10800 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10801 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10802 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10803 ASTContext::PSF_Read,
10804 TheDecl: NewFD))
10805 NewFD->dropAttr<SectionAttr>();
10806 }
10807
10808 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10809 // active.
10810 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10811 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10812 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10813 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10814
10815 // Apply an implicit CodeSegAttr from class declspec or
10816 // apply an implicit SectionAttr from #pragma code_seg if active.
10817 if (!NewFD->hasAttr<CodeSegAttr>()) {
10818 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10819 IsDefinition: D.isFunctionDefinition())) {
10820 NewFD->addAttr(A: SAttr);
10821 }
10822 }
10823
10824 // Handle attributes.
10825 ProcessDeclAttributes(S, D: NewFD, PD: D);
10826 addImplicitCallingConvAbiTag(FD: NewFD);
10827 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10828 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10829 !NewTVA->isDefaultVersion() &&
10830 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10831 // Don't add to scope fmv functions declarations if fmv disabled
10832 AddToScope = false;
10833 return NewFD;
10834 }
10835
10836 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10837 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10838 // type.
10839 //
10840 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10841 // type declaration will generate a compilation error.
10842 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10843 if (AddressSpace != LangAS::Default) {
10844 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10845 NewFD->setInvalidDecl();
10846 }
10847 }
10848
10849 if (!getLangOpts().CPlusPlus) {
10850 // Perform semantic checking on the function declaration.
10851 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10852 CheckMain(FD: NewFD, D: D.getDeclSpec());
10853
10854 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10855 CheckMSVCRTEntryPoint(FD: NewFD);
10856
10857 if (!NewFD->isInvalidDecl())
10858 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10859 IsMemberSpecialization: isMemberSpecialization,
10860 DeclIsDefn: D.isFunctionDefinition()));
10861 else if (!Previous.empty())
10862 // Recover gracefully from an invalid redeclaration.
10863 D.setRedeclaration(true);
10864 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10865 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10866 "previous declaration set still overloaded");
10867
10868 // Diagnose no-prototype function declarations with calling conventions that
10869 // don't support variadic calls. Only do this in C and do it after merging
10870 // possibly prototyped redeclarations.
10871 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10872 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10873 CallingConv CC = FT->getExtInfo().getCC();
10874 if (!supportsVariadicCall(CC)) {
10875 // Windows system headers sometimes accidentally use stdcall without
10876 // (void) parameters, so we relax this to a warning.
10877 int DiagID =
10878 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10879 Diag(Loc: NewFD->getLocation(), DiagID)
10880 << FunctionType::getNameForCallConv(CC);
10881 }
10882 }
10883
10884 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10885 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10886 checkNonTrivialCUnion(
10887 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10888 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10889 } else {
10890 // C++11 [replacement.functions]p3:
10891 // The program's definitions shall not be specified as inline.
10892 //
10893 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10894 //
10895 // Suppress the diagnostic if the function is __attribute__((used)), since
10896 // that forces an external definition to be emitted.
10897 if (D.getDeclSpec().isInlineSpecified() &&
10898 NewFD->isReplaceableGlobalAllocationFunction() &&
10899 !NewFD->hasAttr<UsedAttr>())
10900 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10901 DiagID: diag::ext_operator_new_delete_declared_inline)
10902 << NewFD->getDeclName();
10903
10904 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10905 // C++20 [dcl.decl.general]p4:
10906 // The optional requires-clause in an init-declarator or
10907 // member-declarator shall be present only if the declarator declares a
10908 // templated function.
10909 //
10910 // C++20 [temp.pre]p8:
10911 // An entity is templated if it is
10912 // - a template,
10913 // - an entity defined or created in a templated entity,
10914 // - a member of a templated entity,
10915 // - an enumerator for an enumeration that is a templated entity, or
10916 // - the closure type of a lambda-expression appearing in the
10917 // declaration of a templated entity.
10918 //
10919 // [Note 6: A local class, a local or block variable, or a friend
10920 // function defined in a templated entity is a templated entity.
10921 // — end note]
10922 //
10923 // A templated function is a function template or a function that is
10924 // templated. A templated class is a class template or a class that is
10925 // templated. A templated variable is a variable template or a variable
10926 // that is templated.
10927 if (!FunctionTemplate) {
10928 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10929 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10930 // An explicit specialization shall not have a trailing
10931 // requires-clause unless it declares a function template.
10932 //
10933 // Since a friend function template specialization cannot be
10934 // definition, and since a non-template friend declaration with a
10935 // trailing requires-clause must be a definition, we diagnose
10936 // friend function template specializations with trailing
10937 // requires-clauses on the same path as explicit specializations
10938 // even though they aren't necessarily prohibited by the same
10939 // language rule.
10940 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
10941 << isFriend;
10942 } else if (isFriend && NewFD->isTemplated() &&
10943 !D.isFunctionDefinition()) {
10944 // C++ [temp.friend]p9:
10945 // A non-template friend declaration with a requires-clause shall be
10946 // a definition.
10947 Diag(Loc: NewFD->getBeginLoc(),
10948 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10949 NewFD->setInvalidDecl();
10950 } else if (!NewFD->isTemplated() ||
10951 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10952 Diag(Loc: TRC->getBeginLoc(),
10953 DiagID: diag::err_constrained_non_templated_function);
10954 }
10955 }
10956 }
10957
10958 // We do not add HD attributes to specializations here because
10959 // they may have different constexpr-ness compared to their
10960 // templates and, after maybeAddHostDeviceAttrs() is applied,
10961 // may end up with different effective targets. Instead, a
10962 // specialization inherits its target attributes from its template
10963 // in the CheckFunctionTemplateSpecialization() call below.
10964 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10965 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
10966
10967 // Handle explicit specializations of function templates
10968 // and friend function declarations with an explicit
10969 // template argument list.
10970 if (isFunctionTemplateSpecialization) {
10971 bool isDependentSpecialization = false;
10972 if (isFriend) {
10973 // For friend function specializations, this is a dependent
10974 // specialization if its semantic context is dependent, its
10975 // qualifier is dependent, its type is dependent, or its template-id is
10976 // dependent.
10977 isDependentSpecialization =
10978 DC->isDependentContext() || NewFD->getQualifier().isDependent() ||
10979 NewFD->getType()->isDependentType() ||
10980 (HasExplicitTemplateArgs &&
10981 TemplateSpecializationType::
10982 anyInstantiationDependentTemplateArguments(
10983 Args: TemplateArgs.arguments()));
10984 assert((!isDependentSpecialization ||
10985 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10986 "dependent friend function specialization without template "
10987 "args");
10988 } else {
10989 // For class-scope explicit specializations of function templates,
10990 // if the lexical context is dependent, then the specialization
10991 // is dependent.
10992 isDependentSpecialization =
10993 CurContext->isRecord() && CurContext->isDependentContext();
10994 }
10995
10996 TemplateArgumentListInfo *ExplicitTemplateArgs =
10997 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10998 if (isDependentSpecialization) {
10999 // If it's a dependent specialization, it may not be possible
11000 // to determine the primary template (for explicit specializations)
11001 // or befriended declaration (for friends) until the enclosing
11002 // template is instantiated. In such cases, we store the declarations
11003 // found by name lookup and defer resolution until instantiation.
11004 if (CheckDependentFunctionTemplateSpecialization(
11005 FD: NewFD, ExplicitTemplateArgs, Previous))
11006 NewFD->setInvalidDecl();
11007 } else if (!NewFD->isInvalidDecl()) {
11008 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
11009 Previous))
11010 NewFD->setInvalidDecl();
11011 }
11012 } else if (isMemberSpecialization && !FunctionTemplate) {
11013 if (CheckMemberSpecialization(Member: NewFD, Previous))
11014 NewFD->setInvalidDecl();
11015 }
11016
11017 // Perform semantic checking on the function declaration.
11018 if (!NewFD->isInvalidDecl() && NewFD->isMain())
11019 CheckMain(FD: NewFD, D: D.getDeclSpec());
11020
11021 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
11022 CheckMSVCRTEntryPoint(FD: NewFD);
11023
11024 if (!NewFD->isInvalidDecl())
11025 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
11026 IsMemberSpecialization: isMemberSpecialization,
11027 DeclIsDefn: D.isFunctionDefinition()));
11028 else if (!Previous.empty())
11029 // Recover gracefully from an invalid redeclaration.
11030 D.setRedeclaration(true);
11031
11032 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
11033 !D.isRedeclaration() ||
11034 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
11035 "previous declaration set still overloaded");
11036
11037 NamedDecl *PrincipalDecl = (FunctionTemplate
11038 ? cast<NamedDecl>(Val: FunctionTemplate)
11039 : NewFD);
11040
11041 if (isFriend && NewFD->getPreviousDecl()) {
11042 AccessSpecifier Access = AS_public;
11043 if (!NewFD->isInvalidDecl())
11044 Access = NewFD->getPreviousDecl()->getAccess();
11045
11046 NewFD->setAccess(Access);
11047 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
11048 }
11049
11050 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
11051 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
11052 PrincipalDecl->setNonMemberOperator();
11053
11054 // If we have a function template, check the template parameter
11055 // list. This will check and merge default template arguments.
11056 if (FunctionTemplate) {
11057 FunctionTemplateDecl *PrevTemplate =
11058 FunctionTemplate->getPreviousDecl();
11059 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
11060 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
11061 : nullptr,
11062 TPC: D.getDeclSpec().isFriendSpecified()
11063 ? (D.isFunctionDefinition()
11064 ? TPC_FriendFunctionTemplateDefinition
11065 : TPC_FriendFunctionTemplate)
11066 : (D.getCXXScopeSpec().isSet() &&
11067 DC && DC->isRecord() &&
11068 DC->isDependentContext())
11069 ? TPC_ClassTemplateMember
11070 : TPC_FunctionTemplate);
11071 }
11072
11073 if (NewFD->isInvalidDecl()) {
11074 // Ignore all the rest of this.
11075 } else if (!D.isRedeclaration()) {
11076 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
11077 .AddToScope: AddToScope };
11078 // Fake up an access specifier if it's supposed to be a class member.
11079 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
11080 NewFD->setAccess(AS_public);
11081
11082 // Qualified decls generally require a previous declaration.
11083 if (D.getCXXScopeSpec().isSet()) {
11084 // ...with the major exception of templated-scope or
11085 // dependent-scope friend declarations.
11086
11087 // TODO: we currently also suppress this check in dependent
11088 // contexts because (1) the parameter depth will be off when
11089 // matching friend templates and (2) we might actually be
11090 // selecting a friend based on a dependent factor. But there
11091 // are situations where these conditions don't apply and we
11092 // can actually do this check immediately.
11093 //
11094 // Unless the scope is dependent, it's always an error if qualified
11095 // redeclaration lookup found nothing at all. Diagnose that now;
11096 // nothing will diagnose that error later.
11097 if (isFriend &&
11098 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
11099 (!Previous.empty() && CurContext->isDependentContext()))) {
11100 // ignore these
11101 } else if (NewFD->isCPUDispatchMultiVersion() ||
11102 NewFD->isCPUSpecificMultiVersion()) {
11103 // ignore this, we allow the redeclaration behavior here to create new
11104 // versions of the function.
11105 } else {
11106 // The user tried to provide an out-of-line definition for a
11107 // function that is a member of a class or namespace, but there
11108 // was no such member function declared (C++ [class.mfct]p2,
11109 // C++ [namespace.memdef]p2). For example:
11110 //
11111 // class X {
11112 // void f() const;
11113 // };
11114 //
11115 // void X::f() { } // ill-formed
11116 //
11117 // Complain about this problem, and attempt to suggest close
11118 // matches (e.g., those that differ only in cv-qualifiers and
11119 // whether the parameter types are references).
11120
11121 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11122 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
11123 AddToScope = ExtraArgs.AddToScope;
11124 return Result;
11125 }
11126 }
11127
11128 // Unqualified local friend declarations are required to resolve
11129 // to something.
11130 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
11131 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
11132 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
11133 AddToScope = ExtraArgs.AddToScope;
11134 return Result;
11135 }
11136 }
11137 } else if (!D.isFunctionDefinition() &&
11138 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
11139 !isFriend && !isFunctionTemplateSpecialization &&
11140 !isMemberSpecialization) {
11141 // An out-of-line member function declaration must also be a
11142 // definition (C++ [class.mfct]p2).
11143 // Note that this is not the case for explicit specializations of
11144 // function templates or member functions of class templates, per
11145 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11146 // extension for compatibility with old SWIG code which likes to
11147 // generate them.
11148 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
11149 << D.getCXXScopeSpec().getRange();
11150 }
11151 }
11152
11153 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11154 // Any top level function could potentially be specified as an entry.
11155 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11156 HLSL().ActOnTopLevelFunction(FD: NewFD);
11157
11158 if (NewFD->hasAttr<HLSLShaderAttr>())
11159 HLSL().CheckEntryPoint(FD: NewFD);
11160
11161 // Resources cannot be passed to functions that are not inlined.
11162 if (const NoInlineAttr *NoInline = NewFD->getAttr<NoInlineAttr>()) {
11163 for (const ParmVarDecl *PVD : NewFD->parameters()) {
11164 QualType ParamTy = PVD->getType().getNonReferenceType();
11165 QualType EltTy = Context.getBaseElementType(QT: ParamTy);
11166 // `isCompleteType` forces completion of the element type without
11167 // reporting an error (diagnosed elsewhere) so the resource parameter
11168 // check is valid.
11169 if (!EltTy->isDependentType() &&
11170 isCompleteType(Loc: PVD->getLocation(), T: EltTy) &&
11171 ParamTy->isHLSLIntangibleType()) {
11172 Diag(Loc: PVD->getLocation(),
11173 DiagID: diag::err_hlsl_resource_param_in_noinline_function)
11174 << ParamTy;
11175 Diag(Loc: NoInline->getLocation(), DiagID: diag::note_attribute);
11176 }
11177 }
11178 }
11179 }
11180
11181 // If this is the first declaration of a library builtin function, add
11182 // attributes as appropriate.
11183 if (!D.isRedeclaration()) {
11184 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11185 if (unsigned BuiltinID = II->getBuiltinID()) {
11186 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
11187 if (!InStdNamespace &&
11188 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11189 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11190 // Validate the type matches unless this builtin is specified as
11191 // matching regardless of its declared type.
11192 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
11193 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11194 } else {
11195 ASTContext::GetBuiltinTypeError Error;
11196 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
11197 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
11198
11199 if (!Error && !BuiltinType.isNull() &&
11200 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11201 T: NewFD->getType(), U: BuiltinType))
11202 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11203 }
11204 }
11205 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11206 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
11207 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11208 }
11209 }
11210 }
11211 }
11212
11213 ProcessPragmaWeak(S, D: NewFD);
11214 ProcessPragmaExport(NewD: NewFD);
11215 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
11216
11217 AddKnownFunctionAttributes(FD: NewFD);
11218 // The above can add the format attribute for known builtin/library functions
11219 // which is required by the modular_format attribute, thus
11220 // validate modular_format now after those attributes have been added.
11221 checkModularFormatAttr(S&: *this, ND&: *NewFD);
11222
11223 if (NewFD->hasAttr<OverloadableAttr>() &&
11224 !NewFD->getType()->getAs<FunctionProtoType>()) {
11225 Diag(Loc: NewFD->getLocation(),
11226 DiagID: diag::err_attribute_overloadable_no_prototype)
11227 << NewFD;
11228 NewFD->dropAttr<OverloadableAttr>();
11229 }
11230
11231 // If there's a #pragma GCC visibility in scope, and this isn't a class
11232 // member, set the visibility of this function.
11233 if (!DC->isRecord() && NewFD->isExternallyVisible())
11234 AddPushedVisibilityAttribute(RD: NewFD);
11235
11236 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11237 // marking the function.
11238 ObjC().AddCFAuditedAttribute(D: NewFD);
11239
11240 // If this is a function definition, check if we have to apply any
11241 // attributes (i.e. optnone and no_builtin) due to a pragma.
11242 if (D.isFunctionDefinition()) {
11243 AddRangeBasedOptnone(FD: NewFD);
11244 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
11245 AddSectionMSAllocText(FD: NewFD);
11246 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
11247 }
11248
11249 // If this is the first declaration of an extern C variable, update
11250 // the map of such variables.
11251 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11252 isIncompleteDeclExternC(S&: *this, D: NewFD))
11253 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
11254
11255 // Set this FunctionDecl's range up to the right paren.
11256 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11257
11258 if (D.isRedeclaration() && !Previous.empty()) {
11259 NamedDecl *Prev = Previous.getRepresentativeDecl();
11260 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
11261 IsSpecialization: isMemberSpecialization ||
11262 isFunctionTemplateSpecialization,
11263 IsDefinition: D.isFunctionDefinition());
11264 }
11265
11266 if (getLangOpts().CUDA) {
11267 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11268 if (II->isStr(Str: CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11269 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11270 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11271 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11272 << CUDA().getConfigureFuncName();
11273 Context.setcudaConfigureCallDecl(NewFD);
11274 }
11275 if (II->isStr(Str: CUDA().getGetParameterBufferFuncName()) &&
11276 !NewFD->isInvalidDecl() &&
11277 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11278 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11279 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_pointer_return)
11280 << CUDA().getConfigureFuncName();
11281 Context.setcudaGetParameterBufferDecl(NewFD);
11282 }
11283 if (II->isStr(Str: CUDA().getLaunchDeviceFuncName()) &&
11284 !NewFD->isInvalidDecl() &&
11285 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11286 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11287 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11288 << CUDA().getConfigureFuncName();
11289 Context.setcudaLaunchDeviceDecl(NewFD);
11290 }
11291 }
11292 }
11293
11294 MarkUnusedFileScopedDecl(D: NewFD);
11295
11296 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11297 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11298 if (SC == SC_Static) {
11299 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
11300 D.setInvalidType();
11301 }
11302
11303 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11304 if (!NewFD->getReturnType()->isVoidType()) {
11305 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11306 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
11307 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
11308 : FixItHint());
11309 D.setInvalidType();
11310 }
11311
11312 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11313 for (auto *Param : NewFD->parameters())
11314 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
11315
11316 if (getLangOpts().OpenCLCPlusPlus) {
11317 if (DC->isRecord()) {
11318 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
11319 D.setInvalidType();
11320 }
11321 if (FunctionTemplate) {
11322 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
11323 D.setInvalidType();
11324 }
11325 }
11326 }
11327
11328 if (getLangOpts().CPlusPlus) {
11329 // Precalculate whether this is a friend function template with a constraint
11330 // that depends on an enclosing template, per [temp.friend]p9.
11331 if (isFriend && FunctionTemplate &&
11332 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
11333 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11334
11335 // C++ [temp.friend]p9:
11336 // A friend function template with a constraint that depends on a
11337 // template parameter from an enclosing template shall be a definition.
11338 if (!D.isFunctionDefinition()) {
11339 Diag(Loc: NewFD->getBeginLoc(),
11340 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11341 NewFD->setInvalidDecl();
11342 }
11343 }
11344
11345 if (FunctionTemplate) {
11346 if (NewFD->isInvalidDecl())
11347 FunctionTemplate->setInvalidDecl();
11348 return FunctionTemplate;
11349 }
11350
11351 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11352 CompleteMemberSpecialization(Member: NewFD, Previous);
11353 }
11354
11355 for (const ParmVarDecl *Param : NewFD->parameters()) {
11356 QualType PT = Param->getType();
11357
11358 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11359 // types.
11360 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11361 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11362 QualType ElemTy = PipeTy->getElementType();
11363 if (ElemTy->isPointerOrReferenceType()) {
11364 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11365 D.setInvalidType();
11366 }
11367 }
11368 }
11369 // WebAssembly tables can't be used as function parameters.
11370 if (Context.getTargetInfo().getTriple().isWasm()) {
11371 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11372 Diag(Loc: Param->getTypeSpecStartLoc(),
11373 DiagID: diag::err_wasm_table_as_function_parameter);
11374 D.setInvalidType();
11375 }
11376 }
11377 }
11378
11379 // Diagnose availability attributes. Availability cannot be used on functions
11380 // that are run during load/unload.
11381 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11382 if (NewFD->hasAttr<ConstructorAttr>()) {
11383 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11384 << 1;
11385 NewFD->dropAttr<AvailabilityAttr>();
11386 }
11387 if (NewFD->hasAttr<DestructorAttr>()) {
11388 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11389 << 2;
11390 NewFD->dropAttr<AvailabilityAttr>();
11391 }
11392 }
11393
11394 // Diagnose no_builtin attribute on function declaration that are not a
11395 // definition.
11396 // FIXME: We should really be doing this in
11397 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11398 // the FunctionDecl and at this point of the code
11399 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11400 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11401 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11402 switch (D.getFunctionDefinitionKind()) {
11403 case FunctionDefinitionKind::Defaulted:
11404 case FunctionDefinitionKind::Deleted:
11405 Diag(Loc: NBA->getLocation(),
11406 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11407 << NBA->getSpelling();
11408 break;
11409 case FunctionDefinitionKind::Declaration:
11410 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11411 << NBA->getSpelling();
11412 break;
11413 case FunctionDefinitionKind::Definition:
11414 break;
11415 }
11416
11417 // Similar to no_builtin logic above, at this point of the code
11418 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11419 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11420 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11421 !NewFD->isInvalidDecl() &&
11422 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11423 ExternalDeclarations.push_back(Elt: NewFD);
11424
11425 // Used for a warning on the 'next' declaration when used with a
11426 // `routine(name)`.
11427 if (getLangOpts().OpenACC)
11428 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11429
11430 return NewFD;
11431}
11432
11433/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11434/// when __declspec(code_seg) "is applied to a class, all member functions of
11435/// the class and nested classes -- this includes compiler-generated special
11436/// member functions -- are put in the specified segment."
11437/// The actual behavior is a little more complicated. The Microsoft compiler
11438/// won't check outer classes if there is an active value from #pragma code_seg.
11439/// The CodeSeg is always applied from the direct parent but only from outer
11440/// classes when the #pragma code_seg stack is empty. See:
11441/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11442/// available since MS has removed the page.
11443static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11444 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11445 if (!Method)
11446 return nullptr;
11447 const CXXRecordDecl *Parent = Method->getParent();
11448 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11449 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11450 NewAttr->setImplicit(true);
11451 return NewAttr;
11452 }
11453
11454 // The Microsoft compiler won't check outer classes for the CodeSeg
11455 // when the #pragma code_seg stack is active.
11456 if (S.CodeSegStack.CurrentValue)
11457 return nullptr;
11458
11459 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11460 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11461 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11462 NewAttr->setImplicit(true);
11463 return NewAttr;
11464 }
11465 }
11466 return nullptr;
11467}
11468
11469Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11470 bool IsDefinition) {
11471 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11472 return A;
11473 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11474 CodeSegStack.CurrentValue)
11475 return SectionAttr::CreateImplicit(
11476 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11477 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11478 return nullptr;
11479}
11480
11481bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11482 QualType NewT, QualType OldT) {
11483 if (!NewD->getLexicalDeclContext()->isDependentContext())
11484 return true;
11485
11486 // For dependently-typed local extern declarations and friends, we can't
11487 // perform a correct type check in general until instantiation:
11488 //
11489 // int f();
11490 // template<typename T> void g() { T f(); }
11491 //
11492 // (valid if g() is only instantiated with T = int).
11493 if (NewT->isDependentType() &&
11494 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11495 return false;
11496
11497 // Similarly, if the previous declaration was a dependent local extern
11498 // declaration, we don't really know its type yet.
11499 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11500 return false;
11501
11502 return true;
11503}
11504
11505bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11506 if (!D->getLexicalDeclContext()->isDependentContext())
11507 return true;
11508
11509 // Don't chain dependent friend function definitions until instantiation, to
11510 // permit cases like
11511 //
11512 // void func();
11513 // template<typename T> class C1 { friend void func() {} };
11514 // template<typename T> class C2 { friend void func() {} };
11515 //
11516 // ... which is valid if only one of C1 and C2 is ever instantiated.
11517 //
11518 // FIXME: This need only apply to function definitions. For now, we proxy
11519 // this by checking for a file-scope function. We do not want this to apply
11520 // to friend declarations nominating member functions, because that gets in
11521 // the way of access checks.
11522 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11523 return false;
11524
11525 auto *VD = dyn_cast<ValueDecl>(Val: D);
11526 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11527 return !VD || !PrevVD ||
11528 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11529 OldT: PrevVD->getType());
11530}
11531
11532/// Check the target or target_version attribute of the function for
11533/// MultiVersion validity.
11534///
11535/// Returns true if there was an error, false otherwise.
11536static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11537 const auto *TA = FD->getAttr<TargetAttr>();
11538 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11539
11540 assert((TA || TVA) && "Expecting target or target_version attribute");
11541
11542 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11543 enum ErrType { Feature = 0, Architecture = 1 };
11544
11545 if (TA) {
11546 ParsedTargetAttr ParseInfo =
11547 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11548 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11549 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11550 << Architecture << ParseInfo.CPU;
11551 return true;
11552 }
11553 for (const auto &Feat : ParseInfo.Features) {
11554 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11555 if (Feat[0] == '-') {
11556 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11557 << Feature << ("no-" + BareFeat);
11558 return true;
11559 }
11560
11561 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11562 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11563 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11564 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11565 << Feature << BareFeat;
11566 return true;
11567 }
11568 }
11569 }
11570
11571 if (TVA) {
11572 llvm::SmallVector<StringRef, 8> Feats;
11573 ParsedTargetAttr ParseInfo;
11574 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11575 ParseInfo =
11576 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11577 for (auto &Feat : ParseInfo.Features)
11578 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11579 } else {
11580 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11581 TVA->getFeatures(Out&: Feats);
11582 }
11583 for (const auto &Feat : Feats) {
11584 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11585 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11586 << Feature << Feat;
11587 return true;
11588 }
11589 }
11590 }
11591 return false;
11592}
11593
11594// Provide a white-list of attributes that are allowed to be combined with
11595// multiversion functions.
11596static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11597 MultiVersionKind MVKind) {
11598 // Note: this list/diagnosis must match the list in
11599 // checkMultiversionAttributesAllSame.
11600 switch (Kind) {
11601 default:
11602 return false;
11603 case attr::ArmLocallyStreaming:
11604 return MVKind == MultiVersionKind::TargetVersion ||
11605 MVKind == MultiVersionKind::TargetClones;
11606 case attr::Used:
11607 return MVKind == MultiVersionKind::Target;
11608 case attr::NonNull:
11609 case attr::NoThrow:
11610 return true;
11611 }
11612}
11613
11614static bool checkNonMultiVersionCompatAttributes(Sema &S,
11615 const FunctionDecl *FD,
11616 const FunctionDecl *CausedFD,
11617 MultiVersionKind MVKind) {
11618 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11619 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11620 << static_cast<unsigned>(MVKind) << A;
11621 if (CausedFD)
11622 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11623 return true;
11624 };
11625
11626 for (const Attr *A : FD->attrs()) {
11627 switch (A->getKind()) {
11628 case attr::CPUDispatch:
11629 case attr::CPUSpecific:
11630 if (MVKind != MultiVersionKind::CPUDispatch &&
11631 MVKind != MultiVersionKind::CPUSpecific)
11632 return Diagnose(S, A);
11633 break;
11634 case attr::Target:
11635 if (MVKind != MultiVersionKind::Target)
11636 return Diagnose(S, A);
11637 break;
11638 case attr::TargetVersion:
11639 if (MVKind != MultiVersionKind::TargetVersion &&
11640 MVKind != MultiVersionKind::TargetClones)
11641 return Diagnose(S, A);
11642 break;
11643 case attr::TargetClones:
11644 if (MVKind != MultiVersionKind::TargetClones &&
11645 MVKind != MultiVersionKind::TargetVersion)
11646 return Diagnose(S, A);
11647 break;
11648 default:
11649 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11650 return Diagnose(S, A);
11651 break;
11652 }
11653 }
11654 return false;
11655}
11656
11657bool Sema::areMultiversionVariantFunctionsCompatible(
11658 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11659 const PartialDiagnostic &NoProtoDiagID,
11660 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11661 const PartialDiagnosticAt &NoSupportDiagIDAt,
11662 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11663 bool ConstexprSupported, bool CLinkageMayDiffer) {
11664 enum DoesntSupport {
11665 FuncTemplates = 0,
11666 VirtFuncs = 1,
11667 DeducedReturn = 2,
11668 Constructors = 3,
11669 Destructors = 4,
11670 DeletedFuncs = 5,
11671 DefaultedFuncs = 6,
11672 ConstexprFuncs = 7,
11673 ConstevalFuncs = 8,
11674 Lambda = 9,
11675 };
11676 enum Different {
11677 CallingConv = 0,
11678 ReturnType = 1,
11679 ConstexprSpec = 2,
11680 InlineSpec = 3,
11681 Linkage = 4,
11682 LanguageLinkage = 5,
11683 };
11684
11685 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11686 !OldFD->getType()->getAs<FunctionProtoType>()) {
11687 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11688 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11689 return true;
11690 }
11691
11692 if (NoProtoDiagID.getDiagID() != 0 &&
11693 !NewFD->getType()->getAs<FunctionProtoType>())
11694 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11695
11696 if (!TemplatesSupported &&
11697 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11698 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11699 << FuncTemplates;
11700
11701 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11702 if (NewCXXFD->isVirtual())
11703 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11704 << VirtFuncs;
11705
11706 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11707 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11708 << Constructors;
11709
11710 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11711 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11712 << Destructors;
11713 }
11714
11715 if (NewFD->isDeleted())
11716 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11717 << DeletedFuncs;
11718
11719 if (NewFD->isDefaulted())
11720 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11721 << DefaultedFuncs;
11722
11723 if (!ConstexprSupported && NewFD->isConstexpr())
11724 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11725 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11726
11727 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11728 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11729 QualType NewReturnType = NewType->getReturnType();
11730
11731 if (NewReturnType->isUndeducedType())
11732 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11733 << DeducedReturn;
11734
11735 // Ensure the return type is identical.
11736 if (OldFD) {
11737 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11738 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11739 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11740 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11741
11742 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11743 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11744
11745 bool ArmStreamingCCMismatched = false;
11746 if (OldFPT && NewFPT) {
11747 unsigned Diff =
11748 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11749 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11750 // cannot be mixed.
11751 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11752 FunctionType::SME_PStateSMCompatibleMask))
11753 ArmStreamingCCMismatched = true;
11754 }
11755
11756 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11757 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11758
11759 QualType OldReturnType = OldType->getReturnType();
11760
11761 if (OldReturnType != NewReturnType)
11762 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11763
11764 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11765 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11766
11767 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11768 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11769
11770 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11771 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11772
11773 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11774 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11775
11776 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11777 NewLoc: NewFD->getLocation()))
11778 return true;
11779 }
11780 return false;
11781}
11782
11783static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11784 const FunctionDecl *NewFD,
11785 bool CausesMV,
11786 MultiVersionKind MVKind) {
11787 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11788 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11789 if (OldFD)
11790 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11791 return true;
11792 }
11793
11794 bool IsCPUSpecificCPUDispatchMVKind =
11795 MVKind == MultiVersionKind::CPUDispatch ||
11796 MVKind == MultiVersionKind::CPUSpecific;
11797
11798 if (CausesMV && OldFD &&
11799 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11800 return true;
11801
11802 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11803 return true;
11804
11805 // Only allow transition to MultiVersion if it hasn't been used.
11806 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11807 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11808 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11809 return true;
11810 }
11811
11812 return S.areMultiversionVariantFunctionsCompatible(
11813 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11814 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11815 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11816 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11817 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11818 << static_cast<unsigned>(MVKind)),
11819 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11820 S.PDiag(DiagID: diag::err_multiversion_diff)),
11821 /*TemplatesSupported=*/false,
11822 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11823 /*CLinkageMayDiffer=*/false);
11824}
11825
11826/// Check the validity of a multiversion function declaration that is the
11827/// first of its kind. Also sets the multiversion'ness' of the function itself.
11828///
11829/// This sets NewFD->isInvalidDecl() to true if there was an error.
11830///
11831/// Returns true if there was an error, false otherwise.
11832static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11833 MultiVersionKind MVKind = FD->getMultiVersionKind();
11834 assert(MVKind != MultiVersionKind::None &&
11835 "Function lacks multiversion attribute");
11836 const auto *TA = FD->getAttr<TargetAttr>();
11837 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11838 // The target attribute only causes MV if this declaration is the default,
11839 // otherwise it is treated as a normal function.
11840 if (TA && !TA->isDefaultVersion())
11841 return false;
11842
11843 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11844 FD->setInvalidDecl();
11845 return true;
11846 }
11847
11848 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11849 FD->setInvalidDecl();
11850 return true;
11851 }
11852
11853 FD->setIsMultiVersion();
11854 return false;
11855}
11856
11857static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11858 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11859 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11860 return true;
11861 }
11862
11863 return false;
11864}
11865
11866static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11867 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11868 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11869 return;
11870
11871 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11872 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11873
11874 if (MVKindTo == MultiVersionKind::None &&
11875 (MVKindFrom == MultiVersionKind::TargetVersion ||
11876 MVKindFrom == MultiVersionKind::TargetClones))
11877 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11878 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11879}
11880
11881static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11882 FunctionDecl *NewFD,
11883 bool &Redeclaration,
11884 NamedDecl *&OldDecl,
11885 LookupResult &Previous) {
11886 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11887
11888 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11889 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11890 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11891 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11892
11893 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11894
11895 // The definitions should be allowed in any order. If we have discovered
11896 // a new target version and the preceeding was the default, then add the
11897 // corresponding attribute to it.
11898 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11899
11900 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11901 // to change, this is a simple redeclaration.
11902 if (NewTA && !NewTA->isDefaultVersion() &&
11903 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11904 return false;
11905
11906 // Otherwise, this decl causes MultiVersioning.
11907 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11908 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11909 : MultiVersionKind::Target)) {
11910 NewFD->setInvalidDecl();
11911 return true;
11912 }
11913
11914 if (CheckMultiVersionValue(S, FD: NewFD)) {
11915 NewFD->setInvalidDecl();
11916 return true;
11917 }
11918
11919 // If this is 'default', permit the forward declaration.
11920 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11921 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11922 Redeclaration = true;
11923 OldDecl = OldFD;
11924 OldFD->setIsMultiVersion();
11925 NewFD->setIsMultiVersion();
11926 return false;
11927 }
11928
11929 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11930 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11931 NewFD->setInvalidDecl();
11932 return true;
11933 }
11934
11935 if (NewTA) {
11936 ParsedTargetAttr OldParsed =
11937 S.getASTContext().getTargetInfo().parseTargetAttr(
11938 Str: OldTA->getFeaturesStr());
11939 llvm::sort(C&: OldParsed.Features);
11940 ParsedTargetAttr NewParsed =
11941 S.getASTContext().getTargetInfo().parseTargetAttr(
11942 Str: NewTA->getFeaturesStr());
11943 // Sort order doesn't matter, it just needs to be consistent.
11944 llvm::sort(C&: NewParsed.Features);
11945 if (OldParsed == NewParsed) {
11946 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11947 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11948 NewFD->setInvalidDecl();
11949 return true;
11950 }
11951 }
11952
11953 for (const auto *FD : OldFD->redecls()) {
11954 const auto *CurTA = FD->getAttr<TargetAttr>();
11955 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11956 // We allow forward declarations before ANY multiversioning attributes, but
11957 // nothing after the fact.
11958 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11959 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11960 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11961 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
11962 << (NewTA ? 0 : 2);
11963 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11964 NewFD->setInvalidDecl();
11965 return true;
11966 }
11967 }
11968
11969 OldFD->setIsMultiVersion();
11970 NewFD->setIsMultiVersion();
11971 Redeclaration = false;
11972 OldDecl = nullptr;
11973 Previous.clear();
11974 return false;
11975}
11976
11977static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11978 MultiVersionKind OldKind = Old->getMultiVersionKind();
11979 MultiVersionKind NewKind = New->getMultiVersionKind();
11980
11981 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11982 NewKind == MultiVersionKind::None)
11983 return true;
11984
11985 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11986 switch (OldKind) {
11987 case MultiVersionKind::TargetVersion:
11988 return NewKind == MultiVersionKind::TargetClones;
11989 case MultiVersionKind::TargetClones:
11990 return NewKind == MultiVersionKind::TargetVersion;
11991 default:
11992 return false;
11993 }
11994 } else {
11995 switch (OldKind) {
11996 case MultiVersionKind::CPUDispatch:
11997 return NewKind == MultiVersionKind::CPUSpecific;
11998 case MultiVersionKind::CPUSpecific:
11999 return NewKind == MultiVersionKind::CPUDispatch;
12000 default:
12001 return false;
12002 }
12003 }
12004}
12005
12006/// Check the validity of a new function declaration being added to an existing
12007/// multiversioned declaration collection.
12008static bool CheckMultiVersionAdditionalDecl(
12009 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
12010 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
12011 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
12012 LookupResult &Previous) {
12013
12014 // Disallow mixing of multiversioning types.
12015 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
12016 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
12017 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
12018 NewFD->setInvalidDecl();
12019 return true;
12020 }
12021
12022 // Add the default target_version attribute if it's missing.
12023 patchDefaultTargetVersion(From: OldFD, To: NewFD);
12024 patchDefaultTargetVersion(From: NewFD, To: OldFD);
12025
12026 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12027 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12028 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
12029 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
12030
12031 ParsedTargetAttr NewParsed;
12032 if (NewTA) {
12033 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
12034 Str: NewTA->getFeaturesStr());
12035 llvm::sort(C&: NewParsed.Features);
12036 }
12037 llvm::SmallVector<StringRef, 8> NewFeats;
12038 if (NewTVA) {
12039 NewTVA->getFeatures(Out&: NewFeats);
12040 llvm::sort(C&: NewFeats);
12041 }
12042
12043 bool UseMemberUsingDeclRules =
12044 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
12045
12046 bool MayNeedOverloadableChecks =
12047 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
12048
12049 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
12050 // of a previous member of the MultiVersion set.
12051 for (NamedDecl *ND : Previous) {
12052 FunctionDecl *CurFD = ND->getAsFunction();
12053 if (!CurFD || CurFD->isInvalidDecl())
12054 continue;
12055 if (MayNeedOverloadableChecks &&
12056 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
12057 continue;
12058
12059 switch (NewMVKind) {
12060 case MultiVersionKind::None:
12061 assert(OldMVKind == MultiVersionKind::TargetClones &&
12062 "Only target_clones can be omitted in subsequent declarations");
12063 break;
12064 case MultiVersionKind::Target: {
12065 const auto *CurTA = CurFD->getAttr<TargetAttr>();
12066 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
12067 NewFD->setIsMultiVersion();
12068 Redeclaration = true;
12069 OldDecl = ND;
12070 return false;
12071 }
12072
12073 ParsedTargetAttr CurParsed =
12074 S.getASTContext().getTargetInfo().parseTargetAttr(
12075 Str: CurTA->getFeaturesStr());
12076 llvm::sort(C&: CurParsed.Features);
12077 if (CurParsed == NewParsed) {
12078 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12079 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12080 NewFD->setInvalidDecl();
12081 return true;
12082 }
12083 break;
12084 }
12085 case MultiVersionKind::TargetVersion: {
12086 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12087 if (CurTVA->getName() == NewTVA->getName()) {
12088 NewFD->setIsMultiVersion();
12089 Redeclaration = true;
12090 OldDecl = ND;
12091 return false;
12092 }
12093 llvm::SmallVector<StringRef, 8> CurFeats;
12094 CurTVA->getFeatures(Out&: CurFeats);
12095 llvm::sort(C&: CurFeats);
12096
12097 if (CurFeats == NewFeats) {
12098 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12099 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12100 NewFD->setInvalidDecl();
12101 return true;
12102 }
12103 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12104 // Default
12105 if (NewFeats.empty())
12106 break;
12107
12108 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
12109 llvm::SmallVector<StringRef, 8> CurFeats;
12110 CurClones->getFeatures(Out&: CurFeats, Index: I);
12111 llvm::sort(C&: CurFeats);
12112
12113 if (CurFeats == NewFeats) {
12114 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12115 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12116 NewFD->setInvalidDecl();
12117 return true;
12118 }
12119 }
12120 }
12121 break;
12122 }
12123 case MultiVersionKind::TargetClones: {
12124 assert(NewClones && "MultiVersionKind does not match attribute type");
12125 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12126 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
12127 !std::equal(first1: CurClones->featuresStrs_begin(),
12128 last1: CurClones->featuresStrs_end(),
12129 first2: NewClones->featuresStrs_begin())) {
12130 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
12131 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12132 NewFD->setInvalidDecl();
12133 return true;
12134 }
12135 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12136 llvm::SmallVector<StringRef, 8> CurFeats;
12137 CurTVA->getFeatures(Out&: CurFeats);
12138 llvm::sort(C&: CurFeats);
12139
12140 // Default
12141 if (CurFeats.empty())
12142 break;
12143
12144 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12145 NewFeats.clear();
12146 NewClones->getFeatures(Out&: NewFeats, Index: I);
12147 llvm::sort(C&: NewFeats);
12148
12149 if (CurFeats == NewFeats) {
12150 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
12151 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12152 NewFD->setInvalidDecl();
12153 return true;
12154 }
12155 }
12156 break;
12157 }
12158 Redeclaration = true;
12159 OldDecl = CurFD;
12160 NewFD->setIsMultiVersion();
12161 return false;
12162 }
12163 case MultiVersionKind::CPUSpecific:
12164 case MultiVersionKind::CPUDispatch: {
12165 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12166 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12167 // Handle CPUDispatch/CPUSpecific versions.
12168 // Only 1 CPUDispatch function is allowed, this will make it go through
12169 // the redeclaration errors.
12170 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12171 CurFD->hasAttr<CPUDispatchAttr>()) {
12172 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12173 std::equal(
12174 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
12175 first2: NewCPUDisp->cpus_begin(),
12176 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12177 return Cur->getName() == New->getName();
12178 })) {
12179 NewFD->setIsMultiVersion();
12180 Redeclaration = true;
12181 OldDecl = ND;
12182 return false;
12183 }
12184
12185 // If the declarations don't match, this is an error condition.
12186 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
12187 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12188 NewFD->setInvalidDecl();
12189 return true;
12190 }
12191 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12192 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12193 std::equal(
12194 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
12195 first2: NewCPUSpec->cpus_begin(),
12196 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12197 return Cur->getName() == New->getName();
12198 })) {
12199 NewFD->setIsMultiVersion();
12200 Redeclaration = true;
12201 OldDecl = ND;
12202 return false;
12203 }
12204
12205 // Only 1 version of CPUSpecific is allowed for each CPU.
12206 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12207 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12208 if (CurII == NewII) {
12209 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
12210 << NewII;
12211 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12212 NewFD->setInvalidDecl();
12213 return true;
12214 }
12215 }
12216 }
12217 }
12218 break;
12219 }
12220 }
12221 }
12222
12223 // Redeclarations of a target_clones function may omit the attribute, in which
12224 // case it will be inherited during declaration merging.
12225 if (NewMVKind == MultiVersionKind::None &&
12226 OldMVKind == MultiVersionKind::TargetClones) {
12227 NewFD->setIsMultiVersion();
12228 Redeclaration = true;
12229 OldDecl = OldFD;
12230 return false;
12231 }
12232
12233 // Else, this is simply a non-redecl case. Checking the 'value' is only
12234 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12235 // handled in the attribute adding step.
12236 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
12237 NewFD->setInvalidDecl();
12238 return true;
12239 }
12240
12241 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12242 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
12243 NewFD->setInvalidDecl();
12244 return true;
12245 }
12246
12247 // Permit forward declarations in the case where these two are compatible.
12248 if (!OldFD->isMultiVersion()) {
12249 OldFD->setIsMultiVersion();
12250 NewFD->setIsMultiVersion();
12251 Redeclaration = true;
12252 OldDecl = OldFD;
12253 return false;
12254 }
12255
12256 NewFD->setIsMultiVersion();
12257 Redeclaration = false;
12258 OldDecl = nullptr;
12259 Previous.clear();
12260 return false;
12261}
12262
12263/// Check the validity of a mulitversion function declaration.
12264/// Also sets the multiversion'ness' of the function itself.
12265///
12266/// This sets NewFD->isInvalidDecl() to true if there was an error.
12267///
12268/// Returns true if there was an error, false otherwise.
12269static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12270 bool &Redeclaration, NamedDecl *&OldDecl,
12271 LookupResult &Previous) {
12272 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12273
12274 // Check if FMV is disabled.
12275 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
12276 return false;
12277
12278 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12279 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12280 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12281 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12282 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12283 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12284
12285 // Main isn't allowed to become a multiversion function, however it IS
12286 // permitted to have 'main' be marked with the 'target' optimization hint,
12287 // for 'target_version' only default is allowed.
12288 if (NewFD->isMain()) {
12289 if (MVKind != MultiVersionKind::None &&
12290 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12291 !(MVKind == MultiVersionKind::TargetVersion &&
12292 NewTVA->isDefaultVersion())) {
12293 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
12294 NewFD->setInvalidDecl();
12295 return true;
12296 }
12297 return false;
12298 }
12299
12300 // Target attribute on AArch64 is not used for multiversioning
12301 if (NewTA && TI.getTriple().isAArch64())
12302 return false;
12303
12304 // Target attribute on RISCV is not used for multiversioning
12305 if (NewTA && TI.getTriple().isRISCV())
12306 return false;
12307
12308 if (!OldDecl || !OldDecl->getAsFunction() ||
12309 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12310 DC: NewFD->getDeclContext()->getRedeclContext())) {
12311 // If there's no previous declaration, AND this isn't attempting to cause
12312 // multiversioning, this isn't an error condition.
12313 if (MVKind == MultiVersionKind::None)
12314 return false;
12315 return CheckMultiVersionFirstFunction(S, FD: NewFD);
12316 }
12317
12318 FunctionDecl *OldFD = OldDecl->getAsFunction();
12319
12320 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12321 return false;
12322
12323 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12324 // for target_clones and target_version.
12325 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12326 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12327 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12328 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12329 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12330 NewFD->setInvalidDecl();
12331 return true;
12332 }
12333
12334 if (!OldFD->isMultiVersion()) {
12335 switch (MVKind) {
12336 case MultiVersionKind::Target:
12337 case MultiVersionKind::TargetVersion:
12338 return CheckDeclarationCausesMultiVersioning(
12339 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12340 case MultiVersionKind::TargetClones:
12341 if (OldFD->isUsed(CheckUsedAttr: false)) {
12342 NewFD->setInvalidDecl();
12343 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
12344 }
12345 OldFD->setIsMultiVersion();
12346 break;
12347
12348 case MultiVersionKind::CPUDispatch:
12349 case MultiVersionKind::CPUSpecific:
12350 case MultiVersionKind::None:
12351 break;
12352 }
12353 }
12354
12355 // At this point, we have a multiversion function decl (in OldFD) AND an
12356 // appropriate attribute in the current function decl (unless it's allowed to
12357 // omit the attribute). Resolve that these are still compatible with previous
12358 // declarations.
12359 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12360 NewCPUSpec, NewClones, Redeclaration,
12361 OldDecl, Previous);
12362}
12363
12364static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12365 bool IsPure = NewFD->hasAttr<PureAttr>();
12366 bool IsConst = NewFD->hasAttr<ConstAttr>();
12367
12368 // If there are no pure or const attributes, there's nothing to check.
12369 if (!IsPure && !IsConst)
12370 return;
12371
12372 // If the function is marked both pure and const, we retain the const
12373 // attribute because it makes stronger guarantees than the pure attribute, and
12374 // we drop the pure attribute explicitly to prevent later confusion about
12375 // semantics.
12376 if (IsPure && IsConst) {
12377 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12378 NewFD->dropAttrs<PureAttr>();
12379 }
12380
12381 // Constructors and destructors are functions which return void, so are
12382 // handled here as well.
12383 if (NewFD->getReturnType()->isVoidType()) {
12384 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12385 << IsConst;
12386 NewFD->dropAttrs<PureAttr, ConstAttr>();
12387 }
12388}
12389
12390bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12391 LookupResult &Previous,
12392 bool IsMemberSpecialization,
12393 bool DeclIsDefn) {
12394 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12395 "Variably modified return types are not handled here");
12396
12397 // Determine whether the type of this function should be merged with
12398 // a previous visible declaration. This never happens for functions in C++,
12399 // and always happens in C if the previous declaration was visible.
12400 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12401 !Previous.isShadowed();
12402
12403 bool Redeclaration = false;
12404 NamedDecl *OldDecl = nullptr;
12405 bool MayNeedOverloadableChecks = false;
12406
12407 inferLifetimeCaptureByAttribute(FD: NewFD);
12408 // Merge or overload the declaration with an existing declaration of
12409 // the same name, if appropriate.
12410 if (!Previous.empty()) {
12411 // Determine whether NewFD is an overload of PrevDecl or
12412 // a declaration that requires merging. If it's an overload,
12413 // there's no more work to do here; we'll just add the new
12414 // function to the scope.
12415 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12416 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12417 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12418 Redeclaration = true;
12419 OldDecl = Candidate;
12420 }
12421 } else {
12422 MayNeedOverloadableChecks = true;
12423 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12424 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12425 case OverloadKind::Match:
12426 Redeclaration = true;
12427 break;
12428
12429 case OverloadKind::NonFunction:
12430 Redeclaration = true;
12431 break;
12432
12433 case OverloadKind::Overload:
12434 Redeclaration = false;
12435 break;
12436 }
12437 }
12438 }
12439
12440 // Check for a previous extern "C" declaration with this name.
12441 if (!Redeclaration &&
12442 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12443 if (!Previous.empty()) {
12444 // This is an extern "C" declaration with the same name as a previous
12445 // declaration, and thus redeclares that entity...
12446 Redeclaration = true;
12447 OldDecl = Previous.getFoundDecl();
12448 MergeTypeWithPrevious = false;
12449
12450 // ... except in the presence of __attribute__((overloadable)).
12451 if (OldDecl->hasAttr<OverloadableAttr>() ||
12452 NewFD->hasAttr<OverloadableAttr>()) {
12453 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12454 MayNeedOverloadableChecks = true;
12455 Redeclaration = false;
12456 OldDecl = nullptr;
12457 }
12458 }
12459 }
12460 }
12461
12462 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12463 return Redeclaration;
12464
12465 // PPC MMA non-pointer types are not allowed as function return types.
12466 if (Context.getTargetInfo().getTriple().isPPC64() &&
12467 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12468 NewFD->setInvalidDecl();
12469 }
12470
12471 CheckConstPureAttributesUsage(S&: *this, NewFD);
12472
12473 // C++ [dcl.spec.auto.general]p12:
12474 // Return type deduction for a templated function with a placeholder in its
12475 // declared type occurs when the definition is instantiated even if the
12476 // function body contains a return statement with a non-type-dependent
12477 // operand.
12478 //
12479 // C++ [temp.dep.expr]p3:
12480 // An id-expression is type-dependent if it is a template-id that is not a
12481 // concept-id and is dependent; or if its terminal name is:
12482 // - [...]
12483 // - associated by name lookup with one or more declarations of member
12484 // functions of a class that is the current instantiation declared with a
12485 // return type that contains a placeholder type,
12486 // - [...]
12487 //
12488 // If this is a templated function with a placeholder in its return type,
12489 // make the placeholder type dependent since it won't be deduced until the
12490 // definition is instantiated. We do this here because it needs to happen
12491 // for implicitly instantiated member functions/member function templates.
12492 if (getLangOpts().CPlusPlus14 &&
12493 (NewFD->isDependentContext() &&
12494 NewFD->getReturnType()->isUndeducedType())) {
12495 const FunctionProtoType *FPT =
12496 NewFD->getType()->castAs<FunctionProtoType>();
12497 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12498 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12499 EPI: FPT->getExtProtoInfo()));
12500 }
12501
12502 // C++11 [dcl.constexpr]p8:
12503 // A constexpr specifier for a non-static member function that is not
12504 // a constructor declares that member function to be const.
12505 //
12506 // This needs to be delayed until we know whether this is an out-of-line
12507 // definition of a static member function.
12508 //
12509 // This rule is not present in C++1y, so we produce a backwards
12510 // compatibility warning whenever it happens in C++11.
12511 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12512 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12513 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12514 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12515 CXXMethodDecl *OldMD = nullptr;
12516 if (OldDecl)
12517 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12518 if (!OldMD || !OldMD->isStatic()) {
12519 const FunctionProtoType *FPT =
12520 MD->getType()->castAs<FunctionProtoType>();
12521 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12522 EPI.TypeQuals.addConst();
12523 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12524 Args: FPT->getParamTypes(), EPI));
12525
12526 // Warn that we did this, if we're not performing template instantiation.
12527 // In that case, we'll have warned already when the template was defined.
12528 if (!inTemplateInstantiation()) {
12529 SourceLocation AddConstLoc;
12530 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12531 .IgnoreParens().getAs<FunctionTypeLoc>())
12532 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12533
12534 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12535 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12536 }
12537 }
12538 }
12539
12540 if (Redeclaration) {
12541 // NewFD and OldDecl represent declarations that need to be
12542 // merged.
12543 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12544 NewDeclIsDefn: DeclIsDefn)) {
12545 NewFD->setInvalidDecl();
12546 return Redeclaration;
12547 }
12548
12549 Previous.clear();
12550 Previous.addDecl(D: OldDecl);
12551
12552 if (FunctionTemplateDecl *OldTemplateDecl =
12553 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12554 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12555 FunctionTemplateDecl *NewTemplateDecl
12556 = NewFD->getDescribedFunctionTemplate();
12557 assert(NewTemplateDecl && "Template/non-template mismatch");
12558
12559 // The call to MergeFunctionDecl above may have created some state in
12560 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12561 // can add it as a redeclaration.
12562 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12563
12564 NewFD->setPreviousDeclaration(OldFD);
12565 if (NewFD->isCXXClassMember()) {
12566 NewFD->setAccess(OldTemplateDecl->getAccess());
12567 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12568 }
12569
12570 // If this is an explicit specialization of a member that is a function
12571 // template, mark it as a member specialization.
12572 if (IsMemberSpecialization &&
12573 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12574 NewTemplateDecl->setMemberSpecialization();
12575 assert(OldTemplateDecl->isMemberSpecialization());
12576 // Explicit specializations of a member template do not inherit deleted
12577 // status from the parent member template that they are specializing.
12578 if (OldFD->isDeleted()) {
12579 // FIXME: This assert will not hold in the presence of modules.
12580 assert(OldFD->getCanonicalDecl() == OldFD);
12581 // FIXME: We need an update record for this AST mutation.
12582 OldFD->setDeletedAsWritten(D: false);
12583 }
12584 }
12585
12586 } else {
12587 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12588 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12589 // This needs to happen first so that 'inline' propagates.
12590 NewFD->setPreviousDeclaration(OldFD);
12591 if (NewFD->isCXXClassMember())
12592 NewFD->setAccess(OldFD->getAccess());
12593 }
12594 }
12595 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12596 !NewFD->getAttr<OverloadableAttr>()) {
12597 assert((Previous.empty() ||
12598 llvm::any_of(Previous,
12599 [](const NamedDecl *ND) {
12600 return ND->hasAttr<OverloadableAttr>();
12601 })) &&
12602 "Non-redecls shouldn't happen without overloadable present");
12603
12604 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12605 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12606 return FD && !FD->hasAttr<OverloadableAttr>();
12607 });
12608
12609 if (OtherUnmarkedIter != Previous.end()) {
12610 Diag(Loc: NewFD->getLocation(),
12611 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12612 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12613 DiagID: diag::note_attribute_overloadable_prev_overload)
12614 << false;
12615
12616 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12617 }
12618 }
12619
12620 if (LangOpts.OpenMP)
12621 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12622
12623 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12624 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12625
12626 if (NewFD->hasAttr<SYCLExternalAttr>())
12627 SYCL().CheckSYCLExternalFunctionDecl(FD: NewFD);
12628
12629 // Semantic checking for this function declaration (in isolation).
12630
12631 if (getLangOpts().CPlusPlus) {
12632 // C++-specific checks.
12633 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12634 CheckConstructor(Constructor);
12635 } else if (CXXDestructorDecl *Destructor =
12636 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12637 // We check here for invalid destructor names.
12638 // If we have a friend destructor declaration that is dependent, we can't
12639 // diagnose right away because cases like this are still valid:
12640 // template <class T> struct A { friend T::X::~Y(); };
12641 // struct B { struct Y { ~Y(); }; using X = Y; };
12642 // template struct A<B>;
12643 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12644 (!Destructor->getFunctionObjectParameterType()->isDependentType() &&
12645 !Destructor->getDeclName().isDependentName())) {
12646 CanQualType ClassType =
12647 Context.getCanonicalTagType(TD: Destructor->getParent());
12648
12649 DeclarationName Name =
12650 Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
12651 if (NewFD->getDeclName() != Name) {
12652 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12653 NewFD->setInvalidDecl();
12654 return Redeclaration;
12655 }
12656 }
12657 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12658 if (auto *TD = Guide->getDescribedFunctionTemplate())
12659 CheckDeductionGuideTemplate(TD);
12660
12661 // A deduction guide is not on the list of entities that can be
12662 // explicitly specialized.
12663 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12664 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12665 << /*explicit specialization*/ 1;
12666 }
12667
12668 // Find any virtual functions that this function overrides.
12669 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12670 if (!Method->isFunctionTemplateSpecialization() &&
12671 !Method->getDescribedFunctionTemplate() &&
12672 Method->isCanonicalDecl()) {
12673 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12674 }
12675 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12676 // C++2a [class.virtual]p6
12677 // A virtual method shall not have a requires-clause.
12678 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12679 DiagID: diag::err_constrained_virtual_method);
12680
12681 if (Method->isStatic())
12682 checkThisInStaticMemberFunctionType(Method);
12683 }
12684
12685 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12686 ActOnConversionDeclarator(Conversion);
12687
12688 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12689 if (NewFD->isOverloadedOperator() &&
12690 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12691 NewFD->setInvalidDecl();
12692 return Redeclaration;
12693 }
12694
12695 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12696 if (NewFD->getLiteralIdentifier() &&
12697 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12698 NewFD->setInvalidDecl();
12699 return Redeclaration;
12700 }
12701
12702 // In C++, check default arguments now that we have merged decls. Unless
12703 // the lexical context is the class, because in this case this is done
12704 // during delayed parsing anyway.
12705 if (!CurContext->isRecord())
12706 CheckCXXDefaultArguments(FD: NewFD);
12707
12708 // If this function is declared as being extern "C", then check to see if
12709 // the function returns a UDT (class, struct, or union type) that is not C
12710 // compatible, and if it does, warn the user.
12711 // But, issue any diagnostic on the first declaration only.
12712 if (Previous.empty() && NewFD->isExternC()) {
12713 QualType R = NewFD->getReturnType();
12714 if (R->isIncompleteType() && !R->isVoidType())
12715 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12716 << NewFD << R;
12717 else if (!R.isPODType(Context) && !R->isVoidType() &&
12718 !R->isObjCObjectPointerType())
12719 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12720 }
12721
12722 // C++1z [dcl.fct]p6:
12723 // [...] whether the function has a non-throwing exception-specification
12724 // [is] part of the function type
12725 //
12726 // This results in an ABI break between C++14 and C++17 for functions whose
12727 // declared type includes an exception-specification in a parameter or
12728 // return type. (Exception specifications on the function itself are OK in
12729 // most cases, and exception specifications are not permitted in most other
12730 // contexts where they could make it into a mangling.)
12731 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12732 auto HasNoexcept = [&](QualType T) -> bool {
12733 // Strip off declarator chunks that could be between us and a function
12734 // type. We don't need to look far, exception specifications are very
12735 // restricted prior to C++17.
12736 if (auto *RT = T->getAs<ReferenceType>())
12737 T = RT->getPointeeType();
12738 else if (T->isAnyPointerType())
12739 T = T->getPointeeType();
12740 else if (auto *MPT = T->getAs<MemberPointerType>())
12741 T = MPT->getPointeeType();
12742 if (auto *FPT = T->getAs<FunctionProtoType>())
12743 if (FPT->isNothrow())
12744 return true;
12745 return false;
12746 };
12747
12748 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12749 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12750 for (QualType T : FPT->param_types())
12751 AnyNoexcept |= HasNoexcept(T);
12752 if (AnyNoexcept)
12753 Diag(Loc: NewFD->getLocation(),
12754 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12755 << NewFD;
12756 }
12757
12758 if (!Redeclaration && LangOpts.CUDA) {
12759 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12760 for (auto *Parm : NewFD->parameters()) {
12761 if (!Parm->getType()->isDependentType() &&
12762 Parm->hasAttr<CUDAGridConstantAttr>() &&
12763 !(IsKernel && Parm->getType().isConstQualified()))
12764 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12765 DiagID: diag::err_cuda_grid_constant_not_allowed);
12766 }
12767 CUDA().checkTargetOverload(NewFD, Previous);
12768 }
12769 }
12770
12771 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12772 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12773
12774 return Redeclaration;
12775}
12776
12777void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12778 // [basic.start.main]p3
12779 // The main function shall not be declared with C linkage-specification.
12780 if (FD->isExternCContext())
12781 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12782
12783 // C++11 [basic.start.main]p3:
12784 // A program that [...] declares main to be inline, static or
12785 // constexpr is ill-formed.
12786 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12787 // appear in a declaration of main.
12788 // static main is not an error under C99, but we should warn about it.
12789 // We accept _Noreturn main as an extension.
12790 if (FD->getStorageClass() == SC_Static)
12791 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12792 ? diag::err_static_main : diag::warn_static_main)
12793 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12794 if (FD->isInlineSpecified())
12795 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12796 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12797 if (DS.isNoreturnSpecified()) {
12798 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12799 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12800 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12801 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12802 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12803 }
12804 if (FD->isConstexpr()) {
12805 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12806 << FD->isConsteval()
12807 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12808 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12809 }
12810
12811 if (getLangOpts().OpenCL) {
12812 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12813 << FD->hasAttr<DeviceKernelAttr>();
12814 FD->setInvalidDecl();
12815 return;
12816 }
12817
12818 if (FD->hasAttr<SYCLExternalAttr>()) {
12819 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_external_invalid_main)
12820 << FD->getAttr<SYCLExternalAttr>();
12821 FD->setInvalidDecl();
12822 return;
12823 }
12824
12825 // Functions named main in hlsl are default entries, but don't have specific
12826 // signatures they are required to conform to.
12827 if (getLangOpts().HLSL)
12828 return;
12829
12830 QualType T = FD->getType();
12831 assert(T->isFunctionType() && "function decl is not of function type");
12832 const FunctionType* FT = T->castAs<FunctionType>();
12833
12834 // Set default calling convention for main()
12835 if (FT->getCallConv() != CC_C) {
12836 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12837 FD->setType(QualType(FT, 0));
12838 T = Context.getCanonicalType(T: FD->getType());
12839 }
12840
12841 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12842 // In C with GNU extensions we allow main() to have non-integer return
12843 // type, but we should warn about the extension, and we disable the
12844 // implicit-return-zero rule.
12845
12846 // GCC in C mode accepts qualified 'int'.
12847 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12848 FD->setHasImplicitReturnZero(true);
12849 else {
12850 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12851 SourceRange RTRange = FD->getReturnTypeSourceRange();
12852 if (RTRange.isValid())
12853 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12854 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12855 }
12856 } else {
12857 // In C and C++, main magically returns 0 if you fall off the end;
12858 // set the flag which tells us that.
12859 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12860
12861 // All the standards say that main() should return 'int'.
12862 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12863 FD->setHasImplicitReturnZero(true);
12864 else {
12865 // Otherwise, this is just a flat-out error.
12866 SourceRange RTRange = FD->getReturnTypeSourceRange();
12867 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12868 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12869 : FixItHint());
12870 FD->setInvalidDecl(true);
12871 }
12872
12873 // [basic.start.main]p3:
12874 // A program that declares a function main that belongs to the global scope
12875 // and is attached to a named module is ill-formed.
12876 if (FD->isInNamedModule()) {
12877 const SourceLocation start = FD->getTypeSpecStartLoc();
12878 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12879 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12880 }
12881 }
12882
12883 // Treat protoless main() as nullary.
12884 if (isa<FunctionNoProtoType>(Val: FT)) return;
12885
12886 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12887 unsigned nparams = FTP->getNumParams();
12888 assert(FD->getNumParams() == nparams);
12889
12890 bool HasExtraParameters = (nparams > 3);
12891
12892 if (FTP->isVariadic()) {
12893 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12894 // FIXME: if we had information about the location of the ellipsis, we
12895 // could add a FixIt hint to remove it as a parameter.
12896 }
12897
12898 // Darwin passes an undocumented fourth argument of type char**. If
12899 // other platforms start sprouting these, the logic below will start
12900 // getting shifty.
12901 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12902 HasExtraParameters = false;
12903
12904 if (HasExtraParameters) {
12905 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12906 FD->setInvalidDecl(true);
12907 nparams = 3;
12908 }
12909
12910 // FIXME: a lot of the following diagnostics would be improved
12911 // if we had some location information about types.
12912
12913 QualType CharPP =
12914 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12915 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12916
12917 for (unsigned i = 0; i < nparams; ++i) {
12918 QualType AT = FTP->getParamType(i);
12919
12920 bool mismatch = true;
12921
12922 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12923 mismatch = false;
12924 else if (Expected[i] == CharPP) {
12925 // As an extension, the following forms are okay:
12926 // char const **
12927 // char const * const *
12928 // char * const *
12929
12930 QualifierCollector qs;
12931 const PointerType* PT;
12932 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12933 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12934 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
12935 T2: Context.CharTy)) {
12936 qs.removeConst();
12937 mismatch = !qs.empty();
12938 }
12939 }
12940
12941 if (mismatch) {
12942 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
12943 // TODO: suggest replacing given type with expected type
12944 FD->setInvalidDecl(true);
12945 }
12946 }
12947
12948 if (nparams == 1 && !FD->isInvalidDecl()) {
12949 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
12950 }
12951
12952 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12953 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12954 FD->setInvalidDecl();
12955 }
12956}
12957
12958static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12959
12960 // Default calling convention for main and wmain is __cdecl
12961 if (FD->getName() == "main" || FD->getName() == "wmain")
12962 return false;
12963
12964 // Default calling convention for MinGW and Cygwin is __cdecl
12965 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12966 if (T.isOSCygMing())
12967 return false;
12968
12969 // Default calling convention for WinMain, wWinMain and DllMain
12970 // is __stdcall on 32 bit Windows
12971 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12972 return true;
12973
12974 return false;
12975}
12976
12977void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12978 QualType T = FD->getType();
12979 assert(T->isFunctionType() && "function decl is not of function type");
12980 const FunctionType *FT = T->castAs<FunctionType>();
12981
12982 // Set an implicit return of 'zero' if the function can return some integral,
12983 // enumeration, pointer or nullptr type.
12984 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12985 FT->getReturnType()->isAnyPointerType() ||
12986 FT->getReturnType()->isNullPtrType())
12987 // DllMain is exempt because a return value of zero means it failed.
12988 if (FD->getName() != "DllMain")
12989 FD->setHasImplicitReturnZero(true);
12990
12991 // Explicitly specified calling conventions are applied to MSVC entry points
12992 if (!hasExplicitCallingConv(T)) {
12993 if (isDefaultStdCall(FD, S&: *this)) {
12994 if (FT->getCallConv() != CC_X86StdCall) {
12995 FT = Context.adjustFunctionType(
12996 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12997 FD->setType(QualType(FT, 0));
12998 }
12999 } else if (FT->getCallConv() != CC_C) {
13000 FT = Context.adjustFunctionType(Fn: FT,
13001 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
13002 FD->setType(QualType(FT, 0));
13003 }
13004 }
13005
13006 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13007 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
13008 FD->setInvalidDecl();
13009 }
13010}
13011
13012bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
13013 // FIXME: Need strict checking. In C89, we need to check for
13014 // any assignment, increment, decrement, function-calls, or
13015 // commas outside of a sizeof. In C99, it's the same list,
13016 // except that the aforementioned are allowed in unevaluated
13017 // expressions. Everything else falls under the
13018 // "may accept other forms of constant expressions" exception.
13019 //
13020 // Regular C++ code will not end up here (exceptions: language extensions,
13021 // OpenCL C++ etc), so the constant expression rules there don't matter.
13022 if (Init->isValueDependent()) {
13023 assert(Init->containsErrors() &&
13024 "Dependent code should only occur in error-recovery path.");
13025 return true;
13026 }
13027 const Expr *Culprit;
13028 if (Init->isConstantInitializer(Ctx&: Context, /*ForRef=*/false, Culprit: &Culprit))
13029 return false;
13030
13031 // The culprit reported by isConstantInitializer() may be wrapped in implicit
13032 // casts and parentheses that it does not look through: under ARC an
13033 // object-pointer initializer is an `ImplicitCastExpr
13034 // <ARCReclaimReturnedObject>`, an `id`-typed (or otherwise differently-typed)
13035 // variable adds an `ImplicitCastExpr <BitCast>` on top, and a parenthesized
13036 // initializer such as `(@{...})` adds a `ParenExpr`. Strip all of these so
13037 // the ObjC-specific classification and per-element reporting below can see
13038 // the underlying literal regardless of how it is wrapped.
13039 const Expr *CulpritLiteral = Culprit->IgnoreParenImpCasts();
13040
13041 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
13042 if (getLangOpts().ObjCConstantLiterals &&
13043 isa<ObjCObjectLiteral>(Val: CulpritLiteral)) {
13044
13045 // For collection literals, iterate the elements to point at the specific
13046 // offender. These per-element checks mirror the constant-initializer rules
13047 // applied when the literal was built (see SemaObjC::BuildObjCArrayLiteral
13048 // and SemaObjC::BuildObjCDictionaryLiteral): each element must itself be a
13049 // constant object literal, and dictionary keys must additionally be string
13050 // literals. Elements, keys and values are wrapped in an implicit BitCast to
13051 // `id`, so the isa<> classification is done on the unwrapped expression.
13052 if (const auto *ALE = dyn_cast<ObjCArrayLiteral>(Val: CulpritLiteral)) {
13053 for (const Expr *Elm : ALE->elements()) {
13054 if (!isa<ObjCObjectLiteral>(Val: Elm->IgnoreImpCasts()) ||
13055 !Elm->isConstantInitializer(Ctx&: Context)) {
13056 Diag(Loc: Elm->getExprLoc(),
13057 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13058 << ObjC().CheckLiteralKind(FromE: Init) << Elm->getSourceRange();
13059 return true;
13060 }
13061 }
13062 }
13063
13064 if (const auto *DLE = dyn_cast<ObjCDictionaryLiteral>(Val: CulpritLiteral)) {
13065 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
13066 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(Index: I);
13067
13068 // Keys must be constant string literals.
13069 if (!isa<ObjCStringLiteral>(Val: Elm.Key->IgnoreImpCasts()) ||
13070 !Elm.Key->isConstantInitializer(Ctx&: Context)) {
13071 Diag(Loc: Elm.Key->getExprLoc(),
13072 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13073 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Key->getSourceRange();
13074 return true;
13075 }
13076
13077 // Values must be constant object literals.
13078 if (!isa<ObjCObjectLiteral>(Val: Elm.Value->IgnoreImpCasts()) ||
13079 !Elm.Value->isConstantInitializer(Ctx&: Context)) {
13080 Diag(Loc: Elm.Value->getExprLoc(),
13081 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13082 << ObjC().CheckLiteralKind(FromE: Init) << Elm.Value->getSourceRange();
13083 return true;
13084 }
13085 }
13086 }
13087
13088 Diag(Loc: CulpritLiteral->getExprLoc(),
13089 DiagID: diag::err_objc_literal_nonconstant_at_file_scope)
13090 << ObjC().CheckLiteralKind(FromE: Init) << CulpritLiteral->getSourceRange();
13091 return true;
13092 }
13093
13094 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
13095 return true;
13096}
13097
13098namespace {
13099 // Visits an initialization expression to see if OrigDecl is evaluated in
13100 // its own initialization and throws a warning if it does.
13101 class SelfReferenceChecker
13102 : public EvaluatedExprVisitor<SelfReferenceChecker> {
13103 Sema &S;
13104 Decl *OrigDecl;
13105 bool isRecordType;
13106 bool isPODType;
13107 bool isReferenceType;
13108 bool isInCXXOperatorCall;
13109
13110 bool isInitList;
13111 llvm::SmallVector<unsigned, 4> InitFieldIndex;
13112
13113 public:
13114 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
13115
13116 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
13117 S(S), OrigDecl(OrigDecl) {
13118 isPODType = false;
13119 isRecordType = false;
13120 isReferenceType = false;
13121 isInCXXOperatorCall = false;
13122 isInitList = false;
13123 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
13124 isPODType = VD->getType().isPODType(Context: S.Context);
13125 isRecordType = VD->getType()->isRecordType();
13126 isReferenceType = VD->getType()->isReferenceType();
13127 }
13128 }
13129
13130 // For most expressions, just call the visitor. For initializer lists,
13131 // track the index of the field being initialized since fields are
13132 // initialized in order allowing use of previously initialized fields.
13133 void CheckExpr(Expr *E) {
13134 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
13135 if (!InitList) {
13136 Visit(S: E);
13137 return;
13138 }
13139
13140 // Track and increment the index here.
13141 isInitList = true;
13142 InitFieldIndex.push_back(Elt: 0);
13143 for (auto *Child : InitList->children()) {
13144 CheckExpr(E: cast<Expr>(Val: Child));
13145 ++InitFieldIndex.back();
13146 }
13147 InitFieldIndex.pop_back();
13148 }
13149
13150 // Returns true if MemberExpr is checked and no further checking is needed.
13151 // Returns false if additional checking is required.
13152 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
13153 llvm::SmallVector<FieldDecl*, 4> Fields;
13154 Expr *Base = E;
13155 bool ReferenceField = false;
13156
13157 // Get the field members used.
13158 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13159 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
13160 if (!FD)
13161 return false;
13162 Fields.push_back(Elt: FD);
13163 if (FD->getType()->isReferenceType())
13164 ReferenceField = true;
13165 Base = ME->getBase()->IgnoreParenImpCasts();
13166 }
13167
13168 // Keep checking only if the base Decl is the same.
13169 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
13170 if (!DRE || DRE->getDecl() != OrigDecl)
13171 return false;
13172
13173 // A reference field can be bound to an unininitialized field.
13174 if (CheckReference && !ReferenceField)
13175 return true;
13176
13177 // Convert FieldDecls to their index number.
13178 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13179 for (const FieldDecl *I : llvm::reverse(C&: Fields))
13180 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
13181
13182 // See if a warning is needed by checking the first difference in index
13183 // numbers. If field being used has index less than the field being
13184 // initialized, then the use is safe.
13185 for (auto UsedIter = UsedFieldIndex.begin(),
13186 UsedEnd = UsedFieldIndex.end(),
13187 OrigIter = InitFieldIndex.begin(),
13188 OrigEnd = InitFieldIndex.end();
13189 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13190 if (*UsedIter < *OrigIter)
13191 return true;
13192 if (*UsedIter > *OrigIter)
13193 break;
13194 }
13195
13196 // TODO: Add a different warning which will print the field names.
13197 HandleDeclRefExpr(DRE);
13198 return true;
13199 }
13200
13201 // For most expressions, the cast is directly above the DeclRefExpr.
13202 // For conditional operators, the cast can be outside the conditional
13203 // operator if both expressions are DeclRefExpr's.
13204 void HandleValue(Expr *E) {
13205 E = E->IgnoreParens();
13206 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13207 HandleDeclRefExpr(DRE);
13208 return;
13209 }
13210
13211 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13212 Visit(S: CO->getCond());
13213 HandleValue(E: CO->getTrueExpr());
13214 HandleValue(E: CO->getFalseExpr());
13215 return;
13216 }
13217
13218 if (BinaryConditionalOperator *BCO =
13219 dyn_cast<BinaryConditionalOperator>(Val: E)) {
13220 Visit(S: BCO->getCond());
13221 HandleValue(E: BCO->getFalseExpr());
13222 return;
13223 }
13224
13225 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
13226 if (Expr *SE = OVE->getSourceExpr())
13227 HandleValue(E: SE);
13228 return;
13229 }
13230
13231 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13232 if (BO->getOpcode() == BO_Comma) {
13233 Visit(S: BO->getLHS());
13234 HandleValue(E: BO->getRHS());
13235 return;
13236 }
13237 }
13238
13239 if (isa<MemberExpr>(Val: E)) {
13240 if (isInitList) {
13241 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
13242 CheckReference: false /*CheckReference*/))
13243 return;
13244 }
13245
13246 Expr *Base = E->IgnoreParenImpCasts();
13247 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13248 // Check for static member variables and don't warn on them.
13249 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13250 return;
13251 Base = ME->getBase()->IgnoreParenImpCasts();
13252 }
13253 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
13254 HandleDeclRefExpr(DRE);
13255 return;
13256 }
13257
13258 Visit(S: E);
13259 }
13260
13261 // Reference types not handled in HandleValue are handled here since all
13262 // uses of references are bad, not just r-value uses.
13263 void VisitDeclRefExpr(DeclRefExpr *E) {
13264 if (isReferenceType)
13265 HandleDeclRefExpr(DRE: E);
13266 }
13267
13268 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13269 if (E->getCastKind() == CK_LValueToRValue) {
13270 HandleValue(E: E->getSubExpr());
13271 return;
13272 }
13273
13274 Inherited::VisitImplicitCastExpr(S: E);
13275 }
13276
13277 void VisitMemberExpr(MemberExpr *E) {
13278 if (isInitList) {
13279 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
13280 return;
13281 }
13282
13283 // Don't warn on arrays since they can be treated as pointers.
13284 if (E->getType()->canDecayToPointerType()) return;
13285
13286 // Warn when a non-static method call is followed by non-static member
13287 // field accesses, which is followed by a DeclRefExpr.
13288 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
13289 bool Warn = (MD && !MD->isStatic());
13290 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13291 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13292 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13293 Warn = false;
13294 Base = ME->getBase()->IgnoreParenImpCasts();
13295 }
13296
13297 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
13298 if (Warn)
13299 HandleDeclRefExpr(DRE);
13300 return;
13301 }
13302
13303 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13304 // Visit that expression.
13305 Visit(S: Base);
13306 }
13307
13308 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13309 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13310 Expr *Callee = E->getCallee();
13311
13312 if (isa<UnresolvedLookupExpr>(Val: Callee))
13313 return Inherited::VisitCXXOperatorCallExpr(S: E);
13314
13315 Visit(S: Callee);
13316 for (auto Arg: E->arguments())
13317 HandleValue(E: Arg->IgnoreParenImpCasts());
13318 }
13319
13320 void VisitLambdaExpr(LambdaExpr *E) {
13321 if (!isInCXXOperatorCall) {
13322 Inherited::VisitLambdaExpr(LE: E);
13323 return;
13324 }
13325
13326 for (Expr *Init : E->capture_inits())
13327 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
13328 HandleDeclRefExpr(DRE);
13329 else if (Init)
13330 Visit(S: Init);
13331 }
13332
13333 void VisitUnaryOperator(UnaryOperator *E) {
13334 // For POD record types, addresses of its own members are well-defined.
13335 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13336 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
13337 if (!isPODType)
13338 HandleValue(E: E->getSubExpr());
13339 return;
13340 }
13341
13342 if (E->isIncrementDecrementOp()) {
13343 HandleValue(E: E->getSubExpr());
13344 return;
13345 }
13346
13347 Inherited::VisitUnaryOperator(S: E);
13348 }
13349
13350 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13351
13352 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13353 if (E->getConstructor()->isCopyConstructor()) {
13354 Expr *ArgExpr = E->getArg(Arg: 0);
13355 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
13356 if (ILE->getNumInits() == 1)
13357 ArgExpr = ILE->getInit(Init: 0);
13358 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
13359 if (ICE->getCastKind() == CK_NoOp)
13360 ArgExpr = ICE->getSubExpr();
13361 HandleValue(E: ArgExpr);
13362 return;
13363 }
13364 Inherited::VisitCXXConstructExpr(S: E);
13365 }
13366
13367 void VisitCallExpr(CallExpr *E) {
13368 // Treat std::move as a use.
13369 if (E->isCallToStdMove()) {
13370 HandleValue(E: E->getArg(Arg: 0));
13371 return;
13372 }
13373
13374 Inherited::VisitCallExpr(CE: E);
13375 }
13376
13377 void VisitBinaryOperator(BinaryOperator *E) {
13378 if (E->isCompoundAssignmentOp()) {
13379 HandleValue(E: E->getLHS());
13380 Visit(S: E->getRHS());
13381 return;
13382 }
13383
13384 Inherited::VisitBinaryOperator(S: E);
13385 }
13386
13387 // A custom visitor for BinaryConditionalOperator is needed because the
13388 // regular visitor would check the condition and true expression separately
13389 // but both point to the same place giving duplicate diagnostics.
13390 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13391 Visit(S: E->getCond());
13392 Visit(S: E->getFalseExpr());
13393 }
13394
13395 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13396 Decl* ReferenceDecl = DRE->getDecl();
13397 if (OrigDecl != ReferenceDecl) return;
13398 unsigned diag;
13399 if (isReferenceType) {
13400 diag = diag::warn_uninit_self_reference_in_reference_init;
13401 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
13402 diag = diag::warn_static_self_reference_in_init;
13403 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
13404 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
13405 DRE->getDecl()->getType()->isRecordType()) {
13406 diag = diag::warn_uninit_self_reference_in_init;
13407 } else {
13408 // Local variables will be handled by the CFG analysis.
13409 return;
13410 }
13411
13412 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
13413 PD: S.PDiag(DiagID: diag)
13414 << DRE->getDecl() << OrigDecl->getLocation()
13415 << DRE->getSourceRange());
13416 }
13417 };
13418
13419 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13420 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13421 bool DirectInit) {
13422 // Parameters arguments are occassionially constructed with itself,
13423 // for instance, in recursive functions. Skip them.
13424 if (isa<ParmVarDecl>(Val: OrigDecl))
13425 return;
13426
13427 // Skip checking for file-scope constexpr variables - constant evaluation
13428 // will produce appropriate errors without needing runtime diagnostics.
13429 // Local constexpr should still emit runtime warnings.
13430 if (auto *VD = dyn_cast<VarDecl>(Val: OrigDecl);
13431 VD && VD->isConstexpr() && VD->isFileVarDecl())
13432 return;
13433
13434 E = E->IgnoreParens();
13435
13436 // Skip checking T a = a where T is not a record or reference type.
13437 // Doing so is a way to silence uninitialized warnings.
13438 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13439 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13440 if (ICE->getCastKind() == CK_LValueToRValue)
13441 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
13442 if (DRE->getDecl() == OrigDecl)
13443 return;
13444
13445 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13446 }
13447} // end anonymous namespace
13448
13449namespace {
13450 // Simple wrapper to add the name of a variable or (if no variable is
13451 // available) a DeclarationName into a diagnostic.
13452 struct VarDeclOrName {
13453 VarDecl *VDecl;
13454 DeclarationName Name;
13455
13456 friend const Sema::SemaDiagnosticBuilder &
13457 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13458 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13459 }
13460 };
13461} // end anonymous namespace
13462
13463QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13464 DeclarationName Name, QualType Type,
13465 TypeSourceInfo *TSI,
13466 SourceRange Range, bool DirectInit,
13467 Expr *Init) {
13468 bool IsInitCapture = !VDecl;
13469 assert((!VDecl || !VDecl->isInitCapture()) &&
13470 "init captures are expected to be deduced prior to initialization");
13471
13472 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13473
13474 DeducedType *Deduced = Type->getContainedDeducedType();
13475 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13476
13477 // Diagnose auto array declarations in C23, unless it's a supported extension.
13478 if (getLangOpts().C23 && Type->isArrayType() &&
13479 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13480 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13481 << (int)Deduced->getContainedAutoType()->getKeyword()
13482 << /*in array decl*/ 23 << Range;
13483 return QualType();
13484 }
13485
13486 // C++11 [dcl.spec.auto]p3
13487 if (!Init) {
13488 assert(VDecl && "no init for init capture deduction?");
13489
13490 // Except for class argument deduction, and then for an initializing
13491 // declaration only, i.e. no static at class scope or extern.
13492 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13493 VDecl->hasExternalStorage() ||
13494 VDecl->isStaticDataMember()) {
13495 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13496 << VDecl->getDeclName() << Type;
13497 return QualType();
13498 }
13499 }
13500
13501 ArrayRef<Expr*> DeduceInits;
13502 if (Init)
13503 DeduceInits = Init;
13504
13505 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13506 if (DirectInit && PL)
13507 DeduceInits = PL->exprs();
13508
13509 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13510 assert(VDecl && "non-auto type for init capture deduction?");
13511 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13512 InitializationKind Kind = InitializationKind::CreateForInit(
13513 Loc: VDecl->getLocation(), DirectInit, Init);
13514 // FIXME: Initialization should not be taking a mutable list of inits.
13515 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13516 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13517 Init: InitsCopy);
13518 }
13519
13520 if (DirectInit) {
13521 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13522 DeduceInits = IL->inits();
13523 }
13524
13525 // Deduction only works if we have exactly one source expression.
13526 if (DeduceInits.empty()) {
13527 // It isn't possible to write this directly, but it is possible to
13528 // end up in this situation with "auto x(some_pack...);"
13529 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13530 ? diag::err_init_capture_no_expression
13531 : diag::err_auto_var_init_no_expression)
13532 << VN << Type << Range;
13533 return QualType();
13534 }
13535
13536 if (DeduceInits.size() > 1) {
13537 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13538 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13539 : diag::err_auto_var_init_multiple_expressions)
13540 << VN << Type << Range;
13541 return QualType();
13542 }
13543
13544 Expr *DeduceInit = DeduceInits[0];
13545 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13546 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13547 ? diag::err_init_capture_paren_braces
13548 : diag::err_auto_var_init_paren_braces)
13549 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13550 return QualType();
13551 }
13552
13553 // Expressions default to 'id' when we're in a debugger.
13554 bool DefaultedAnyToId = false;
13555 if (getLangOpts().DebuggerCastResultToId &&
13556 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13557 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13558 if (Result.isInvalid()) {
13559 return QualType();
13560 }
13561 Init = Result.get();
13562 DefaultedAnyToId = true;
13563 }
13564
13565 // C++ [dcl.decomp]p1:
13566 // If the assignment-expression [...] has array type A and no ref-qualifier
13567 // is present, e has type cv A
13568 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13569 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13570 DeduceInit->getType()->isConstantArrayType())
13571 return Context.getQualifiedType(T: DeduceInit->getType(),
13572 Qs: Type.getQualifiers());
13573
13574 QualType DeducedType;
13575 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13576 TemplateDeductionResult Result =
13577 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13578 if (Result != TemplateDeductionResult::Success &&
13579 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13580 if (!IsInitCapture)
13581 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13582 else if (isa<InitListExpr>(Val: Init))
13583 Diag(Loc: Range.getBegin(),
13584 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13585 << VN
13586 << (DeduceInit->getType().isNull() ? TSI->getType()
13587 : DeduceInit->getType())
13588 << DeduceInit->getSourceRange();
13589 else
13590 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13591 << VN << TSI->getType()
13592 << (DeduceInit->getType().isNull() ? TSI->getType()
13593 : DeduceInit->getType())
13594 << DeduceInit->getSourceRange();
13595 }
13596
13597 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13598 // 'id' instead of a specific object type prevents most of our usual
13599 // checks.
13600 // We only want to warn outside of template instantiations, though:
13601 // inside a template, the 'id' could have come from a parameter.
13602 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13603 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13604 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13605 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13606 }
13607
13608 return DeducedType;
13609}
13610
13611bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13612 Expr *Init) {
13613 assert(!Init || !Init->containsErrors());
13614 QualType DeducedType = deduceVarTypeFromInitializer(
13615 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13616 Range: VDecl->getSourceRange(), DirectInit, Init);
13617 if (DeducedType.isNull()) {
13618 VDecl->setInvalidDecl();
13619 return true;
13620 }
13621
13622 VDecl->setType(DeducedType);
13623 assert(VDecl->isLinkageValid());
13624
13625 // In ARC, infer lifetime.
13626 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13627 VDecl->setInvalidDecl();
13628
13629 if (getLangOpts().OpenCL)
13630 deduceOpenCLAddressSpace(Var: VDecl);
13631
13632 if (getLangOpts().HLSL)
13633 HLSL().deduceAddressSpace(Decl: VDecl);
13634
13635 // If this is a redeclaration, check that the type we just deduced matches
13636 // the previously declared type.
13637 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13638 // We never need to merge the type, because we cannot form an incomplete
13639 // array of auto, nor deduce such a type.
13640 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13641 }
13642
13643 // Check the deduced type is valid for a variable declaration.
13644 CheckVariableDeclarationType(NewVD: VDecl);
13645 return VDecl->isInvalidDecl();
13646}
13647
13648void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13649 SourceLocation Loc) {
13650 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13651 Init = EWC->getSubExpr();
13652
13653 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13654 Init = CE->getSubExpr();
13655
13656 QualType InitType = Init->getType();
13657 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13658 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13659 "shouldn't be called if type doesn't have a non-trivial C struct");
13660 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13661 for (auto *I : ILE->inits()) {
13662 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13663 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13664 continue;
13665 SourceLocation SL = I->getExprLoc();
13666 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13667 }
13668 return;
13669 }
13670
13671 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13672 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13673 checkNonTrivialCUnion(QT: InitType, Loc,
13674 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13675 NonTrivialKind: NTCUK_Init);
13676 } else {
13677 // Assume all other explicit initializers involving copying some existing
13678 // object.
13679 // TODO: ignore any explicit initializers where we can guarantee
13680 // copy-elision.
13681 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13682 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13683 NonTrivialKind: NTCUK_Copy);
13684 }
13685}
13686
13687namespace {
13688
13689bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13690 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13691 // in the source code or implicitly by the compiler if it is in a union
13692 // defined in a system header and has non-trivial ObjC ownership
13693 // qualifications. We don't want those fields to participate in determining
13694 // whether the containing union is non-trivial.
13695 return FD->hasAttr<UnavailableAttr>();
13696}
13697
13698struct DiagNonTrivalCUnionDefaultInitializeVisitor
13699 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13700 void> {
13701 using Super =
13702 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13703 void>;
13704
13705 DiagNonTrivalCUnionDefaultInitializeVisitor(
13706 QualType OrigTy, SourceLocation OrigLoc,
13707 NonTrivialCUnionContext UseContext, Sema &S)
13708 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13709
13710 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13711 const FieldDecl *FD, bool InNonTrivialUnion) {
13712 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13713 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13714 Args&: InNonTrivialUnion);
13715 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13716 }
13717
13718 void visitARCStrong(QualType QT, const FieldDecl *FD,
13719 bool InNonTrivialUnion) {
13720 if (InNonTrivialUnion)
13721 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13722 << 1 << 0 << QT << FD->getName();
13723 }
13724
13725 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13726 if (InNonTrivialUnion)
13727 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13728 << 1 << 0 << QT << FD->getName();
13729 }
13730
13731 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13732 const auto *RD = QT->castAsRecordDecl();
13733 if (RD->isUnion()) {
13734 if (OrigLoc.isValid()) {
13735 bool IsUnion = false;
13736 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13737 IsUnion = OrigRD->isUnion();
13738 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13739 << 0 << OrigTy << IsUnion << UseContext;
13740 // Reset OrigLoc so that this diagnostic is emitted only once.
13741 OrigLoc = SourceLocation();
13742 }
13743 InNonTrivialUnion = true;
13744 }
13745
13746 if (InNonTrivialUnion)
13747 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13748 << 0 << 0 << QT.getUnqualifiedType() << "";
13749
13750 for (const FieldDecl *FD : RD->fields())
13751 if (!shouldIgnoreForRecordTriviality(FD))
13752 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13753 }
13754
13755 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13756
13757 // The non-trivial C union type or the struct/union type that contains a
13758 // non-trivial C union.
13759 QualType OrigTy;
13760 SourceLocation OrigLoc;
13761 NonTrivialCUnionContext UseContext;
13762 Sema &S;
13763};
13764
13765struct DiagNonTrivalCUnionDestructedTypeVisitor
13766 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13767 using Super =
13768 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13769
13770 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13771 SourceLocation OrigLoc,
13772 NonTrivialCUnionContext UseContext,
13773 Sema &S)
13774 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13775
13776 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13777 const FieldDecl *FD, bool InNonTrivialUnion) {
13778 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13779 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13780 Args&: InNonTrivialUnion);
13781 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13782 }
13783
13784 void visitARCStrong(QualType QT, const FieldDecl *FD,
13785 bool InNonTrivialUnion) {
13786 if (InNonTrivialUnion)
13787 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13788 << 1 << 1 << QT << FD->getName();
13789 }
13790
13791 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13792 if (InNonTrivialUnion)
13793 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13794 << 1 << 1 << QT << FD->getName();
13795 }
13796
13797 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13798 const auto *RD = QT->castAsRecordDecl();
13799 if (RD->isUnion()) {
13800 if (OrigLoc.isValid()) {
13801 bool IsUnion = false;
13802 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13803 IsUnion = OrigRD->isUnion();
13804 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13805 << 1 << OrigTy << IsUnion << UseContext;
13806 // Reset OrigLoc so that this diagnostic is emitted only once.
13807 OrigLoc = SourceLocation();
13808 }
13809 InNonTrivialUnion = true;
13810 }
13811
13812 if (InNonTrivialUnion)
13813 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13814 << 0 << 1 << QT.getUnqualifiedType() << "";
13815
13816 for (const FieldDecl *FD : RD->fields())
13817 if (!shouldIgnoreForRecordTriviality(FD))
13818 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13819 }
13820
13821 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13822 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13823 bool InNonTrivialUnion) {}
13824
13825 // The non-trivial C union type or the struct/union type that contains a
13826 // non-trivial C union.
13827 QualType OrigTy;
13828 SourceLocation OrigLoc;
13829 NonTrivialCUnionContext UseContext;
13830 Sema &S;
13831};
13832
13833struct DiagNonTrivalCUnionCopyVisitor
13834 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13835 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13836
13837 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13838 NonTrivialCUnionContext UseContext, Sema &S)
13839 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13840
13841 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13842 const FieldDecl *FD, bool InNonTrivialUnion) {
13843 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13844 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13845 Args&: InNonTrivialUnion);
13846 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13847 }
13848
13849 void visitARCStrong(QualType QT, const FieldDecl *FD,
13850 bool InNonTrivialUnion) {
13851 if (InNonTrivialUnion)
13852 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13853 << 1 << 2 << QT << FD->getName();
13854 }
13855
13856 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13857 if (InNonTrivialUnion)
13858 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13859 << 1 << 2 << QT << FD->getName();
13860 }
13861
13862 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13863 const auto *RD = QT->castAsRecordDecl();
13864 if (RD->isUnion()) {
13865 if (OrigLoc.isValid()) {
13866 bool IsUnion = false;
13867 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13868 IsUnion = OrigRD->isUnion();
13869 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13870 << 2 << OrigTy << IsUnion << UseContext;
13871 // Reset OrigLoc so that this diagnostic is emitted only once.
13872 OrigLoc = SourceLocation();
13873 }
13874 InNonTrivialUnion = true;
13875 }
13876
13877 if (InNonTrivialUnion)
13878 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13879 << 0 << 2 << QT.getUnqualifiedType() << "";
13880
13881 for (const FieldDecl *FD : RD->fields())
13882 if (!shouldIgnoreForRecordTriviality(FD))
13883 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13884 }
13885
13886 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13887 if (InNonTrivialUnion)
13888 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13889 << 1 << 2 << QT << FD->getName();
13890 }
13891
13892 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13893 const FieldDecl *FD, bool InNonTrivialUnion) {}
13894 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13895 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13896 bool InNonTrivialUnion) {}
13897
13898 // The non-trivial C union type or the struct/union type that contains a
13899 // non-trivial C union.
13900 QualType OrigTy;
13901 SourceLocation OrigLoc;
13902 NonTrivialCUnionContext UseContext;
13903 Sema &S;
13904};
13905
13906} // namespace
13907
13908void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13909 NonTrivialCUnionContext UseContext,
13910 unsigned NonTrivialKind) {
13911 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13912 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13913 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13914 "shouldn't be called if type doesn't have a non-trivial C union");
13915
13916 if ((NonTrivialKind & NTCUK_Init) &&
13917 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13918 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13919 .visit(FT: QT, Args: nullptr, Args: false);
13920 if ((NonTrivialKind & NTCUK_Destruct) &&
13921 QT.hasNonTrivialToPrimitiveDestructCUnion())
13922 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13923 .visit(FT: QT, Args: nullptr, Args: false);
13924 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13925 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13926 .visit(FT: QT, Args: nullptr, Args: false);
13927}
13928
13929bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13930 const VarDecl *Dcl) {
13931 if (!getLangOpts().CPlusPlus)
13932 return false;
13933
13934 // We only need to warn if the definition is in a header file, so wait to
13935 // diagnose until we've seen the definition.
13936 if (!Dcl->isThisDeclarationADefinition())
13937 return false;
13938
13939 // If an object is defined in a source file, its definition can't get
13940 // duplicated since it will never appear in more than one TU.
13941 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
13942 return false;
13943
13944 // If the variable we're looking at is a static local, then we actually care
13945 // about the properties of the function containing it.
13946 const ValueDecl *Target = Dcl;
13947 // VarDecls and FunctionDecls have different functions for checking
13948 // inline-ness, and whether they were originally templated, so we have to
13949 // call the appropriate functions manually.
13950 bool TargetIsInline = Dcl->isInline();
13951 bool TargetWasTemplated =
13952 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13953
13954 // Update the Target and TargetIsInline property if necessary
13955 if (Dcl->isStaticLocal()) {
13956 const DeclContext *Ctx = Dcl->getDeclContext();
13957 if (!Ctx)
13958 return false;
13959
13960 const FunctionDecl *FunDcl =
13961 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
13962 if (!FunDcl)
13963 return false;
13964
13965 Target = FunDcl;
13966 // IsInlined() checks for the C++ inline property
13967 TargetIsInline = FunDcl->isInlined();
13968 TargetWasTemplated =
13969 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
13970 }
13971
13972 // Non-inline functions/variables can only legally appear in one TU
13973 // unless they were part of a template. Unfortunately, making complex
13974 // template instantiations visible is infeasible in practice, since
13975 // everything the template depends on also has to be visible. To avoid
13976 // giving impractical-to-fix warnings, don't warn if we're inside
13977 // something that was templated, even on inline stuff.
13978 if (!TargetIsInline || TargetWasTemplated)
13979 return false;
13980
13981 // If the object isn't hidden, the dynamic linker will prevent duplication.
13982 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13983
13984 // The target is "hidden" (from the dynamic linker) if:
13985 // 1. On posix, it has hidden visibility, or
13986 // 2. On windows, it has no import/export annotation, and neither does the
13987 // class which directly contains it.
13988 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13989 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13990 return false;
13991
13992 // If the variable isn't directly annotated, check to see if it's a member
13993 // of an annotated class.
13994 const CXXRecordDecl *Ctx =
13995 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
13996 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13997 return false;
13998
13999 } else if (Lnk.getVisibility() != HiddenVisibility) {
14000 // Posix case
14001 return false;
14002 }
14003
14004 // If the obj doesn't have external linkage, it's supposed to be duplicated.
14005 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
14006 return false;
14007
14008 return true;
14009}
14010
14011// Determine whether the object seems mutable for the purpose of diagnosing
14012// possible unique object duplication, i.e. non-const-qualified, and
14013// not an always-constant type like a function.
14014// Not perfect: doesn't account for mutable members, for example, or
14015// elements of container types.
14016// For nested pointers, any individual level being non-const is sufficient.
14017static bool looksMutable(QualType T, const ASTContext &Ctx) {
14018 T = T.getNonReferenceType();
14019 if (T->isFunctionType())
14020 return false;
14021 if (!T.isConstant(Ctx))
14022 return true;
14023 if (T->isPointerType())
14024 return looksMutable(T: T->getPointeeType(), Ctx);
14025 return false;
14026}
14027
14028void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
14029 // If this object has external linkage and hidden visibility, it might be
14030 // duplicated when built into a shared library, which causes problems if it's
14031 // mutable (since the copies won't be in sync) or its initialization has side
14032 // effects (since it will run once per copy instead of once globally).
14033
14034 // Don't diagnose if we're inside a template, because it's not practical to
14035 // fix the warning in most cases.
14036 if (!VD->isTemplated() &&
14037 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
14038
14039 QualType Type = VD->getType();
14040 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
14041 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
14042 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14043 }
14044
14045 // To keep false positives low, only warn if we're certain that the
14046 // initializer has side effects. Don't warn on operator new, since a mutable
14047 // pointer will trigger the previous warning, and an immutable pointer
14048 // getting duplicated just results in a little extra memory usage.
14049 const Expr *Init = VD->getAnyInitializer();
14050 if (Init &&
14051 Init->HasSideEffects(Ctx: VD->getASTContext(),
14052 /*IncludePossibleEffects=*/false) &&
14053 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
14054 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
14055 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14056 }
14057 }
14058}
14059
14060void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
14061 llvm::scope_exit ResetDeclForInitializer([this]() {
14062 if (!this->ExprEvalContexts.empty())
14063 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
14064 });
14065
14066 // If there is no declaration, there was an error parsing it. Just ignore
14067 // the initializer.
14068 if (!RealDecl) {
14069 return;
14070 }
14071
14072 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
14073 if (!Method->isInvalidDecl()) {
14074 // Pure-specifiers are handled in ActOnPureSpecifier.
14075 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
14076 << Method->getDeclName() << Init->getSourceRange();
14077 Method->setInvalidDecl();
14078 }
14079 return;
14080 }
14081
14082 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
14083 if (!VDecl) {
14084 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
14085 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
14086 RealDecl->setInvalidDecl();
14087 return;
14088 }
14089
14090 if (VDecl->isInvalidDecl()) {
14091 ExprResult Recovery =
14092 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
14093 if (Expr *E = Recovery.get())
14094 VDecl->setInit(E);
14095 return;
14096 }
14097
14098 // __amdgpu_feature_predicate_t cannot be initialised
14099 if (VDecl->getType().getDesugaredType(Context) ==
14100 Context.AMDGPUFeaturePredicateTy) {
14101 Diag(Loc: VDecl->getLocation(),
14102 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14103 << VDecl;
14104 VDecl->setInvalidDecl();
14105 return;
14106 }
14107
14108 // WebAssembly tables can't be used to initialise a variable.
14109 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
14110 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
14111 VDecl->setInvalidDecl();
14112 return;
14113 }
14114
14115 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
14116 if (VDecl->getType()->isUndeducedType()) {
14117 if (Init->containsErrors()) {
14118 // Invalidate the decl as we don't know the type for recovery-expr yet.
14119 RealDecl->setInvalidDecl();
14120 VDecl->setInit(Init);
14121 return;
14122 }
14123
14124 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
14125 assert(VDecl->isInvalidDecl() &&
14126 "decl should be invalidated when deduce fails");
14127 if (auto *RecoveryExpr =
14128 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init})
14129 .get())
14130 VDecl->setInit(RecoveryExpr);
14131 return;
14132 }
14133 }
14134
14135 this->CheckAttributesOnDeducedType(D: RealDecl);
14136
14137 // we don't initialize groupshared variables so warn and return
14138 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
14139 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_hlsl_groupshared_init);
14140 return;
14141 }
14142
14143 // dllimport cannot be used on variable definitions.
14144 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
14145 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
14146 VDecl->setInvalidDecl();
14147 return;
14148 }
14149
14150 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
14151 // the identifier has external or internal linkage, the declaration shall
14152 // have no initializer for the identifier.
14153 // C++14 [dcl.init]p5 is the same restriction for C++.
14154 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14155 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
14156 VDecl->setInvalidDecl();
14157 return;
14158 }
14159
14160 if (!VDecl->getType()->isDependentType()) {
14161 // A definition must end up with a complete type, which means it must be
14162 // complete with the restriction that an array type might be completed by
14163 // the initializer; note that later code assumes this restriction.
14164 QualType BaseDeclType = VDecl->getType();
14165 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
14166 BaseDeclType = Array->getElementType();
14167 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
14168 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14169 RealDecl->setInvalidDecl();
14170 return;
14171 }
14172
14173 // The variable can not have an abstract class type.
14174 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
14175 DiagID: diag::err_abstract_type_in_decl,
14176 Args: AbstractVariableType))
14177 VDecl->setInvalidDecl();
14178 }
14179
14180 // C++ [module.import/6]
14181 // ...
14182 // A header unit shall not contain a definition of a non-inline function or
14183 // variable whose name has external linkage.
14184 //
14185 // We choose to allow weak & selectany definitions, as they are common in
14186 // headers, and have semantics similar to inline definitions which are allowed
14187 // in header units.
14188 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14189 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14190 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14191 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
14192 !VDecl->getInstantiatedFromStaticDataMember() &&
14193 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14194 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
14195 VDecl->setInvalidDecl();
14196 }
14197
14198 // If adding the initializer will turn this declaration into a definition,
14199 // and we already have a definition for this variable, diagnose or otherwise
14200 // handle the situation.
14201 if (VarDecl *Def = VDecl->getDefinition())
14202 if (Def != VDecl &&
14203 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14204 !VDecl->isThisDeclarationADemotedDefinition() &&
14205 checkVarDeclRedefinition(Old: Def, New: VDecl))
14206 return;
14207
14208 if (getLangOpts().CPlusPlus) {
14209 // C++ [class.static.data]p4
14210 // If a static data member is of const integral or const
14211 // enumeration type, its declaration in the class definition can
14212 // specify a constant-initializer which shall be an integral
14213 // constant expression (5.19). In that case, the member can appear
14214 // in integral constant expressions. The member shall still be
14215 // defined in a namespace scope if it is used in the program and the
14216 // namespace scope definition shall not contain an initializer.
14217 //
14218 // We already performed a redefinition check above, but for static
14219 // data members we also need to check whether there was an in-class
14220 // declaration with an initializer.
14221 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14222 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
14223 << VDecl->getDeclName();
14224 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14225 DiagID: diag::note_previous_initializer)
14226 << 0;
14227 return;
14228 }
14229
14230 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
14231 VDecl->setInvalidDecl();
14232 return;
14233 }
14234 }
14235
14236 // If the variable has an initializer and local storage, check whether
14237 // anything jumps over the initialization.
14238 if (VDecl->hasLocalStorage())
14239 setFunctionHasBranchProtectedScope();
14240
14241 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14242 // a kernel function cannot be initialized."
14243 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14244 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
14245 VDecl->setInvalidDecl();
14246 return;
14247 }
14248
14249 // The LoaderUninitialized attribute acts as a definition (of undef).
14250 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14251 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
14252 VDecl->setInvalidDecl();
14253 return;
14254 }
14255
14256 if (getLangOpts().HLSL)
14257 if (!HLSL().handleInitialization(VDecl, Init))
14258 return;
14259
14260 // Get the decls type and save a reference for later, since
14261 // CheckInitializerTypes may change it.
14262 QualType DclT = VDecl->getType(), SavT = DclT;
14263
14264 // Expressions default to 'id' when we're in a debugger
14265 // and we are assigning it to a variable of Objective-C pointer type.
14266 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14267 Init->getType() == Context.UnknownAnyTy) {
14268 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
14269 if (!Result.isUsable()) {
14270 VDecl->setInvalidDecl();
14271 return;
14272 }
14273 Init = Result.get();
14274 }
14275
14276 // Perform the initialization.
14277 bool InitializedFromParenListExpr = false;
14278 bool IsParenListInit = false;
14279 if (!VDecl->isInvalidDecl()) {
14280 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
14281 InitializationKind Kind = InitializationKind::CreateForInit(
14282 Loc: VDecl->getLocation(), DirectInit, Init);
14283
14284 MultiExprArg Args = Init;
14285 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
14286 Args =
14287 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14288 InitializedFromParenListExpr = true;
14289 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
14290 Args = CXXDirectInit->getInitExprs();
14291 InitializedFromParenListExpr = true;
14292 }
14293
14294 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14295 /*TopLevelOfInitList=*/false,
14296 /*TreatUnavailableAsInvalid=*/false);
14297 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
14298 if (!Result.isUsable()) {
14299 // If the provided initializer fails to initialize the var decl,
14300 // we attach a recovery expr for better recovery.
14301 auto RecoveryExpr =
14302 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
14303 if (RecoveryExpr.get())
14304 VDecl->setInit(RecoveryExpr.get());
14305 // In general, for error recovery purposes, the initializer doesn't play
14306 // part in the valid bit of the declaration. There are a few exceptions:
14307 // 1) if the var decl has a deduced auto type, and the type cannot be
14308 // deduced by an invalid initializer;
14309 // 2) if the var decl is a decomposition decl with a non-deduced type,
14310 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14311 // Case 1) was already handled elsewhere.
14312 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
14313 VDecl->setInvalidDecl();
14314 return;
14315 }
14316
14317 Init = Result.getAs<Expr>();
14318 IsParenListInit = !InitSeq.steps().empty() &&
14319 InitSeq.step_begin()->Kind ==
14320 InitializationSequence::SK_ParenthesizedListInit;
14321 QualType VDeclType = VDecl->getType();
14322 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14323 !VDeclType->isDependentType() &&
14324 Context.getAsIncompleteArrayType(T: VDeclType) &&
14325 Context.getAsIncompleteArrayType(T: Init->getType())) {
14326 // Bail out if it is not possible to deduce array size from the
14327 // initializer.
14328 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
14329 << VDeclType;
14330 VDecl->setInvalidDecl();
14331 return;
14332 }
14333 }
14334
14335 // Check for self-references within variable initializers.
14336 // Variables declared within a function/method body (except for references)
14337 // are handled by a dataflow analysis.
14338 // This is undefined behavior in C++, but valid in C.
14339 if (getLangOpts().CPlusPlus)
14340 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14341 VDecl->getType()->isReferenceType())
14342 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
14343
14344 // If the type changed, it means we had an incomplete type that was
14345 // completed by the initializer. For example:
14346 // int ary[] = { 1, 3, 5 };
14347 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14348 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14349 VDecl->setType(DclT);
14350
14351 if (!VDecl->isInvalidDecl()) {
14352 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
14353
14354 if (VDecl->hasAttr<BlocksAttr>())
14355 ObjC().checkRetainCycles(Var: VDecl, Init);
14356
14357 // It is safe to assign a weak reference into a strong variable.
14358 // Although this code can still have problems:
14359 // id x = self.weakProp;
14360 // id y = self.weakProp;
14361 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14362 // paths through the function. This should be revisited if
14363 // -Wrepeated-use-of-weak is made flow-sensitive.
14364 if (FunctionScopeInfo *FSI = getCurFunction())
14365 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14366 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14367 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14368 Loc: Init->getBeginLoc()))
14369 FSI->markSafeWeakUse(E: Init);
14370 }
14371
14372 // The initialization is usually a full-expression.
14373 //
14374 // FIXME: If this is a braced initialization of an aggregate, it is not
14375 // an expression, and each individual field initializer is a separate
14376 // full-expression. For instance, in:
14377 //
14378 // struct Temp { ~Temp(); };
14379 // struct S { S(Temp); };
14380 // struct T { S a, b; } t = { Temp(), Temp() }
14381 //
14382 // we should destroy the first Temp before constructing the second.
14383
14384 // Set context flag for OverflowBehaviorType initialization analysis
14385 llvm::SaveAndRestore OBTAssignmentContext(InOverflowBehaviorAssignmentContext,
14386 true);
14387 ExprResult Result =
14388 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
14389 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
14390 if (!Result.isUsable()) {
14391 VDecl->setInvalidDecl();
14392 return;
14393 }
14394 Init = Result.get();
14395
14396 // Attach the initializer to the decl.
14397 VDecl->setInit(Init);
14398
14399 if (VDecl->isLocalVarDecl()) {
14400 // Don't check the initializer if the declaration is malformed.
14401 if (VDecl->isInvalidDecl()) {
14402 // do nothing
14403
14404 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14405 // This is true even in C++ for OpenCL.
14406 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14407 CheckForConstantInitializer(Init);
14408
14409 // Otherwise, C++ does not restrict the initializer.
14410 } else if (getLangOpts().CPlusPlus) {
14411 // do nothing
14412
14413 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14414 // static storage duration shall be constant expressions or string literals.
14415 } else if (VDecl->getStorageClass() == SC_Static) {
14416 // Avoid evaluating the initializer twice for constexpr variables. It will
14417 // be evaluated later.
14418 if (!VDecl->isConstexpr())
14419 CheckForConstantInitializer(Init);
14420
14421 // C89 is stricter than C99 for aggregate initializers.
14422 // C89 6.5.7p3: All the expressions [...] in an initializer list
14423 // for an object that has aggregate or union type shall be
14424 // constant expressions.
14425 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14426 isa<InitListExpr>(Val: Init)) {
14427 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
14428 }
14429
14430 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
14431 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
14432 if (VDecl->hasLocalStorage())
14433 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14434 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14435 VDecl->getLexicalDeclContext()->isRecord()) {
14436 // This is an in-class initialization for a static data member, e.g.,
14437 //
14438 // struct S {
14439 // static const int value = 17;
14440 // };
14441
14442 // C++ [class.mem]p4:
14443 // A member-declarator can contain a constant-initializer only
14444 // if it declares a static member (9.4) of const integral or
14445 // const enumeration type, see 9.4.2.
14446 //
14447 // C++11 [class.static.data]p3:
14448 // If a non-volatile non-inline const static data member is of integral
14449 // or enumeration type, its declaration in the class definition can
14450 // specify a brace-or-equal-initializer in which every initializer-clause
14451 // that is an assignment-expression is a constant expression. A static
14452 // data member of literal type can be declared in the class definition
14453 // with the constexpr specifier; if so, its declaration shall specify a
14454 // brace-or-equal-initializer in which every initializer-clause that is
14455 // an assignment-expression is a constant expression.
14456
14457 // Do nothing on dependent types.
14458 if (DclT->isDependentType()) {
14459
14460 // Allow any 'static constexpr' members, whether or not they are of literal
14461 // type. We separately check that every constexpr variable is of literal
14462 // type.
14463 } else if (VDecl->isConstexpr()) {
14464
14465 // Require constness.
14466 } else if (!DclT.isConstQualified()) {
14467 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
14468 << Init->getSourceRange();
14469 VDecl->setInvalidDecl();
14470
14471 // We allow integer constant expressions in all cases.
14472 } else if (DclT->isIntegralOrEnumerationType()) {
14473 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14474 // In C++11, a non-constexpr const static data member with an
14475 // in-class initializer cannot be volatile.
14476 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
14477
14478 // We allow foldable floating-point constants as an extension.
14479 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14480 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14481 // it anyway and provide a fixit to add the 'constexpr'.
14482 if (getLangOpts().CPlusPlus11) {
14483 Diag(Loc: VDecl->getLocation(),
14484 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
14485 << DclT << Init->getSourceRange();
14486 Diag(Loc: VDecl->getBeginLoc(),
14487 DiagID: diag::note_in_class_initializer_float_type_cxx11)
14488 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14489 } else {
14490 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14491 << DclT << Init->getSourceRange();
14492
14493 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14494 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14495 << Init->getSourceRange();
14496 VDecl->setInvalidDecl();
14497 }
14498 }
14499
14500 // Suggest adding 'constexpr' in C++11 for literal types.
14501 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14502 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14503 << DclT << Init->getSourceRange()
14504 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14505 VDecl->setConstexpr(true);
14506
14507 } else {
14508 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14509 << DclT << Init->getSourceRange();
14510 VDecl->setInvalidDecl();
14511 }
14512 } else if (VDecl->isFileVarDecl()) {
14513 // In C, extern is typically used to avoid tentative definitions when
14514 // declaring variables in headers, but adding an initializer makes it a
14515 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14516 // In C++, extern is often used to give implicitly static const variables
14517 // external linkage, so don't warn in that case. If selectany is present,
14518 // this might be header code intended for C and C++ inclusion, so apply the
14519 // C++ rules.
14520 if (VDecl->getStorageClass() == SC_Extern &&
14521 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14522 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14523 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14524 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14525 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14526
14527 // In Microsoft C++ mode, a const variable defined in namespace scope has
14528 // external linkage by default if the variable is declared with
14529 // __declspec(dllexport).
14530 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14531 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14532 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14533 VDecl->setStorageClass(SC_Extern);
14534
14535 // C99 6.7.8p4. All file scoped initializers need to be constant.
14536 // Avoid duplicate diagnostics for constexpr variables.
14537 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14538 !VDecl->isConstexpr())
14539 CheckForConstantInitializer(Init);
14540 }
14541
14542 QualType InitType = Init->getType();
14543 if (!InitType.isNull() &&
14544 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14545 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14546 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14547
14548 // We will represent direct-initialization similarly to copy-initialization:
14549 // int x(1); -as-> int x = 1;
14550 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14551 //
14552 // Clients that want to distinguish between the two forms, can check for
14553 // direct initializer using VarDecl::getInitStyle().
14554 // A major benefit is that clients that don't particularly care about which
14555 // exactly form was it (like the CodeGen) can handle both cases without
14556 // special case code.
14557
14558 // C++ 8.5p11:
14559 // The form of initialization (using parentheses or '=') matters
14560 // when the entity being initialized has class type.
14561 if (InitializedFromParenListExpr) {
14562 assert(DirectInit && "Call-style initializer must be direct init.");
14563 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14564 : VarDecl::CallInit);
14565 } else if (DirectInit) {
14566 // This must be list-initialization. No other way is direct-initialization.
14567 VDecl->setInitStyle(VarDecl::ListInit);
14568 }
14569
14570 if (LangOpts.OpenMP &&
14571 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14572 VDecl->isFileVarDecl())
14573 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14574 CheckCompleteVariableDeclaration(VD: VDecl);
14575
14576 if (LangOpts.OpenACC && !InitType.isNull())
14577 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14578}
14579
14580void Sema::ActOnInitializerError(Decl *D) {
14581 // Our main concern here is re-establishing invariants like "a
14582 // variable's type is either dependent or complete".
14583 if (!D || D->isInvalidDecl()) return;
14584
14585 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14586 if (!VD) return;
14587
14588 // Bindings are not usable if we can't make sense of the initializer.
14589 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14590 for (auto *BD : DD->bindings())
14591 BD->setInvalidDecl();
14592
14593 // Auto types are meaningless if we can't make sense of the initializer.
14594 if (VD->getType()->isUndeducedType()) {
14595 D->setInvalidDecl();
14596 return;
14597 }
14598
14599 QualType Ty = VD->getType();
14600 if (Ty->isDependentType()) return;
14601
14602 // Require a complete type.
14603 if (RequireCompleteType(Loc: VD->getLocation(),
14604 T: Context.getBaseElementType(QT: Ty),
14605 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14606 VD->setInvalidDecl();
14607 return;
14608 }
14609
14610 // Require a non-abstract type.
14611 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14612 DiagID: diag::err_abstract_type_in_decl,
14613 Args: AbstractVariableType)) {
14614 VD->setInvalidDecl();
14615 return;
14616 }
14617
14618 // Don't bother complaining about constructors or destructors,
14619 // though.
14620}
14621
14622void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14623 // If there is no declaration, there was an error parsing it. Just ignore it.
14624 if (!RealDecl)
14625 return;
14626
14627 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14628 QualType Type = Var->getType();
14629
14630 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14631 Diag(Loc: Var->getLocation(),
14632 DiagID: diag::err_amdgcn_predicate_type_is_not_constructible)
14633 << Var;
14634 Var->setInvalidDecl();
14635 return;
14636 }
14637 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14638 if (isa<DecompositionDecl>(Val: RealDecl)) {
14639 // Point the caret to the token immediately after the closing bracket if
14640 // it can be found; otherwise fall back to the declaration's location.
14641 SourceLocation Loc = Var->getLocation();
14642 SourceLocation RSquareLoc =
14643 dyn_cast<DecompositionDecl>(Val: RealDecl)->getRSquareLoc();
14644 if (std::optional<Token> Next = Lexer::findNextToken(
14645 Loc: RSquareLoc, SM: PP.getSourceManager(), LangOpts: PP.getLangOpts()))
14646 Loc = Next->getLocation();
14647 Diag(Loc, DiagID: diag::err_decomp_decl_requires_init) << Var;
14648 Var->setInvalidDecl();
14649 return;
14650 }
14651
14652 if (Type->isUndeducedType() &&
14653 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14654 return;
14655
14656 this->CheckAttributesOnDeducedType(D: RealDecl);
14657
14658 // C++11 [class.static.data]p3: A static data member can be declared with
14659 // the constexpr specifier; if so, its declaration shall specify
14660 // a brace-or-equal-initializer.
14661 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14662 // the definition of a variable [...] or the declaration of a static data
14663 // member.
14664 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14665 !Var->isThisDeclarationADemotedDefinition()) {
14666 if (Var->isStaticDataMember()) {
14667 // C++1z removes the relevant rule; the in-class declaration is always
14668 // a definition there.
14669 if (!getLangOpts().CPlusPlus17 &&
14670 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14671 Diag(Loc: Var->getLocation(),
14672 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14673 << Var;
14674 Var->setInvalidDecl();
14675 return;
14676 }
14677 } else {
14678 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14679 Var->setInvalidDecl();
14680 return;
14681 }
14682 }
14683
14684 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14685 // be initialized.
14686 if (!Var->isInvalidDecl() &&
14687 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14688 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14689 bool HasConstExprDefaultConstructor = false;
14690 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14691 for (auto *Ctor : RD->ctors()) {
14692 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14693 Ctor->getMethodQualifiers().getAddressSpace() ==
14694 LangAS::opencl_constant) {
14695 HasConstExprDefaultConstructor = true;
14696 }
14697 }
14698 }
14699 if (!HasConstExprDefaultConstructor) {
14700 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14701 Var->setInvalidDecl();
14702 return;
14703 }
14704 }
14705
14706 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14707 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14708 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14709 Var->setInvalidDecl();
14710 return;
14711 }
14712
14713 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14714 if (Var->getStorageClass() == SC_Extern) {
14715 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14716 << Var;
14717 Var->setInvalidDecl();
14718 return;
14719 }
14720 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14721 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14722 Var->setInvalidDecl();
14723 return;
14724 }
14725 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14726 if (!RD->hasTrivialDefaultConstructor()) {
14727 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14728 Var->setInvalidDecl();
14729 return;
14730 }
14731 }
14732 // The declaration is uninitialized, no need for further checks.
14733 return;
14734 }
14735
14736 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14737 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14738 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14739 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14740 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14741 NonTrivialKind: NTCUK_Init);
14742
14743 switch (DefKind) {
14744 case VarDecl::Definition:
14745 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14746 break;
14747
14748 // We have an out-of-line definition of a static data member
14749 // that has an in-class initializer, so we type-check this like
14750 // a declaration.
14751 //
14752 [[fallthrough]];
14753
14754 case VarDecl::DeclarationOnly:
14755 // It's only a declaration.
14756
14757 // Block scope. C99 6.7p7: If an identifier for an object is
14758 // declared with no linkage (C99 6.2.2p6), the type for the
14759 // object shall be complete.
14760 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14761 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14762 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14763 DiagID: diag::err_typecheck_decl_incomplete_type))
14764 Var->setInvalidDecl();
14765
14766 // Make sure that the type is not abstract.
14767 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14768 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14769 DiagID: diag::err_abstract_type_in_decl,
14770 Args: AbstractVariableType))
14771 Var->setInvalidDecl();
14772 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14773 Var->getStorageClass() == SC_PrivateExtern) {
14774 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14775 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14776 }
14777
14778 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14779 !Var->isInvalidDecl())
14780 ExternalDeclarations.push_back(Elt: Var);
14781
14782 return;
14783
14784 case VarDecl::TentativeDefinition:
14785 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14786 // object that has file scope without an initializer, and without a
14787 // storage-class specifier or with the storage-class specifier "static",
14788 // constitutes a tentative definition. Note: A tentative definition with
14789 // external linkage is valid (C99 6.2.2p5).
14790 if (!Var->isInvalidDecl()) {
14791 if (const IncompleteArrayType *ArrayT
14792 = Context.getAsIncompleteArrayType(T: Type)) {
14793 if (RequireCompleteSizedType(
14794 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14795 DiagID: diag::err_array_incomplete_or_sizeless_type))
14796 Var->setInvalidDecl();
14797 }
14798 if (Var->getStorageClass() == SC_Static) {
14799 // C99 6.9.2p3: If the declaration of an identifier for an object is
14800 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14801 // declared type shall not be an incomplete type.
14802 // NOTE: code such as the following
14803 // static struct s;
14804 // struct s { int a; };
14805 // is accepted by gcc. Hence here we issue a warning instead of
14806 // an error and we do not invalidate the static declaration.
14807 // NOTE: to avoid multiple warnings, only check the first declaration.
14808 if (Var->isFirstDecl())
14809 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14810 DiagID: diag::ext_typecheck_decl_incomplete_type,
14811 Args: Type->isArrayType());
14812 }
14813 }
14814
14815 // Record the tentative definition; we're done.
14816 if (!Var->isInvalidDecl())
14817 TentativeDefinitions.push_back(LocalValue: Var);
14818 return;
14819 }
14820
14821 // Provide a specific diagnostic for uninitialized variable definitions
14822 // with incomplete array type, unless it is a global unbounded HLSL resource
14823 // array.
14824 if (Type->isIncompleteArrayType() &&
14825 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14826 Type->isHLSLResourceRecordArray())) {
14827 if (Var->isConstexpr())
14828 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14829 << Var;
14830 else
14831 Diag(Loc: Var->getLocation(),
14832 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14833 Var->setInvalidDecl();
14834 return;
14835 }
14836
14837 // Provide a specific diagnostic for uninitialized variable
14838 // definitions with reference type.
14839 if (Type->isReferenceType()) {
14840 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14841 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14842 return;
14843 }
14844
14845 // Do not attempt to type-check the default initializer for a
14846 // variable with dependent type.
14847 if (Type->isDependentType())
14848 return;
14849
14850 if (Var->isInvalidDecl())
14851 return;
14852
14853 if (!Var->hasAttr<AliasAttr>()) {
14854 if (RequireCompleteType(Loc: Var->getLocation(),
14855 T: Context.getBaseElementType(QT: Type),
14856 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14857 Var->setInvalidDecl();
14858 return;
14859 }
14860 } else {
14861 return;
14862 }
14863
14864 // The variable can not have an abstract class type.
14865 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14866 DiagID: diag::err_abstract_type_in_decl,
14867 Args: AbstractVariableType)) {
14868 Var->setInvalidDecl();
14869 return;
14870 }
14871
14872 // In C, if the definition is const-qualified and has no initializer, it
14873 // is left uninitialized unless it has static or thread storage duration.
14874 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14875 unsigned DiagID = diag::warn_default_init_const_unsafe;
14876 if (Var->getStorageDuration() == SD_Static ||
14877 Var->getStorageDuration() == SD_Thread)
14878 DiagID = diag::warn_default_init_const;
14879
14880 bool EmitCppCompat = !Diags.isIgnored(
14881 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14882 Loc: Var->getLocation());
14883
14884 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14885 }
14886
14887 // Check for jumps past the implicit initializer. C++0x
14888 // clarifies that this applies to a "variable with automatic
14889 // storage duration", not a "local variable".
14890 // C++11 [stmt.dcl]p3
14891 // A program that jumps from a point where a variable with automatic
14892 // storage duration is not in scope to a point where it is in scope is
14893 // ill-formed unless the variable has scalar type, class type with a
14894 // trivial default constructor and a trivial destructor, a cv-qualified
14895 // version of one of these types, or an array of one of the preceding
14896 // types and is declared without an initializer.
14897 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14898 if (const auto *CXXRecord =
14899 Context.getBaseElementType(QT: Type)->getAsCXXRecordDecl()) {
14900 // Mark the function (if we're in one) for further checking even if the
14901 // looser rules of C++11 do not require such checks, so that we can
14902 // diagnose incompatibilities with C++98.
14903 if (!CXXRecord->isPOD())
14904 setFunctionHasBranchProtectedScope();
14905 }
14906 }
14907 // In OpenCL, we can't initialize objects in the __local address space,
14908 // even implicitly, so don't synthesize an implicit initializer.
14909 if (getLangOpts().OpenCL &&
14910 Var->getType().getAddressSpace() == LangAS::opencl_local)
14911 return;
14912
14913 // Handle HLSL uninitialized decls
14914 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14915 return;
14916
14917 // HLSL input & push-constant variables are expected to be externally
14918 // initialized, even when marked `static`.
14919 if (getLangOpts().HLSL &&
14920 hlsl::isInitializedByPipeline(AS: Var->getType().getAddressSpace()))
14921 return;
14922
14923 // C++03 [dcl.init]p9:
14924 // If no initializer is specified for an object, and the
14925 // object is of (possibly cv-qualified) non-POD class type (or
14926 // array thereof), the object shall be default-initialized; if
14927 // the object is of const-qualified type, the underlying class
14928 // type shall have a user-declared default
14929 // constructor. Otherwise, if no initializer is specified for
14930 // a non- static object, the object and its subobjects, if
14931 // any, have an indeterminate initial value); if the object
14932 // or any of its subobjects are of const-qualified type, the
14933 // program is ill-formed.
14934 // C++0x [dcl.init]p11:
14935 // If no initializer is specified for an object, the object is
14936 // default-initialized; [...].
14937 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14938 InitializationKind Kind
14939 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14940
14941 InitializationSequence InitSeq(*this, Entity, Kind, {});
14942 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
14943
14944 if (Init.get()) {
14945 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14946 // This is important for template substitution.
14947 Var->setInitStyle(VarDecl::CallInit);
14948 } else if (Init.isInvalid()) {
14949 // If default-init fails, attach a recovery-expr initializer to track
14950 // that initialization was attempted and failed.
14951 auto RecoveryExpr =
14952 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14953 if (RecoveryExpr.get())
14954 Var->setInit(RecoveryExpr.get());
14955 }
14956
14957 CheckCompleteVariableDeclaration(VD: Var);
14958 }
14959}
14960
14961void Sema::ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt) {
14962 // If there is no declaration, there was an error parsing it. Ignore it.
14963 if (!D)
14964 return;
14965
14966 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14967 if (!VD) {
14968 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var)
14969 << InExpansionStmt;
14970 D->setInvalidDecl();
14971 return;
14972 }
14973
14974 VD->setCXXForRangeDecl(true);
14975
14976 // for-range-declaration cannot be given a storage class specifier.
14977 int Error = -1;
14978 switch (VD->getStorageClass()) {
14979 case SC_None:
14980 break;
14981 case SC_Extern:
14982 Error = 0;
14983 break;
14984 case SC_Static:
14985 Error = 1;
14986 break;
14987 case SC_PrivateExtern:
14988 Error = 2;
14989 break;
14990 case SC_Auto:
14991 Error = 3;
14992 break;
14993 case SC_Register:
14994 Error = 4;
14995 break;
14996 }
14997
14998 // for-range-declaration cannot be given a storage class specifier con't.
14999 switch (VD->getTSCSpec()) {
15000 case TSCS_thread_local:
15001 Error = 6;
15002 break;
15003 case TSCS___thread:
15004 case TSCS__Thread_local:
15005 case TSCS_unspecified:
15006 break;
15007 }
15008
15009 if (Error != -1) {
15010 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
15011 << InExpansionStmt << VD << Error;
15012 D->setInvalidDecl();
15013 }
15014}
15015
15016StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
15017 IdentifierInfo *Ident,
15018 ParsedAttributes &Attrs) {
15019 // C++1y [stmt.iter]p1:
15020 // A range-based for statement of the form
15021 // for ( for-range-identifier : for-range-initializer ) statement
15022 // is equivalent to
15023 // for ( auto&& for-range-identifier : for-range-initializer ) statement
15024 DeclSpec DS(Attrs.getPool().getFactory());
15025
15026 const char *PrevSpec;
15027 unsigned DiagID;
15028 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
15029 Policy: getPrintingPolicy());
15030
15031 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
15032 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
15033 D.takeAttributesAppending(attrs&: Attrs);
15034
15035 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
15036 EndLoc: IdentLoc);
15037 Decl *Var = ActOnDeclarator(S, D);
15038 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
15039 FinalizeDeclaration(D: Var);
15040 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
15041 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
15042 : IdentLoc);
15043}
15044
15045void Sema::addLifetimeBoundToImplicitThis(CXXMethodDecl *MD) {
15046 if (!MD || lifetimes::implicitObjectParamIsLifetimeBound(FD: MD))
15047 return;
15048 auto *Attr = LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: MD->getLocation());
15049 QualType MethodType = MD->getType();
15050 QualType AttributedType =
15051 Context.getAttributedType(attr: Attr, modifiedType: MethodType, equivalentType: MethodType);
15052 TypeLocBuilder TLB;
15053 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
15054 TLB.pushFullCopy(L: TSI->getTypeLoc());
15055 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
15056 TyLoc.setAttr(Attr);
15057 MD->setType(AttributedType);
15058 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, T: AttributedType));
15059}
15060
15061void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
15062 if (var->isInvalidDecl()) return;
15063
15064 CUDA().MaybeAddConstantAttr(VD: var);
15065
15066 if (getLangOpts().OpenCL) {
15067 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
15068 // initialiser
15069 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
15070 !var->hasInit()) {
15071 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
15072 << 1 /*Init*/;
15073 var->setInvalidDecl();
15074 return;
15075 }
15076 }
15077
15078 // In Objective-C, don't allow jumps past the implicit initialization of a
15079 // local retaining variable.
15080 if (getLangOpts().ObjC &&
15081 var->hasLocalStorage()) {
15082 switch (var->getType().getObjCLifetime()) {
15083 case Qualifiers::OCL_None:
15084 case Qualifiers::OCL_ExplicitNone:
15085 case Qualifiers::OCL_Autoreleasing:
15086 break;
15087
15088 case Qualifiers::OCL_Weak:
15089 case Qualifiers::OCL_Strong:
15090 setFunctionHasBranchProtectedScope();
15091 break;
15092 }
15093 }
15094
15095 if (var->hasLocalStorage() &&
15096 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
15097 setFunctionHasBranchProtectedScope();
15098
15099 // Warn about externally-visible variables being defined without a
15100 // prior declaration. We only want to do this for global
15101 // declarations, but we also specifically need to avoid doing it for
15102 // class members because the linkage of an anonymous class can
15103 // change if it's later given a typedef name.
15104 if (var->isThisDeclarationADefinition() &&
15105 var->getDeclContext()->getRedeclContext()->isFileContext() &&
15106 var->isExternallyVisible() && var->hasLinkage() &&
15107 !var->isInline() && !var->getDescribedVarTemplate() &&
15108 var->getStorageClass() != SC_Register &&
15109 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
15110 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
15111 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
15112 Loc: var->getLocation())) {
15113 // Find a previous declaration that's not a definition.
15114 VarDecl *prev = var->getPreviousDecl();
15115 while (prev && prev->isThisDeclarationADefinition())
15116 prev = prev->getPreviousDecl();
15117
15118 if (!prev) {
15119 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
15120 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
15121 << /* variable */ 0;
15122 }
15123 }
15124
15125 // Cache the result of checking for constant initialization.
15126 std::optional<bool> CacheHasConstInit;
15127 const Expr *CacheCulprit = nullptr;
15128 auto checkConstInit = [&]() mutable {
15129 const Expr *Init = var->getInit();
15130 if (Init->isInstantiationDependent())
15131 return true;
15132
15133 if (!CacheHasConstInit)
15134 CacheHasConstInit = var->getInit()->isConstantInitializer(
15135 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
15136 return *CacheHasConstInit;
15137 };
15138
15139 if (var->getTLSKind() == VarDecl::TLS_Static) {
15140 if (var->getType().isDestructedType()) {
15141 // GNU C++98 edits for __thread, [basic.start.term]p3:
15142 // The type of an object with thread storage duration shall not
15143 // have a non-trivial destructor.
15144 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
15145 if (getLangOpts().CPlusPlus11)
15146 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15147 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
15148 if (!checkConstInit()) {
15149 // GNU C++98 edits for __thread, [basic.start.init]p4:
15150 // An object of thread storage duration shall not require dynamic
15151 // initialization.
15152 // FIXME: Need strict checking here.
15153 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
15154 << CacheCulprit->getSourceRange();
15155 if (getLangOpts().CPlusPlus11)
15156 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
15157 }
15158 }
15159 }
15160
15161
15162 if (!var->getType()->isStructureType() && var->hasInit() &&
15163 isa<InitListExpr>(Val: var->getInit())) {
15164 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
15165 unsigned NumInits = ILE->getNumInits();
15166 if (NumInits > 2)
15167 for (unsigned I = 0; I < NumInits; ++I) {
15168 const auto *Init = ILE->getInit(Init: I);
15169 if (!Init)
15170 break;
15171 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15172 if (!SL)
15173 break;
15174
15175 unsigned NumConcat = SL->getNumConcatenated();
15176 // Diagnose missing comma in string array initialization.
15177 // Do not warn when all the elements in the initializer are concatenated
15178 // together. Do not warn for macros too.
15179 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15180 bool OnlyOneMissingComma = true;
15181 for (unsigned J = I + 1; J < NumInits; ++J) {
15182 const auto *Init = ILE->getInit(Init: J);
15183 if (!Init)
15184 break;
15185 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
15186 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15187 OnlyOneMissingComma = false;
15188 break;
15189 }
15190 }
15191
15192 if (OnlyOneMissingComma) {
15193 SmallVector<FixItHint, 1> Hints;
15194 for (unsigned i = 0; i < NumConcat - 1; ++i)
15195 Hints.push_back(Elt: FixItHint::CreateInsertion(
15196 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
15197
15198 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
15199 DiagID: diag::warn_concatenated_literal_array_init)
15200 << Hints;
15201 Diag(Loc: SL->getBeginLoc(),
15202 DiagID: diag::note_concatenated_string_literal_silence);
15203 }
15204 // In any case, stop now.
15205 break;
15206 }
15207 }
15208 }
15209
15210
15211 QualType type = var->getType();
15212
15213 if (var->hasAttr<BlocksAttr>())
15214 getCurFunction()->addByrefBlockVar(VD: var);
15215
15216 Expr *Init = var->getInit();
15217 bool GlobalStorage = var->hasGlobalStorage();
15218 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15219 QualType baseType = Context.getBaseElementType(QT: type);
15220 bool HasConstInit = true;
15221
15222 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15223 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
15224 << var;
15225
15226 // Check whether the initializer is sufficiently constant.
15227 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15228 !type->isDependentType() && Init && !Init->isValueDependent() &&
15229 (GlobalStorage || var->isConstexpr() ||
15230 var->mightBeUsableInConstantExpressions(C: Context))) {
15231 // If this variable might have a constant initializer or might be usable in
15232 // constant expressions, check whether or not it actually is now. We can't
15233 // do this lazily, because the result might depend on things that change
15234 // later, such as which constexpr functions happen to be defined.
15235 SmallVector<PartialDiagnosticAt, 8> Notes;
15236 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15237 // Prior to C++11, in contexts where a constant initializer is required,
15238 // the set of valid constant initializers is described by syntactic rules
15239 // in [expr.const]p2-6.
15240 // FIXME: Stricter checking for these rules would be useful for constinit /
15241 // -Wglobal-constructors.
15242 HasConstInit = checkConstInit();
15243
15244 // Compute and cache the constant value, and remember that we have a
15245 // constant initializer.
15246 if (HasConstInit) {
15247 if (var->isStaticDataMember() && !var->isInline() &&
15248 var->getLexicalDeclContext()->isRecord() &&
15249 type->isIntegralOrEnumerationType()) {
15250 // In C++98, in-class initialization for a static data member must
15251 // be an integer constant expression.
15252 if (!Init->isIntegerConstantExpr(Ctx: Context)) {
15253 Diag(Loc: Init->getExprLoc(),
15254 DiagID: diag::ext_in_class_initializer_non_constant)
15255 << Init->getSourceRange();
15256 }
15257 }
15258 (void)var->checkForConstantInitialization(Notes);
15259 Notes.clear();
15260 } else if (CacheCulprit) {
15261 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
15262 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
15263 Notes.back().second << CacheCulprit->getSourceRange();
15264 }
15265 } else {
15266 // Evaluate the initializer to see if it's a constant initializer.
15267 HasConstInit = var->checkForConstantInitialization(Notes);
15268 }
15269
15270 if (HasConstInit) {
15271 // FIXME: Consider replacing the initializer with a ConstantExpr.
15272 } else if (var->isConstexpr()) {
15273 SourceLocation DiagLoc = var->getLocation();
15274 // If the note doesn't add any useful information other than a source
15275 // location, fold it into the primary diagnostic.
15276 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15277 diag::note_invalid_subexpr_in_const_expr) {
15278 DiagLoc = Notes[0].first;
15279 Notes.clear();
15280 }
15281 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
15282 << var << Init->getSourceRange();
15283 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15284 Diag(Loc: Notes[I].first, PD: Notes[I].second);
15285 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15286 auto *Attr = var->getAttr<ConstInitAttr>();
15287 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
15288 << Init->getSourceRange();
15289 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
15290 << Attr->getRange() << Attr->isConstinit();
15291 for (auto &it : Notes)
15292 Diag(Loc: it.first, PD: it.second);
15293 } else if (var->isStaticDataMember() && !var->isInline() &&
15294 var->getLexicalDeclContext()->isRecord()) {
15295 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
15296 << Init->getSourceRange();
15297 for (auto &it : Notes)
15298 Diag(Loc: it.first, PD: it.second);
15299 var->setInvalidDecl();
15300 } else if (IsGlobal &&
15301 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
15302 Loc: var->getLocation())) {
15303 // Warn about globals which don't have a constant initializer. Don't
15304 // warn about globals with a non-trivial destructor because we already
15305 // warned about them.
15306 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15307 if (!(RD && !RD->hasTrivialDestructor())) {
15308 // checkConstInit() here permits trivial default initialization even in
15309 // C++11 onwards, where such an initializer is not a constant initializer
15310 // but nonetheless doesn't require a global constructor.
15311 if (!checkConstInit())
15312 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
15313 << Init->getSourceRange();
15314 }
15315 }
15316 }
15317
15318 // Apply section attributes and pragmas to global variables.
15319 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15320 !inTemplateInstantiation()) {
15321 PragmaStack<StringLiteral *> *Stack = nullptr;
15322 int SectionFlags = ASTContext::PSF_Read;
15323 bool MSVCEnv =
15324 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15325 std::optional<QualType::NonConstantStorageReason> Reason;
15326 if (HasConstInit &&
15327 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
15328 Stack = &ConstSegStack;
15329 } else {
15330 SectionFlags |= ASTContext::PSF_Write;
15331 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15332 }
15333 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15334 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15335 SectionFlags |= ASTContext::PSF_Implicit;
15336 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
15337 } else if (Stack->CurrentValue) {
15338 if (Stack != &ConstSegStack && MSVCEnv &&
15339 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15340 var->getType().isConstQualified()) {
15341 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15342 NonConstNonReferenceType) &&
15343 "This case should've already been handled elsewhere");
15344 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
15345 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15346 ? QualType::NonConstantStorageReason::NonTrivialCtor
15347 : *Reason);
15348 }
15349 SectionFlags |= ASTContext::PSF_Implicit;
15350 auto SectionName = Stack->CurrentValue->getString();
15351 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
15352 Range: Stack->CurrentPragmaLocation,
15353 S: SectionAttr::Declspec_allocate));
15354 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
15355 var->dropAttr<SectionAttr>();
15356 }
15357
15358 // Apply the init_seg attribute if this has an initializer. If the
15359 // initializer turns out to not be dynamic, we'll end up ignoring this
15360 // attribute.
15361 if (CurInitSeg && var->getInit())
15362 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
15363 Range: CurInitSegLoc));
15364 }
15365
15366 // All the following checks are C++ only.
15367 if (!getLangOpts().CPlusPlus) {
15368 // If this variable must be emitted, add it as an initializer for the
15369 // current module.
15370 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15371 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15372 return;
15373 }
15374
15375 DiagnoseUniqueObjectDuplication(VD: var);
15376
15377 // Require the destructor.
15378 if (!type->isDependentType())
15379 if (auto *RD = baseType->getAsCXXRecordDecl())
15380 FinalizeVarWithDestructor(VD: var, DeclInit: RD);
15381
15382 // If this variable must be emitted, add it as an initializer for the current
15383 // module. For named modules, discardable inline variables may be deferred
15384 // until they are odr-used. Non-inline variables that must be emitted,
15385 // including those with side-effecting initialization, must still be emitted
15386 // even if they have internal linkage.
15387 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty()) {
15388 GVALinkage Linkage = Context.GetGVALinkageForVariable(VD: var);
15389 if (ModuleScopes.back().Module->isHeaderLikeModule() ||
15390 !isDiscardableGVALinkage(L: Linkage) ||
15391 (Linkage == GVA_Internal && !var->isInline()))
15392 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15393 }
15394
15395 // Build the bindings if this is a structured binding declaration.
15396 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
15397 CheckCompleteDecompositionDeclaration(DD);
15398}
15399
15400void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15401 assert(VD->isStaticLocal());
15402
15403 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15404
15405 // Find outermost function when VD is in lambda function.
15406 while (FD && !getDLLAttr(D: FD) &&
15407 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15408 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15409 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
15410 }
15411
15412 if (!FD)
15413 return;
15414
15415 // Static locals inherit dll attributes from their function.
15416 if (Attr *A = getDLLAttr(D: FD)) {
15417 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
15418 NewAttr->setInherited(true);
15419 VD->addAttr(A: NewAttr);
15420 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15421 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15422 NewAttr->setInherited(true);
15423 VD->addAttr(A: NewAttr);
15424
15425 // Export this function to enforce exporting this static variable even
15426 // if it is not used in this compilation unit.
15427 if (!FD->hasAttr<DLLExportAttr>())
15428 FD->addAttr(A: NewAttr);
15429
15430 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15431 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15432 NewAttr->setInherited(true);
15433 VD->addAttr(A: NewAttr);
15434 }
15435}
15436
15437void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15438 assert(VD->getTLSKind());
15439
15440 // Perform TLS alignment check here after attributes attached to the variable
15441 // which may affect the alignment have been processed. Only perform the check
15442 // if the target has a maximum TLS alignment (zero means no constraints).
15443 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15444 // Protect the check so that it's not performed on dependent types and
15445 // dependent alignments (we can't determine the alignment in that case).
15446 if (!VD->hasDependentAlignment()) {
15447 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
15448 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
15449 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
15450 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
15451 << (unsigned)MaxAlignChars.getQuantity();
15452 }
15453 }
15454 }
15455}
15456
15457void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15458 // Note that we are no longer parsing the initializer for this declaration.
15459 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
15460
15461 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
15462 if (!VD)
15463 return;
15464
15465 // Emit any deferred warnings for the variable's initializer, even if the
15466 // variable is invalid
15467 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15468
15469 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15470 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15471 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15472 if (PragmaClangBSSSection.Valid)
15473 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
15474 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
15475 Range: PragmaClangBSSSection.PragmaLocation));
15476 if (PragmaClangDataSection.Valid)
15477 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
15478 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
15479 Range: PragmaClangDataSection.PragmaLocation));
15480 if (PragmaClangRodataSection.Valid)
15481 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
15482 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
15483 Range: PragmaClangRodataSection.PragmaLocation));
15484 if (PragmaClangRelroSection.Valid)
15485 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
15486 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
15487 Range: PragmaClangRelroSection.PragmaLocation));
15488 }
15489
15490 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
15491 for (auto *BD : DD->bindings()) {
15492 FinalizeDeclaration(ThisDecl: BD);
15493 }
15494 }
15495
15496 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
15497 K: BuiltinCountedByRefKind::Initializer);
15498
15499 checkAttributesAfterMerging(S&: *this, ND&: *VD);
15500
15501 if (VD->isStaticLocal())
15502 CheckStaticLocalForDllExport(VD);
15503
15504 if (VD->getTLSKind())
15505 CheckThreadLocalForLargeAlignment(VD);
15506
15507 // Perform check for initializers of device-side global variables.
15508 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15509 // 7.5). We must also apply the same checks to all __shared__
15510 // variables whether they are local or not. CUDA also allows
15511 // constant initializers for __constant__ and __device__ variables.
15512 if (getLangOpts().CUDA)
15513 CUDA().checkAllowedInitializer(VD);
15514
15515 // Grab the dllimport or dllexport attribute off of the VarDecl.
15516 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
15517
15518 // Imported static data members cannot be defined out-of-line.
15519 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
15520 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15521 VD->isThisDeclarationADefinition()) {
15522 // We allow definitions of dllimport class template static data members
15523 // with a warning.
15524 CXXRecordDecl *Context =
15525 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
15526 bool IsClassTemplateMember =
15527 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
15528 Context->getDescribedClassTemplate();
15529
15530 Diag(Loc: VD->getLocation(),
15531 DiagID: IsClassTemplateMember
15532 ? diag::warn_attribute_dllimport_static_field_definition
15533 : diag::err_attribute_dllimport_static_field_definition);
15534 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
15535 if (!IsClassTemplateMember)
15536 VD->setInvalidDecl();
15537 }
15538 }
15539
15540 // dllimport/dllexport variables cannot be thread local, their TLS index
15541 // isn't exported with the variable.
15542 if (DLLAttr && VD->getTLSKind()) {
15543 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15544 if (F && getDLLAttr(D: F)) {
15545 assert(VD->isStaticLocal());
15546 // But if this is a static local in a dlimport/dllexport function, the
15547 // function will never be inlined, which means the var would never be
15548 // imported, so having it marked import/export is safe.
15549 } else {
15550 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15551 << DLLAttr;
15552 VD->setInvalidDecl();
15553 }
15554 }
15555
15556 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15557 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15558 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15559 << Attr;
15560 VD->dropAttr<UsedAttr>();
15561 }
15562 }
15563 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15564 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15565 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15566 << Attr;
15567 VD->dropAttr<RetainAttr>();
15568 }
15569 }
15570
15571 const DeclContext *DC = VD->getDeclContext();
15572 // If there's a #pragma GCC visibility in scope, and this isn't a class
15573 // member, set the visibility of this variable.
15574 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15575 AddPushedVisibilityAttribute(RD: VD);
15576
15577 // FIXME: Warn on unused var template partial specializations.
15578 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15579 MarkUnusedFileScopedDecl(D: VD);
15580
15581 // Now we have parsed the initializer and can update the table of magic
15582 // tag values.
15583 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15584 !VD->getType()->isIntegralOrEnumerationType())
15585 return;
15586
15587 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15588 const Expr *MagicValueExpr = VD->getInit();
15589 if (!MagicValueExpr) {
15590 continue;
15591 }
15592 std::optional<llvm::APSInt> MagicValueInt;
15593 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15594 Diag(Loc: I->getRange().getBegin(),
15595 DiagID: diag::err_type_tag_for_datatype_not_ice)
15596 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15597 continue;
15598 }
15599 if (MagicValueInt->getActiveBits() > 64) {
15600 Diag(Loc: I->getRange().getBegin(),
15601 DiagID: diag::err_type_tag_for_datatype_too_large)
15602 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15603 continue;
15604 }
15605 uint64_t MagicValue = MagicValueInt->getZExtValue();
15606 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15607 MagicValue,
15608 Type: I->getMatchingCType(),
15609 LayoutCompatible: I->getLayoutCompatible(),
15610 MustBeNull: I->getMustBeNull());
15611 }
15612}
15613
15614static bool hasDeducedAuto(DeclaratorDecl *DD) {
15615 auto *VD = dyn_cast<VarDecl>(Val: DD);
15616 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15617}
15618
15619Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15620 ArrayRef<Decl *> Group) {
15621 SmallVector<Decl*, 8> Decls;
15622
15623 if (DS.isTypeSpecOwned())
15624 Decls.push_back(Elt: DS.getRepAsDecl());
15625
15626 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15627 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15628 bool DiagnosedMultipleDecomps = false;
15629 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15630 bool DiagnosedNonDeducedAuto = false;
15631
15632 for (Decl *D : Group) {
15633 if (!D)
15634 continue;
15635 // Check if the Decl has been declared in '#pragma omp declare target'
15636 // directive and has static storage duration.
15637 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15638 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15639 VD->hasGlobalStorage())
15640 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15641 // For declarators, there are some additional syntactic-ish checks we need
15642 // to perform.
15643 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15644 if (!FirstDeclaratorInGroup)
15645 FirstDeclaratorInGroup = DD;
15646 if (!FirstDecompDeclaratorInGroup)
15647 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15648 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15649 !hasDeducedAuto(DD))
15650 FirstNonDeducedAutoInGroup = DD;
15651
15652 if (FirstDeclaratorInGroup != DD) {
15653 // A decomposition declaration cannot be combined with any other
15654 // declaration in the same group.
15655 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15656 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15657 DiagID: diag::err_decomp_decl_not_alone)
15658 << FirstDeclaratorInGroup->getSourceRange()
15659 << DD->getSourceRange();
15660 DiagnosedMultipleDecomps = true;
15661 }
15662
15663 // A declarator that uses 'auto' in any way other than to declare a
15664 // variable with a deduced type cannot be combined with any other
15665 // declarator in the same group.
15666 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15667 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15668 DiagID: diag::err_auto_non_deduced_not_alone)
15669 << FirstNonDeducedAutoInGroup->getType()
15670 ->hasAutoForTrailingReturnType()
15671 << FirstDeclaratorInGroup->getSourceRange()
15672 << DD->getSourceRange();
15673 DiagnosedNonDeducedAuto = true;
15674 }
15675 }
15676 }
15677
15678 Decls.push_back(Elt: D);
15679 }
15680
15681 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15682 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15683 handleTagNumbering(Tag, TagScope: S);
15684 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15685 getLangOpts().CPlusPlus)
15686 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15687 }
15688 }
15689
15690 return BuildDeclaratorGroup(Group: Decls);
15691}
15692
15693Sema::DeclGroupPtrTy
15694Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15695 // C++14 [dcl.spec.auto]p7: (DR1347)
15696 // If the type that replaces the placeholder type is not the same in each
15697 // deduction, the program is ill-formed.
15698 if (Group.size() > 1) {
15699 QualType Deduced;
15700 VarDecl *DeducedDecl = nullptr;
15701 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15702 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15703 if (!D || D->isInvalidDecl())
15704 break;
15705 DeducedType *DT = D->getType()->getContainedDeducedType();
15706 if (!DT || DT->getDeducedType().isNull())
15707 continue;
15708 if (Deduced.isNull()) {
15709 Deduced = DT->getDeducedType();
15710 DeducedDecl = D;
15711 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15712 auto *AT = dyn_cast<AutoType>(Val: DT);
15713 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15714 DiagID: diag::err_auto_different_deductions)
15715 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15716 << DeducedDecl->getDeclName() << DT->getDeducedType()
15717 << D->getDeclName();
15718 if (DeducedDecl->hasInit())
15719 Dia << DeducedDecl->getInit()->getSourceRange();
15720 if (D->getInit())
15721 Dia << D->getInit()->getSourceRange();
15722 D->setInvalidDecl();
15723 break;
15724 }
15725 }
15726 }
15727
15728 ActOnDocumentableDecls(Group);
15729
15730 return DeclGroupPtrTy::make(
15731 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15732}
15733
15734void Sema::ActOnDocumentableDecl(Decl *D) {
15735 ActOnDocumentableDecls(Group: D);
15736}
15737
15738void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15739 // Don't parse the comment if Doxygen diagnostics are ignored.
15740 if (Group.empty() || !Group[0])
15741 return;
15742
15743 if (Diags.isIgnored(DiagID: diag::warn_doc_param_not_found,
15744 Loc: Group[0]->getLocation()) &&
15745 Diags.isIgnored(DiagID: diag::warn_unknown_comment_command_name,
15746 Loc: Group[0]->getLocation()))
15747 return;
15748
15749 if (Group.size() >= 2) {
15750 // This is a decl group. Normally it will contain only declarations
15751 // produced from declarator list. But in case we have any definitions or
15752 // additional declaration references:
15753 // 'typedef struct S {} S;'
15754 // 'typedef struct S *S;'
15755 // 'struct S *pS;'
15756 // FinalizeDeclaratorGroup adds these as separate declarations.
15757 Decl *MaybeTagDecl = Group[0];
15758 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15759 Group = Group.slice(N: 1);
15760 }
15761 }
15762
15763 // FIXME: We assume every Decl in the group is in the same file.
15764 // This is false when preprocessor constructs the group from decls in
15765 // different files (e. g. macros or #include).
15766 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15767}
15768
15769void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15770 // Check that there are no default arguments inside the type of this
15771 // parameter.
15772 if (getLangOpts().CPlusPlus)
15773 CheckExtraCXXDefaultArguments(D);
15774
15775 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15776 if (D.getCXXScopeSpec().isSet()) {
15777 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15778 << D.getCXXScopeSpec().getRange();
15779 }
15780
15781 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15782 // simple identifier except [...irrelevant cases...].
15783 switch (D.getName().getKind()) {
15784 case UnqualifiedIdKind::IK_Identifier:
15785 break;
15786
15787 case UnqualifiedIdKind::IK_OperatorFunctionId:
15788 case UnqualifiedIdKind::IK_ConversionFunctionId:
15789 case UnqualifiedIdKind::IK_LiteralOperatorId:
15790 case UnqualifiedIdKind::IK_ConstructorName:
15791 case UnqualifiedIdKind::IK_DestructorName:
15792 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15793 case UnqualifiedIdKind::IK_DeductionGuideName:
15794 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15795 << GetNameForDeclarator(D).getName();
15796 break;
15797
15798 case UnqualifiedIdKind::IK_TemplateId:
15799 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15800 // GetNameForDeclarator would not produce a useful name in this case.
15801 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15802 break;
15803 }
15804}
15805
15806void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15807 // This only matters in C.
15808 if (getLangOpts().CPlusPlus)
15809 return;
15810
15811 // This only matters if the declaration has a type.
15812 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15813 if (!VD)
15814 return;
15815
15816 // Get the type, this only matters for tag types.
15817 QualType QT = VD->getType();
15818 const auto *TD = QT->getAsTagDecl();
15819 if (!TD)
15820 return;
15821
15822 // Check if the tag declaration is lexically declared somewhere different
15823 // from the lexical declaration of the given object, then it will be hidden
15824 // in C++ and we should warn on it.
15825 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15826 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15827 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15828 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15829 }
15830}
15831
15832static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15833 SourceLocation ExplicitThisLoc) {
15834 if (!ExplicitThisLoc.isValid())
15835 return;
15836 assert(S.getLangOpts().CPlusPlus &&
15837 "explicit parameter in non-cplusplus mode");
15838 if (!S.getLangOpts().CPlusPlus23)
15839 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15840 << P->getSourceRange();
15841
15842 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15843 // parameter pack.
15844 if (P->isParameterPack()) {
15845 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15846 << P->getSourceRange();
15847 return;
15848 }
15849 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15850 if (LambdaScopeInfo *LSI = S.getCurLambda())
15851 LSI->ExplicitObjectParameter = P;
15852}
15853
15854Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15855 SourceLocation ExplicitThisLoc) {
15856 const DeclSpec &DS = D.getDeclSpec();
15857
15858 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15859 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15860 // except for the special case of a single unnamed parameter of type void
15861 // with no storage class specifier, no type qualifier, and no following
15862 // ellipsis terminator.
15863 // Clang applies the C2y rules for 'register void' in all C language modes,
15864 // same as GCC, because it's questionable what that could possibly mean.
15865
15866 // C++03 [dcl.stc]p2 also permits 'auto'.
15867 StorageClass SC = SC_None;
15868 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15869 SC = SC_Register;
15870 // In C++11, the 'register' storage class specifier is deprecated.
15871 // In C++17, it is not allowed, but we tolerate it as an extension.
15872 if (getLangOpts().CPlusPlus11) {
15873 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15874 ? diag::ext_register_storage_class
15875 : diag::warn_deprecated_register)
15876 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15877 } else if (!getLangOpts().CPlusPlus &&
15878 DS.getTypeSpecType() == DeclSpec::TST_void &&
15879 D.getNumTypeObjects() == 0) {
15880 Diag(Loc: DS.getStorageClassSpecLoc(),
15881 DiagID: diag::err_invalid_storage_class_in_func_decl)
15882 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15883 D.getMutableDeclSpec().ClearStorageClassSpecs();
15884 }
15885 } else if (getLangOpts().CPlusPlus &&
15886 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15887 SC = SC_Auto;
15888 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15889 Diag(Loc: DS.getStorageClassSpecLoc(),
15890 DiagID: diag::err_invalid_storage_class_in_func_decl);
15891 D.getMutableDeclSpec().ClearStorageClassSpecs();
15892 }
15893
15894 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15895 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15896 << DeclSpec::getSpecifierName(S: TSCS);
15897 if (DS.isInlineSpecified())
15898 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15899 << getLangOpts().CPlusPlus17;
15900 if (DS.hasConstexprSpecifier())
15901 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15902 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15903
15904 DiagnoseFunctionSpecifiers(DS);
15905
15906 CheckFunctionOrTemplateParamDeclarator(S, D);
15907
15908 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15909 QualType parmDeclType = TInfo->getType();
15910
15911 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15912 const IdentifierInfo *II = D.getIdentifier();
15913 if (II) {
15914 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15915 RedeclarationKind::ForVisibleRedeclaration);
15916 LookupName(R, S);
15917 if (!R.empty()) {
15918 NamedDecl *PrevDecl = *R.begin();
15919 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15920 // Maybe we will complain about the shadowed template parameter.
15921 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
15922 // Just pretend that we didn't see the previous declaration.
15923 PrevDecl = nullptr;
15924 }
15925 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
15926 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
15927 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
15928 // Recover by removing the name
15929 II = nullptr;
15930 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15931 D.setInvalidType(true);
15932 }
15933 }
15934 }
15935
15936 // Incomplete resource arrays are not allowed as function parameters in HLSL
15937 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType()) {
15938 QualType EltTy = Context.getBaseElementType(QT: parmDeclType);
15939 // `isCompleteType` forces completion of the element type so the resource
15940 // check is valid.
15941 if (!EltTy->isDependentType() &&
15942 isCompleteType(Loc: D.getIdentifierLoc(), T: EltTy) &&
15943 parmDeclType->isHLSLResourceRecordArray()) {
15944 Diag(Loc: D.getIdentifierLoc(),
15945 DiagID: diag::err_hlsl_incomplete_resource_array_in_function_param);
15946 D.setInvalidType(true);
15947 }
15948 }
15949
15950 // Temporarily put parameter variables in the translation unit, not
15951 // the enclosing context. This prevents them from accidentally
15952 // looking like class members in C++.
15953 ParmVarDecl *New =
15954 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
15955 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
15956
15957 if (D.isInvalidType())
15958 New->setInvalidDecl();
15959
15960 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15961
15962 assert(S->isFunctionPrototypeScope());
15963 assert(S->getFunctionPrototypeDepth() >= 1);
15964 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15965 parameterIndex: S->getNextFunctionPrototypeIndex());
15966
15967 warnOnCTypeHiddenInCPlusPlus(D: New);
15968
15969 // Add the parameter declaration into this scope.
15970 S->AddDecl(D: New);
15971 if (II)
15972 IdResolver.AddDecl(D: New);
15973
15974 ProcessDeclAttributes(S, D: New, PD: D);
15975
15976 if (D.getDeclSpec().isModulePrivateSpecified())
15977 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
15978 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15979 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
15980
15981 if (New->hasAttr<BlocksAttr>())
15982 Diag(Loc: New->getLocation(), DiagID: diag::err_block_not_allowed_on)
15983 << diag::NotAllowedBlockVarReason::NonlocalVariable;
15984
15985 New->deduceParmAddressSpace(Ctxt: Context);
15986
15987 return New;
15988}
15989
15990ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15991 SourceLocation Loc,
15992 QualType T) {
15993 /* FIXME: setting StartLoc == Loc.
15994 Would it be worth to modify callers so as to provide proper source
15995 location for the unnamed parameters, embedding the parameter's type? */
15996 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15997 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15998 S: SC_None, DefArg: nullptr);
15999 Param->setImplicit();
16000 return Param;
16001}
16002
16003void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
16004 // Don't diagnose unused-parameter errors in template instantiations; we
16005 // will already have done so in the template itself.
16006 if (inTemplateInstantiation())
16007 return;
16008
16009 for (const ParmVarDecl *Parameter : Parameters) {
16010 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
16011 !Parameter->hasAttr<UnusedAttr>() &&
16012 !Parameter->getIdentifier()->isPlaceholder()) {
16013 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
16014 << Parameter->getDeclName();
16015 }
16016 }
16017}
16018
16019void Sema::DiagnoseSizeOfParametersAndReturnValue(
16020 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
16021 if (LangOpts.NumLargeByValueCopy == 0) // No check.
16022 return;
16023
16024 // Warn if the return value is pass-by-value and larger than the specified
16025 // threshold.
16026 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
16027 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
16028 if (Size > LangOpts.NumLargeByValueCopy)
16029 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
16030 }
16031
16032 // Warn if any parameter is pass-by-value and larger than the specified
16033 // threshold.
16034 for (const ParmVarDecl *Parameter : Parameters) {
16035 QualType T = Parameter->getType();
16036 if (T->isDependentType() || !T.isPODType(Context))
16037 continue;
16038 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
16039 if (Size > LangOpts.NumLargeByValueCopy)
16040 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
16041 << Parameter << Size;
16042 }
16043}
16044
16045ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
16046 SourceLocation NameLoc,
16047 const IdentifierInfo *Name, QualType T,
16048 TypeSourceInfo *TSInfo, StorageClass SC) {
16049 // In ARC, infer a lifetime qualifier for appropriate parameter types.
16050 if (getLangOpts().ObjCAutoRefCount &&
16051 T.getObjCLifetime() == Qualifiers::OCL_None &&
16052 T->isObjCLifetimeType()) {
16053
16054 Qualifiers::ObjCLifetime lifetime;
16055
16056 // Special cases for arrays:
16057 // - if it's const, use __unsafe_unretained
16058 // - otherwise, it's an error
16059 if (T->isArrayType()) {
16060 if (!T.isConstQualified()) {
16061 if (DelayedDiagnostics.shouldDelayDiagnostics())
16062 DelayedDiagnostics.add(
16063 diag: sema::DelayedDiagnostic::makeForbiddenType(
16064 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
16065 else
16066 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
16067 << TSInfo->getTypeLoc().getSourceRange();
16068 }
16069 lifetime = Qualifiers::OCL_ExplicitNone;
16070 } else {
16071 lifetime = T->getObjCARCImplicitLifetime();
16072 }
16073 T = Context.getLifetimeQualifiedType(type: T, lifetime);
16074 }
16075
16076 if (getLangOpts().OpenCL) {
16077 assert(!isa<DecayedType>(T));
16078 if (T->isArrayType() && !T.hasAddressSpace()) {
16079 QualType ET = Context.getAsArrayType(T)->getElementType();
16080 if (!ET.hasAddressSpace()) {
16081 // Add the private address space to the contents of the pointer when a
16082 // pointer parameter is declared as an array and not declared.
16083 LangAS ImplAS = LangAS::opencl_private;
16084 T = Context.getAddrSpaceQualType(T, AddressSpace: ImplAS);
16085 T = QualType(Context.getAsArrayType(T), 0);
16086 }
16087 }
16088 }
16089
16090 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
16091 T: Context.getAdjustedParameterType(T),
16092 TInfo: TSInfo, S: SC, DefArg: nullptr);
16093
16094 // Make a note if we created a new pack in the scope of a lambda, so that
16095 // we know that references to that pack must also be expanded within the
16096 // lambda scope.
16097 if (New->isParameterPack())
16098 if (auto *CSI = getEnclosingLambdaOrBlock())
16099 CSI->LocalPacks.push_back(Elt: New);
16100
16101 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16102 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
16103 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
16104 UseContext: NonTrivialCUnionContext::FunctionParam,
16105 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
16106
16107 // Parameter declarators cannot be interface types. All ObjC objects are
16108 // passed by reference.
16109 if (T->isObjCObjectType()) {
16110 SourceLocation TypeEndLoc =
16111 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
16112 Diag(Loc: NameLoc,
16113 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
16114 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
16115 T = Context.getObjCObjectPointerType(OIT: T);
16116 New->setType(T);
16117 }
16118
16119 // __ptrauth is forbidden on parameters.
16120 if (T.getPointerAuth()) {
16121 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
16122 New->setInvalidDecl();
16123 }
16124
16125 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
16126 // duration shall not be qualified by an address-space qualifier."
16127 // Since all parameters have automatic store duration, they can not have
16128 // an address space.
16129 if (T.getAddressSpace() != LangAS::Default &&
16130 // OpenCL allows function arguments declared to be an array of a type
16131 // to be qualified with an address space.
16132 !(getLangOpts().OpenCL &&
16133 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
16134 // WebAssembly allows reference types as parameters. Funcref in particular
16135 // lives in a different address space.
16136 !(T->isFunctionPointerType() &&
16137 T.getAddressSpace() == LangAS::wasm_funcref) &&
16138 // HLSL allows function arguments to be qualified with an address space
16139 // if the groupshared annotation is used.
16140 !(getLangOpts().HLSL &&
16141 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
16142 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
16143 New->setInvalidDecl();
16144 }
16145
16146 // PPC MMA non-pointer types are not allowed as function argument types.
16147 if (Context.getTargetInfo().getTriple().isPPC64() &&
16148 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
16149 New->setInvalidDecl();
16150 }
16151
16152 return New;
16153}
16154
16155void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
16156 SourceLocation LocAfterDecls) {
16157 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
16158
16159 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
16160 // in the declaration list shall have at least one declarator, those
16161 // declarators shall only declare identifiers from the identifier list, and
16162 // every identifier in the identifier list shall be declared.
16163 //
16164 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
16165 // identifiers it names shall be declared in the declaration list."
16166 //
16167 // This is why we only diagnose in C99 and later. Note, the other conditions
16168 // listed are checked elsewhere.
16169 if (!FTI.hasPrototype) {
16170 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
16171 --i;
16172 if (FTI.Params[i].Param == nullptr) {
16173 if (getLangOpts().C99) {
16174 SmallString<256> Code;
16175 llvm::raw_svector_ostream(Code)
16176 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16177 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
16178 << FTI.Params[i].Ident
16179 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
16180 }
16181
16182 // Implicitly declare the argument as type 'int' for lack of a better
16183 // type.
16184 AttributeFactory attrs;
16185 DeclSpec DS(attrs);
16186 const char* PrevSpec; // unused
16187 unsigned DiagID; // unused
16188 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
16189 DiagID, Policy: Context.getPrintingPolicy());
16190 // Use the identifier location for the type source range.
16191 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16192 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16193 Declarator ParamD(DS, ParsedAttributesView::none(),
16194 DeclaratorContext::KNRTypeList);
16195 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
16196 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
16197 }
16198 }
16199 }
16200}
16201
16202Decl *
16203Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
16204 MultiTemplateParamsArg TemplateParameterLists,
16205 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16206 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16207 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16208 Scope *ParentScope = FnBodyScope->getParent();
16209
16210 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16211 // we define a non-templated function definition, we will create a declaration
16212 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16213 // The base function declaration will have the equivalent of an `omp declare
16214 // variant` annotation which specifies the mangled definition as a
16215 // specialization function under the OpenMP context defined as part of the
16216 // `omp begin declare variant`.
16217 SmallVector<FunctionDecl *, 4> Bases;
16218 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16219 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
16220 S: ParentScope, D, TemplateParameterLists, Bases);
16221
16222 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
16223 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
16224 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
16225
16226 if (!Bases.empty())
16227 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
16228 Bases);
16229
16230 return Dcl;
16231}
16232
16233void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
16234 Consumer.HandleInlineFunctionDefinition(D);
16235}
16236
16237static bool FindPossiblePrototype(const FunctionDecl *FD,
16238 const FunctionDecl *&PossiblePrototype) {
16239 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16240 Prev = Prev->getPreviousDecl()) {
16241 // Ignore any declarations that occur in function or method
16242 // scope, because they aren't visible from the header.
16243 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16244 continue;
16245
16246 PossiblePrototype = Prev;
16247 return Prev->getType()->isFunctionProtoType();
16248 }
16249 return false;
16250}
16251
16252static bool
16253ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
16254 const FunctionDecl *&PossiblePrototype) {
16255 // Don't warn about invalid declarations.
16256 if (FD->isInvalidDecl())
16257 return false;
16258
16259 // Or declarations that aren't global.
16260 if (!FD->isGlobal())
16261 return false;
16262
16263 // Don't warn about C++ member functions.
16264 if (isa<CXXMethodDecl>(Val: FD))
16265 return false;
16266
16267 // Don't warn about 'main'.
16268 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
16269 if (IdentifierInfo *II = FD->getIdentifier())
16270 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
16271 return false;
16272
16273 if (FD->isMSVCRTEntryPoint())
16274 return false;
16275
16276 // Don't warn about inline functions.
16277 if (FD->isInlined())
16278 return false;
16279
16280 // Don't warn about function templates.
16281 if (FD->getDescribedFunctionTemplate())
16282 return false;
16283
16284 // Don't warn about function template specializations.
16285 if (FD->isFunctionTemplateSpecialization())
16286 return false;
16287
16288 // Don't warn for OpenCL kernels.
16289 if (FD->hasAttr<DeviceKernelAttr>())
16290 return false;
16291
16292 // Don't warn on explicitly deleted functions.
16293 if (FD->isDeleted())
16294 return false;
16295
16296 // Don't warn on implicitly local functions (such as having local-typed
16297 // parameters).
16298 if (!FD->isExternallyVisible())
16299 return false;
16300
16301 // If we were able to find a potential prototype, don't warn.
16302 if (FindPossiblePrototype(FD, PossiblePrototype))
16303 return false;
16304
16305 return true;
16306}
16307
16308void
16309Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
16310 const FunctionDecl *EffectiveDefinition,
16311 SkipBodyInfo *SkipBody) {
16312 const FunctionDecl *Definition = EffectiveDefinition;
16313 if (!Definition &&
16314 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16315 return;
16316
16317 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16318 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16319 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16320 // A merged copy of the same function, instantiated as a member of
16321 // the same class, is OK.
16322 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
16323 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
16324 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
16325 return;
16326 }
16327 }
16328 }
16329
16330 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
16331 return;
16332
16333 // Don't emit an error when this is redefinition of a typo-corrected
16334 // definition.
16335 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
16336 return;
16337
16338 bool DefinitionVisible = false;
16339 if (SkipBody && isRedefinitionAllowedFor(D: Definition, Visible&: DefinitionVisible) &&
16340 (Definition->getFormalLinkage() == Linkage::Internal ||
16341 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16342 !Definition->getTemplateParameterLists().empty())) {
16343 SkipBody->ShouldSkip = true;
16344 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16345 if (!DefinitionVisible) {
16346 if (auto *TD = Definition->getDescribedFunctionTemplate())
16347 makeMergedDefinitionVisible(ND: TD);
16348 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl *>(Definition));
16349 }
16350 return;
16351 }
16352
16353 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16354 Definition->getStorageClass() == SC_Extern)
16355 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
16356 << FD << getLangOpts().CPlusPlus;
16357 else
16358 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
16359
16360 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
16361 FD->setInvalidDecl();
16362}
16363
16364LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16365 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16366
16367 LambdaScopeInfo *LSI = PushLambdaScope();
16368 LSI->CallOperator = CallOperator;
16369 LSI->Lambda = LambdaClass;
16370 LSI->ReturnType = CallOperator->getReturnType();
16371 // When this function is called in situation where the context of the call
16372 // operator is not entered, we set AfterParameterList to false, so that
16373 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16374 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16375 // where we would set the CurContext to the lambda operator before
16376 // substituting into it. In this case the flag needs to be true such that
16377 // tryCaptureVariable can correctly handle potential captures thereof.
16378 LSI->AfterParameterList = CurContext == CallOperator;
16379 LSI->BeforeCompoundStatement = false;
16380
16381 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16382 // used at the point of dealing with potential captures.
16383 //
16384 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16385 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16386 // associated. (Technically, we could recover that list from their
16387 // instantiation patterns, but for now, the GLTemplateParameterList seems
16388 // unnecessary in these cases.)
16389 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16390 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16391 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16392
16393 if (LCD == LCD_None)
16394 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16395 else if (LCD == LCD_ByCopy)
16396 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16397 else if (LCD == LCD_ByRef)
16398 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16399 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16400
16401 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16402 LSI->Mutable = !CallOperator->isConst();
16403 if (CallOperator->isExplicitObjectMemberFunction())
16404 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
16405
16406 // Add the captures to the LSI so they can be noted as already
16407 // captured within tryCaptureVar.
16408 auto I = LambdaClass->field_begin();
16409 for (const auto &C : LambdaClass->captures()) {
16410 if (C.capturesVariable()) {
16411 ValueDecl *VD = C.getCapturedVar();
16412 if (VD->isInitCapture())
16413 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
16414 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16415 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
16416 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
16417 /*EllipsisLoc*/C.isPackExpansion()
16418 ? C.getEllipsisLoc() : SourceLocation(),
16419 CaptureType: I->getType(), /*Invalid*/false);
16420
16421 } else if (C.capturesThis()) {
16422 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
16423 ByCopy: C.getCaptureKind() == LCK_StarThis);
16424 } else {
16425 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
16426 CaptureType: I->getType());
16427 }
16428 ++I;
16429 }
16430 return LSI;
16431}
16432
16433Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16434 SkipBodyInfo *SkipBody,
16435 FnBodyKind BodyKind) {
16436 if (!D) {
16437 // Parsing the function declaration failed in some way. Push on a fake scope
16438 // anyway so we can try to parse the function body.
16439 PushFunctionScope();
16440 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16441 return D;
16442 }
16443
16444 FunctionDecl *FD = nullptr;
16445
16446 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
16447 FD = FunTmpl->getTemplatedDecl();
16448 else
16449 FD = cast<FunctionDecl>(Val: D);
16450
16451 // Do not push if it is a lambda because one is already pushed when building
16452 // the lambda in ActOnStartOfLambdaDefinition().
16453 if (!isLambdaCallOperator(DC: FD))
16454 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
16455 FD);
16456
16457 // Check for defining attributes before the check for redefinition.
16458 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16459 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
16460 FD->dropAttr<AliasAttr>();
16461 FD->setInvalidDecl();
16462 }
16463 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16464 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
16465 FD->dropAttr<IFuncAttr>();
16466 FD->setInvalidDecl();
16467 }
16468 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16469 if (Context.getTargetInfo().getTriple().isAArch64() &&
16470 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
16471 !Attr->isDefaultVersion()) {
16472 // If function multi versioning disabled skip parsing function body
16473 // defined with non-default target_version attribute
16474 if (SkipBody)
16475 SkipBody->ShouldSkip = true;
16476 return nullptr;
16477 }
16478 }
16479
16480 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
16481 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16482 Ctor->isDefaultConstructor() &&
16483 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16484 // If this is an MS ABI dllexport default constructor, instantiate any
16485 // default arguments.
16486 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
16487 BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor);
16488 }
16489 }
16490
16491 // See if this is a redefinition. If 'will have body' (or similar) is already
16492 // set, then these checks were already performed when it was set.
16493 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16494 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16495 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
16496
16497 // If we're skipping the body, we're done. Don't enter the scope.
16498 if (SkipBody && SkipBody->ShouldSkip)
16499 return D;
16500 }
16501
16502 // Mark this function as "will have a body eventually". This lets users to
16503 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16504 // this function.
16505 FD->setWillHaveBody();
16506
16507 // If we are instantiating a generic lambda call operator, push
16508 // a LambdaScopeInfo onto the function stack. But use the information
16509 // that's already been calculated (ActOnLambdaExpr) to prime the current
16510 // LambdaScopeInfo.
16511 // When the template operator is being specialized, the LambdaScopeInfo,
16512 // has to be properly restored so that tryCaptureVariable doesn't try
16513 // and capture any new variables. In addition when calculating potential
16514 // captures during transformation of nested lambdas, it is necessary to
16515 // have the LSI properly restored.
16516 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
16517 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16518 // specialized.
16519 if (FD->getTemplateSpecializationInfo()->isExplicitSpecialization()) {
16520 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_temp_spec)
16521 << /*specialization*/ 0;
16522 CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: FD->getParent());
16523 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
16524
16525 FD->setInvalidDecl();
16526 PushFunctionScope();
16527 } else {
16528 assert(inTemplateInstantiation() &&
16529 "There should be an active template instantiation on the stack "
16530 "when instantiating a generic lambda!");
16531 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
16532 }
16533 } else {
16534 // Enter a new function scope
16535 PushFunctionScope();
16536 }
16537
16538 // Builtin functions cannot be defined.
16539 if (unsigned BuiltinID = FD->getBuiltinID()) {
16540 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
16541 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
16542 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
16543 FD->setInvalidDecl();
16544 }
16545 }
16546
16547 // The return type of a function definition must be complete (C99 6.9.1p3).
16548 // C++23 [dcl.fct.def.general]/p2
16549 // The type of [...] the return for a function definition
16550 // shall not be a (possibly cv-qualified) class type that is incomplete
16551 // or abstract within the function body unless the function is deleted.
16552 QualType ResultType = FD->getReturnType();
16553 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16554 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16555 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
16556 DiagID: diag::err_func_def_incomplete_result) ||
16557 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
16558 DiagID: diag::err_abstract_type_in_decl,
16559 Args: AbstractReturnType)))
16560 FD->setInvalidDecl();
16561
16562 if (FnBodyScope)
16563 PushDeclContext(S: FnBodyScope, DC: FD);
16564
16565 // Check the validity of our function parameters
16566 if (BodyKind != FnBodyKind::Delete)
16567 CheckParmsForFunctionDef(Parameters: FD->parameters(),
16568 /*CheckParameterNames=*/true);
16569
16570 // Add non-parameter declarations already in the function to the current
16571 // scope.
16572 if (FnBodyScope) {
16573 for (Decl *NPD : FD->decls()) {
16574 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16575 if (!NonParmDecl)
16576 continue;
16577 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16578 "parameters should not be in newly created FD yet");
16579
16580 // If the decl has a name, make it accessible in the current scope.
16581 if (NonParmDecl->getDeclName())
16582 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16583
16584 // Similarly, dive into enums and fish their constants out, making them
16585 // accessible in this scope.
16586 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16587 for (auto *EI : ED->enumerators())
16588 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16589 }
16590 }
16591 }
16592
16593 // Introduce our parameters into the function scope
16594 for (auto *Param : FD->parameters()) {
16595 Param->setOwningFunction(FD);
16596
16597 // If this has an identifier, add it to the scope stack.
16598 if (Param->getIdentifier() && FnBodyScope) {
16599 CheckShadow(S: FnBodyScope, D: Param);
16600
16601 PushOnScopeChains(D: Param, S: FnBodyScope);
16602 }
16603 }
16604
16605 // C++ [module.import/6]
16606 // ...
16607 // A header unit shall not contain a definition of a non-inline function or
16608 // variable whose name has external linkage.
16609 //
16610 // Deleted and Defaulted functions are implicitly inline (but the
16611 // inline state is not set at this point, so check the BodyKind explicitly).
16612 // We choose to allow weak & selectany definitions, as they are common in
16613 // headers, and have semantics similar to inline definitions which are allowed
16614 // in header units.
16615 // FIXME: Consider an alternate location for the test where the inlined()
16616 // state is complete.
16617 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16618 !FD->isInvalidDecl() && !FD->isInlined() &&
16619 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16620 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16621 !FD->isTemplateInstantiation() &&
16622 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16623 assert(FD->isThisDeclarationADefinition());
16624 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16625 FD->setInvalidDecl();
16626 }
16627
16628 // Ensure that the function's exception specification is instantiated.
16629 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16630 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16631
16632 // dllimport cannot be applied to non-inline function definitions.
16633 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16634 !FD->isTemplateInstantiation()) {
16635 assert(!FD->hasAttr<DLLExportAttr>());
16636 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16637 FD->setInvalidDecl();
16638 return D;
16639 }
16640
16641 // Some function attributes (like OptimizeNoneAttr) need actions before
16642 // parsing body started.
16643 applyFunctionAttributesBeforeParsingBody(FD: D);
16644
16645 // We want to attach documentation to original Decl (which might be
16646 // a function template).
16647 ActOnDocumentableDecl(D);
16648 if (getCurLexicalContext()->isObjCContainer() &&
16649 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16650 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16651 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16652
16653 maybeAddDeclWithEffects(D: FD);
16654
16655 if (!FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16656 FnBodyScope) {
16657 // An implicit call expression is synthesized for functions declared with
16658 // the sycl_kernel_entry_point attribute. The call may resolve to a
16659 // function template, a member function template, or a call operator
16660 // of a variable template depending on the results of unqualified lookup
16661 // for 'sycl_kernel_launch' from the beginning of the function body.
16662 // Performing that lookup requires the stack of parsing scopes active
16663 // when the definition is parsed and is thus done here; the result is
16664 // cached in FunctionScopeInfo and used to synthesize the (possibly
16665 // unresolved) call expression after the function body has been parsed.
16666 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16667 if (!SKEPAttr->isInvalidAttr()) {
16668 ExprResult LaunchIdExpr =
16669 SYCL().BuildSYCLKernelLaunchIdExpr(FD, KernelName: SKEPAttr->getKernelName());
16670 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16671 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16672 // treated as an error in the definition of 'FD'; treating it as an error
16673 // of the declaration would affect overload resolution which would
16674 // potentially result in additional errors. If construction of
16675 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16676 // a null pointer value below; that is expected.
16677 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16678 }
16679 }
16680
16681 return D;
16682}
16683
16684void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16685 if (!FD || FD->isInvalidDecl())
16686 return;
16687 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16688 FD = TD->getTemplatedDecl();
16689 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16690 FPOptionsOverride FPO;
16691 FPO.setDisallowOptimizations();
16692 CurFPFeatures.applyChanges(FPO);
16693 FpPragmaStack.CurrentValue =
16694 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16695 }
16696}
16697
16698void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16699 ReturnStmt **Returns = Scope->Returns.data();
16700
16701 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16702 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16703 if (!NRVOCandidate->isNRVOVariable()) {
16704 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16705 DiagID: diag::warn_not_eliding_copy_on_return);
16706 Returns[I]->setNRVOCandidate(nullptr);
16707 }
16708 }
16709 }
16710}
16711
16712bool Sema::canDelayFunctionBody(const Declarator &D) {
16713 // We can't delay parsing the body of a constexpr function template (yet).
16714 if (D.getDeclSpec().hasConstexprSpecifier())
16715 return false;
16716
16717 // We can't delay parsing the body of a function template with a deduced
16718 // return type (yet).
16719 if (D.getDeclSpec().hasAutoTypeSpec()) {
16720 // If the placeholder introduces a non-deduced trailing return type,
16721 // we can still delay parsing it.
16722 if (D.getNumTypeObjects()) {
16723 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16724 if (Outer.Kind == DeclaratorChunk::Function &&
16725 Outer.Fun.hasTrailingReturnType()) {
16726 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16727 return Ty.isNull() || !Ty->isUndeducedType();
16728 }
16729 }
16730 return false;
16731 }
16732
16733 return true;
16734}
16735
16736bool Sema::canSkipFunctionBody(Decl *D) {
16737 // We cannot skip the body of a function (or function template) which is
16738 // constexpr, since we may need to evaluate its body in order to parse the
16739 // rest of the file.
16740 // We cannot skip the body of a function with an undeduced return type,
16741 // because any callers of that function need to know the type.
16742 if (const FunctionDecl *FD = D->getAsFunction()) {
16743 if (FD->isConstexpr())
16744 return false;
16745 // We can't simply call Type::isUndeducedType here, because inside template
16746 // auto can be deduced to a dependent type, which is not considered
16747 // "undeduced".
16748 if (FD->getReturnType()->getContainedDeducedType())
16749 return false;
16750 }
16751 return Consumer.shouldSkipFunctionBody(D);
16752}
16753
16754Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16755 if (!Decl)
16756 return nullptr;
16757 if (FunctionDecl *FD = Decl->getAsFunction())
16758 FD->setHasSkippedBody();
16759 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16760 MD->setHasSkippedBody();
16761 return Decl;
16762}
16763
16764/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16765/// body.
16766class ExitFunctionBodyRAII {
16767public:
16768 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16769 ~ExitFunctionBodyRAII() {
16770 if (!IsLambda)
16771 S.PopExpressionEvaluationContext();
16772 }
16773
16774private:
16775 Sema &S;
16776 bool IsLambda = false;
16777};
16778
16779static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16780 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16781
16782 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16783 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16784 if (!Inserted)
16785 return It->second;
16786
16787 bool R = false;
16788 const BlockDecl *CurBD = BD;
16789
16790 do {
16791 R = !CurBD->doesNotEscape();
16792 if (R)
16793 break;
16794 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16795 } while (CurBD);
16796
16797 return It->second = R;
16798 };
16799
16800 // If the location where 'self' is implicitly retained is inside a escaping
16801 // block, emit a diagnostic.
16802 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16803 S.ImplicitlyRetainedSelfLocs)
16804 if (IsOrNestedInEscapingBlock(P.second))
16805 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16806 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16807}
16808
16809static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16810 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16811 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16812}
16813
16814bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16815 return methodHasName(FD, Name: "get_return_object");
16816}
16817
16818bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16819 return FD->isStatic() &&
16820 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16821}
16822
16823void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16824 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16825 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16826 return;
16827 // Allow some_promise_type::get_return_object().
16828 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16829 return;
16830 if (!FD->hasAttr<CoroWrapperAttr>())
16831 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16832}
16833
16834Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16835 bool RetainFunctionScopeInfo) {
16836 FunctionScopeInfo *FSI = getCurFunction();
16837 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16838
16839 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16840 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16841
16842 SourceLocation AnalysisLoc;
16843 if (Body)
16844 AnalysisLoc = Body->getEndLoc();
16845 else if (FD)
16846 AnalysisLoc = FD->getEndLoc();
16847 sema::AnalysisBasedWarnings::Policy WP =
16848 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16849 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16850
16851 // If we skip function body, we can't tell if a function is a coroutine.
16852 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16853 if (FSI->isCoroutine())
16854 CheckCompletedCoroutineBody(FD, Body);
16855 else
16856 CheckCoroutineWrapper(FD);
16857 }
16858
16859 // Diagnose invalid SYCL kernel entry point function declarations
16860 // and build SYCLKernelCallStmts for valid ones.
16861 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16862 SYCLKernelEntryPointAttr *SKEPAttr =
16863 FD->getAttr<SYCLKernelEntryPointAttr>();
16864 if (FD->isDefaulted()) {
16865 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16866 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16867 SKEPAttr->setInvalidAttr();
16868 } else if (FD->isDeleted()) {
16869 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16870 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16871 SKEPAttr->setInvalidAttr();
16872 } else if (FSI->isCoroutine()) {
16873 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16874 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16875 SKEPAttr->setInvalidAttr();
16876 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16877 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16878 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16879 SKEPAttr->setInvalidAttr();
16880 }
16881
16882 // Build an unresolved SYCL kernel call statement for a function template,
16883 // validate that a SYCL kernel call statement was instantiated for an
16884 // (implicit or explicit) instantiation of a function template, or otherwise
16885 // build a (resolved) SYCL kernel call statement for a non-templated
16886 // function or an explicit specialization.
16887 if (Body && !SKEPAttr->isInvalidAttr()) {
16888 StmtResult SR;
16889 if (FD->isTemplateInstantiation()) {
16890 // The function body should already be a SYCLKernelCallStmt in this
16891 // case, but might not be if there were previous errors.
16892 SR = Body;
16893 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16894 // If name lookup for a template named sycl_kernel_launch failed
16895 // earlier, don't try to build a SYCL kernel call statement as that
16896 // would cause additional errors to be issued; just proceed with the
16897 // original function body.
16898 SR = Body;
16899 } else if (FD->isTemplated()) {
16900 SR = SYCL().BuildUnresolvedSYCLKernelCallStmt(
16901 Body: cast<CompoundStmt>(Val: Body), LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16902 } else {
16903 SR = SYCL().BuildSYCLKernelCallStmt(
16904 FD, Body: cast<CompoundStmt>(Val: Body),
16905 LaunchIdExpr: getCurFunction()->SYCLKernelLaunchIdExpr);
16906 }
16907 // If construction of the replacement body fails, just continue with the
16908 // original function body. An early error return here is not valid; the
16909 // current declaration context and function scopes must be popped before
16910 // returning.
16911 if (SR.isUsable())
16912 Body = SR.get();
16913 }
16914 }
16915
16916 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16917 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16918 if (FD->isDeletedAsWritten())
16919 Diag(Loc: SEAttr->getLocation(),
16920 DiagID: diag::err_sycl_external_invalid_deleted_function)
16921 << SEAttr;
16922 }
16923
16924 {
16925 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16926 // one is already popped when finishing the lambda in BuildLambdaExpr().
16927 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16928 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
16929 if (FD) {
16930 // The function body and the DefaultedOrDeletedInfo, if present, use
16931 // the same storage; don't overwrite the latter if the former is null
16932 // (the body is initialised to null anyway, so even if the latter isn't
16933 // present, this would still be a no-op).
16934 if (Body)
16935 FD->setBody(Body);
16936 FD->setWillHaveBody(false);
16937
16938 if (getLangOpts().CPlusPlus14) {
16939 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16940 FD->getReturnType()->isUndeducedType()) {
16941 // For a function with a deduced result type to return void,
16942 // the result type as written must be 'auto' or 'decltype(auto)',
16943 // possibly cv-qualified or constrained, but not ref-qualified.
16944 if (!FD->getReturnType()->getAs<AutoType>()) {
16945 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
16946 << FD->getReturnType();
16947 FD->setInvalidDecl();
16948 } else {
16949 // Falling off the end of the function is the same as 'return;'.
16950 Expr *Dummy = nullptr;
16951 if (DeduceFunctionTypeFromReturnExpr(
16952 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16953 AT: FD->getReturnType()->getAs<AutoType>()))
16954 FD->setInvalidDecl();
16955 }
16956 }
16957 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
16958 // In C++11, we don't use 'auto' deduction rules for lambda call
16959 // operators because we don't support return type deduction.
16960 auto *LSI = getCurLambda();
16961 if (LSI->HasImplicitReturnType) {
16962 deduceClosureReturnType(CSI&: *LSI);
16963
16964 // C++11 [expr.prim.lambda]p4:
16965 // [...] if there are no return statements in the compound-statement
16966 // [the deduced type is] the type void
16967 QualType RetType =
16968 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16969
16970 // Update the return type to the deduced type.
16971 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16972 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16973 EPI: Proto->getExtProtoInfo()));
16974 }
16975 }
16976
16977 // If the function implicitly returns zero (like 'main') or is naked,
16978 // don't complain about missing return statements.
16979 // Clang implicitly returns 0 in C89 mode, but that's considered an
16980 // extension. The check is necessary to ensure the expected extension
16981 // warning is emitted in C89 mode.
16982 if ((FD->hasImplicitReturnZero() &&
16983 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16984 FD->hasAttr<NakedAttr>())
16985 WP.disableCheckFallThrough();
16986
16987 // MSVC permits the use of pure specifier (=0) on function definition,
16988 // defined at class scope, warn about this non-standard construct.
16989 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16990 !FD->isOutOfLine())
16991 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
16992
16993 if (!FD->isInvalidDecl()) {
16994 // Don't diagnose unused parameters of defaulted, deleted or naked
16995 // functions.
16996 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16997 !FD->hasAttr<NakedAttr>())
16998 DiagnoseUnusedParameters(Parameters: FD->parameters());
16999 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
17000 ReturnTy: FD->getReturnType(), D: FD);
17001
17002 // If this is a structor, we need a vtable.
17003 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
17004 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
17005 else if (CXXDestructorDecl *Destructor =
17006 dyn_cast<CXXDestructorDecl>(Val: FD))
17007 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
17008
17009 // Try to apply the named return value optimization. We have to check
17010 // if we can do this here because lambdas keep return statements around
17011 // to deduce an implicit return type.
17012 if (FD->getReturnType()->isRecordType() &&
17013 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
17014 computeNRVO(Body, Scope: FSI);
17015 }
17016
17017 // GNU warning -Wmissing-prototypes:
17018 // Warn if a global function is defined without a previous
17019 // prototype declaration. This warning is issued even if the
17020 // definition itself provides a prototype. The aim is to detect
17021 // global functions that fail to be declared in header files.
17022 const FunctionDecl *PossiblePrototype = nullptr;
17023 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
17024 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
17025
17026 if (PossiblePrototype) {
17027 // We found a declaration that is not a prototype,
17028 // but that could be a zero-parameter prototype
17029 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
17030 TypeLoc TL = TI->getTypeLoc();
17031 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
17032 Diag(Loc: PossiblePrototype->getLocation(),
17033 DiagID: diag::note_declaration_not_a_prototype)
17034 << (FD->getNumParams() != 0)
17035 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
17036 InsertionLoc: FTL.getRParenLoc(), Code: "void")
17037 : FixItHint{});
17038 }
17039 } else {
17040 // Returns true if the token beginning at this Loc is `const`.
17041 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
17042 const LangOptions &LangOpts) {
17043 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
17044 if (LocInfo.first.isInvalid())
17045 return false;
17046
17047 bool Invalid = false;
17048 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
17049 if (Invalid)
17050 return false;
17051
17052 if (LocInfo.second > Buffer.size())
17053 return false;
17054
17055 const char *LexStart = Buffer.data() + LocInfo.second;
17056 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
17057
17058 return StartTok.consume_front(Prefix: "const") &&
17059 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
17060 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
17061 };
17062
17063 auto findBeginLoc = [&]() {
17064 // If the return type has `const` qualifier, we want to insert
17065 // `static` before `const` (and not before the typename).
17066 if ((FD->getReturnType()->isAnyPointerType() &&
17067 FD->getReturnType()->getPointeeType().isConstQualified()) ||
17068 FD->getReturnType().isConstQualified()) {
17069 // But only do this if we can determine where the `const` is.
17070
17071 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
17072 getLangOpts()))
17073
17074 return FD->getBeginLoc();
17075 }
17076 return FD->getTypeSpecStartLoc();
17077 };
17078 Diag(Loc: FD->getTypeSpecStartLoc(),
17079 DiagID: diag::note_static_for_internal_linkage)
17080 << /* function */ 1
17081 << (FD->getStorageClass() == SC_None
17082 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
17083 : FixItHint{});
17084 }
17085 }
17086
17087 // We might not have found a prototype because we didn't wish to warn on
17088 // the lack of a missing prototype. Try again without the checks for
17089 // whether we want to warn on the missing prototype.
17090 if (!PossiblePrototype)
17091 (void)FindPossiblePrototype(FD, PossiblePrototype);
17092
17093 // If the function being defined does not have a prototype, then we may
17094 // need to diagnose it as changing behavior in C23 because we now know
17095 // whether the function accepts arguments or not. This only handles the
17096 // case where the definition has no prototype but does have parameters
17097 // and either there is no previous potential prototype, or the previous
17098 // potential prototype also has no actual prototype. This handles cases
17099 // like:
17100 // void f(); void f(a) int a; {}
17101 // void g(a) int a; {}
17102 // See MergeFunctionDecl() for other cases of the behavior change
17103 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
17104 // type without a prototype.
17105 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
17106 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
17107 !PossiblePrototype->isImplicit()))) {
17108 // The function definition has parameters, so this will change behavior
17109 // in C23. If there is a possible prototype, it comes before the
17110 // function definition.
17111 // FIXME: The declaration may have already been diagnosed as being
17112 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
17113 // there's no way to test for the "changes behavior" condition in
17114 // SemaType.cpp when forming the declaration's function type. So, we do
17115 // this awkward dance instead.
17116 //
17117 // If we have a possible prototype and it declares a function with a
17118 // prototype, we don't want to diagnose it; if we have a possible
17119 // prototype and it has no prototype, it may have already been
17120 // diagnosed in SemaType.cpp as deprecated depending on whether
17121 // -Wstrict-prototypes is enabled. If we already warned about it being
17122 // deprecated, add a note that it also changes behavior. If we didn't
17123 // warn about it being deprecated (because the diagnostic is not
17124 // enabled), warn now that it is deprecated and changes behavior.
17125
17126 // This K&R C function definition definitely changes behavior in C23,
17127 // so diagnose it.
17128 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
17129 << /*definition*/ 1 << /* not supported in C23 */ 0;
17130
17131 // If we have a possible prototype for the function which is a user-
17132 // visible declaration, we already tested that it has no prototype.
17133 // This will change behavior in C23. This gets a warning rather than a
17134 // note because it's the same behavior-changing problem as with the
17135 // definition.
17136 if (PossiblePrototype)
17137 Diag(Loc: PossiblePrototype->getLocation(),
17138 DiagID: diag::warn_non_prototype_changes_behavior)
17139 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
17140 << /*definition*/ 1;
17141 }
17142
17143 // Warn on CPUDispatch with an actual body.
17144 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
17145 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
17146 if (!CmpndBody->body_empty())
17147 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
17148 DiagID: diag::warn_dispatch_body_ignored);
17149
17150 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
17151 const CXXMethodDecl *KeyFunction;
17152 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
17153 MD->isVirtual() &&
17154 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
17155 MD == KeyFunction->getCanonicalDecl()) {
17156 // Update the key-function state if necessary for this ABI.
17157 if (FD->isInlined() &&
17158 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
17159 Context.setNonKeyFunction(MD);
17160
17161 // If the newly-chosen key function is already defined, then we
17162 // need to mark the vtable as used retroactively.
17163 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
17164 const FunctionDecl *Definition;
17165 if (KeyFunction && KeyFunction->isDefined(Definition))
17166 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17167 } else {
17168 // We just defined they key function; mark the vtable as used.
17169 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
17170 }
17171 }
17172 }
17173
17174 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
17175 "Function parsing confused");
17176 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
17177 assert(MD == getCurMethodDecl() && "Method parsing confused");
17178 MD->setBody(Body);
17179 if (!MD->isInvalidDecl()) {
17180 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
17181 ReturnTy: MD->getReturnType(), D: MD);
17182
17183 if (Body)
17184 computeNRVO(Body, Scope: FSI);
17185 }
17186 if (FSI->ObjCShouldCallSuper) {
17187 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
17188 << MD->getSelector().getAsString();
17189 FSI->ObjCShouldCallSuper = false;
17190 }
17191 if (FSI->ObjCWarnForNoDesignatedInitChain) {
17192 const ObjCMethodDecl *InitMethod = nullptr;
17193 bool isDesignated =
17194 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
17195 assert(isDesignated && InitMethod);
17196 (void)isDesignated;
17197
17198 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17199 auto IFace = MD->getClassInterface();
17200 if (!IFace)
17201 return false;
17202 auto SuperD = IFace->getSuperClass();
17203 if (!SuperD)
17204 return false;
17205 return SuperD->getIdentifier() ==
17206 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
17207 };
17208 // Don't issue this warning for unavailable inits or direct subclasses
17209 // of NSObject.
17210 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17211 Diag(Loc: MD->getLocation(),
17212 DiagID: diag::warn_objc_designated_init_missing_super_call);
17213 Diag(Loc: InitMethod->getLocation(),
17214 DiagID: diag::note_objc_designated_init_marked_here);
17215 }
17216 FSI->ObjCWarnForNoDesignatedInitChain = false;
17217 }
17218 if (FSI->ObjCWarnForNoInitDelegation) {
17219 // Don't issue this warning for unavailable inits.
17220 if (!MD->isUnavailable())
17221 Diag(Loc: MD->getLocation(),
17222 DiagID: diag::warn_objc_secondary_init_missing_init_call);
17223 FSI->ObjCWarnForNoInitDelegation = false;
17224 }
17225
17226 diagnoseImplicitlyRetainedSelf(S&: *this);
17227 } else {
17228 // Parsing the function declaration failed in some way. Pop the fake scope
17229 // we pushed on.
17230 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17231 return nullptr;
17232 }
17233
17234 if (Body) {
17235 if (FSI->HasPotentialAvailabilityViolations)
17236 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
17237 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17238 AMDGPU().DiagnoseUnguardedBuiltinUsage(FD);
17239 }
17240
17241 assert(!FSI->ObjCShouldCallSuper &&
17242 "This should only be set for ObjC methods, which should have been "
17243 "handled in the block above.");
17244
17245 // Verify and clean out per-function state.
17246 if (Body && (!FD || !FD->isDefaulted())) {
17247 // C++ constructors that have function-try-blocks can't have return
17248 // statements in the handlers of that block. (C++ [except.handle]p14)
17249 // Verify this.
17250 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
17251 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
17252
17253 // Verify that gotos and switch cases don't jump into scopes illegally.
17254 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17255 DiagnoseInvalidJumps(Body);
17256
17257 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
17258 if (!Destructor->getParent()->isDependentType())
17259 CheckDestructor(Destructor);
17260
17261 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
17262 Record: Destructor->getParent());
17263 }
17264
17265 // If any errors have occurred, clear out any temporaries that may have
17266 // been leftover. This ensures that these temporaries won't be picked up
17267 // for deletion in some later function.
17268 if (hasUncompilableErrorOccurred() ||
17269 hasAnyUnrecoverableErrorsInThisFunction() ||
17270 getDiagnostics().getSuppressAllDiagnostics()) {
17271 DiscardCleanupsInEvaluationContext();
17272 }
17273 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
17274 // Since the body is valid, issue any analysis-based warnings that are
17275 // enabled.
17276 ActivePolicy = &WP;
17277 }
17278
17279 if (!IsInstantiation && FD &&
17280 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17281 !FD->isInvalidDecl() &&
17282 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
17283 FD->setInvalidDecl();
17284
17285 if (FD && FD->hasAttr<NakedAttr>()) {
17286 for (const Stmt *S : Body->children()) {
17287 // Allow local register variables without initializer as they don't
17288 // require prologue.
17289 bool RegisterVariables = false;
17290 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
17291 for (const auto *Decl : DS->decls()) {
17292 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
17293 RegisterVariables =
17294 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17295 if (!RegisterVariables)
17296 break;
17297 }
17298 }
17299 }
17300 if (RegisterVariables)
17301 continue;
17302 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
17303 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
17304 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
17305 FD->setInvalidDecl();
17306 break;
17307 }
17308 }
17309 }
17310
17311 assert(ExprCleanupObjects.size() ==
17312 ExprEvalContexts.back().NumCleanupObjects &&
17313 "Leftover temporaries in function");
17314 assert(!Cleanup.exprNeedsCleanups() &&
17315 "Unaccounted cleanups in function");
17316 assert(MaybeODRUseExprs.empty() &&
17317 "Leftover expressions for odr-use checking");
17318 }
17319 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17320 // the declaration context below. Otherwise, we're unable to transform
17321 // 'this' expressions when transforming immediate context functions.
17322
17323 if (FD)
17324 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
17325
17326 if (!IsInstantiation)
17327 PopDeclContext();
17328
17329 if (!RetainFunctionScopeInfo)
17330 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
17331 // If any errors have occurred, clear out any temporaries that may have
17332 // been leftover. This ensures that these temporaries won't be picked up for
17333 // deletion in some later function.
17334 if (hasUncompilableErrorOccurred()) {
17335 DiscardCleanupsInEvaluationContext();
17336 }
17337
17338 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17339 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17340 auto ES = getEmissionStatus(Decl: FD);
17341 if (ES == Sema::FunctionEmissionStatus::Emitted ||
17342 ES == Sema::FunctionEmissionStatus::Unknown)
17343 DeclsToCheckForDeferredDiags.insert(X: FD);
17344 }
17345
17346 if (FD && !FD->isDeleted())
17347 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
17348
17349 return dcl;
17350}
17351
17352/// When we finish delayed parsing of an attribute, we must attach it to the
17353/// relevant Decl.
17354void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
17355 ParsedAttributes &Attrs) {
17356 // Always attach attributes to the underlying decl.
17357 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
17358 D = TD->getTemplatedDecl();
17359 ProcessDeclAttributeList(S, D, AttrList: Attrs);
17360 ProcessAPINotes(D);
17361
17362 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
17363 if (Method->isStatic())
17364 checkThisInStaticMemberFunctionAttributes(Method);
17365}
17366
17367NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
17368 IdentifierInfo &II, Scope *S) {
17369 // It is not valid to implicitly define a function in C23.
17370 assert(LangOpts.implicitFunctionsAllowed() &&
17371 "Implicit function declarations aren't allowed in this language mode");
17372
17373 // Find the scope in which the identifier is injected and the corresponding
17374 // DeclContext.
17375 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17376 // In that case, we inject the declaration into the translation unit scope
17377 // instead.
17378 Scope *BlockScope = S;
17379 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17380 BlockScope = BlockScope->getParent();
17381
17382 // Loop until we find a DeclContext that is either a function/method or the
17383 // translation unit, which are the only two valid places to implicitly define
17384 // a function. This avoids accidentally defining the function within a tag
17385 // declaration, for example.
17386 Scope *ContextScope = BlockScope;
17387 while (!ContextScope->getEntity() ||
17388 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17389 !ContextScope->getEntity()->isTranslationUnit()))
17390 ContextScope = ContextScope->getParent();
17391 ContextRAII SavedContext(*this, ContextScope->getEntity());
17392
17393 // Before we produce a declaration for an implicitly defined
17394 // function, see whether there was a locally-scoped declaration of
17395 // this name as a function or variable. If so, use that
17396 // (non-visible) declaration, and complain about it.
17397 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
17398 if (ExternCPrev) {
17399 // We still need to inject the function into the enclosing block scope so
17400 // that later (non-call) uses can see it.
17401 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
17402
17403 // C89 footnote 38:
17404 // If in fact it is not defined as having type "function returning int",
17405 // the behavior is undefined.
17406 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
17407 !Context.typesAreCompatible(
17408 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
17409 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
17410 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
17411 << ExternCPrev << !getLangOpts().C99;
17412 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
17413 return ExternCPrev;
17414 }
17415 }
17416
17417 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17418 unsigned diag_id;
17419 if (II.getName().starts_with(Prefix: "__builtin_"))
17420 diag_id = diag::warn_builtin_unknown;
17421 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17422 else if (getLangOpts().C99)
17423 diag_id = diag::ext_implicit_function_decl_c99;
17424 else
17425 diag_id = diag::warn_implicit_function_decl;
17426
17427 TypoCorrection Corrected;
17428 // Because typo correction is expensive, only do it if the implicit
17429 // function declaration is going to be treated as an error.
17430 //
17431 // Perform the correction before issuing the main diagnostic, as some
17432 // consumers use typo-correction callbacks to enhance the main diagnostic.
17433 if (S && !ExternCPrev &&
17434 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
17435 DeclFilterCCC<FunctionDecl> CCC{};
17436 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
17437 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
17438 }
17439
17440 Diag(Loc, DiagID: diag_id) << &II;
17441 if (Corrected) {
17442 // If the correction is going to suggest an implicitly defined function,
17443 // skip the correction as not being a particularly good idea.
17444 bool Diagnose = true;
17445 if (const auto *D = Corrected.getCorrectionDecl())
17446 Diagnose = !D->isImplicit();
17447 if (Diagnose)
17448 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
17449 /*ErrorRecovery*/ false);
17450 }
17451
17452 // If we found a prior declaration of this function, don't bother building
17453 // another one. We've already pushed that one into scope, so there's nothing
17454 // more to do.
17455 if (ExternCPrev)
17456 return ExternCPrev;
17457
17458 // Set a Declarator for the implicit definition: int foo();
17459 const char *Dummy;
17460 AttributeFactory attrFactory;
17461 DeclSpec DS(attrFactory);
17462 unsigned DiagID;
17463 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
17464 Policy: Context.getPrintingPolicy());
17465 (void)Error; // Silence warning.
17466 assert(!Error && "Error setting up implicit decl!");
17467 SourceLocation NoLoc;
17468 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17469 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
17470 /*IsAmbiguous=*/false,
17471 /*LParenLoc=*/NoLoc,
17472 /*Params=*/nullptr,
17473 /*NumParams=*/0,
17474 /*EllipsisLoc=*/NoLoc,
17475 /*RParenLoc=*/NoLoc,
17476 /*RefQualifierIsLvalueRef=*/true,
17477 /*RefQualifierLoc=*/NoLoc,
17478 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
17479 /*ESpecRange=*/SourceRange(),
17480 /*Exceptions=*/nullptr,
17481 /*ExceptionRanges=*/nullptr,
17482 /*NumExceptions=*/0,
17483 /*NoexceptExpr=*/nullptr,
17484 /*ExceptionSpecTokens=*/nullptr,
17485 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
17486 TheDeclarator&: D),
17487 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
17488 D.SetIdentifier(Id: &II, IdLoc: Loc);
17489
17490 // Insert this function into the enclosing block scope.
17491 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
17492 FD->setImplicit();
17493
17494 AddKnownFunctionAttributes(FD);
17495
17496 return FD;
17497}
17498
17499void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17500 FunctionDecl *FD) {
17501 if (FD->isInvalidDecl())
17502 return;
17503
17504 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17505 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17506 return;
17507
17508 UnsignedOrNone AlignmentParam = std::nullopt;
17509 bool IsNothrow = false;
17510 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
17511 return;
17512
17513 // C++2a [basic.stc.dynamic.allocation]p4:
17514 // An allocation function that has a non-throwing exception specification
17515 // indicates failure by returning a null pointer value. Any other allocation
17516 // function never returns a null pointer value and indicates failure only by
17517 // throwing an exception [...]
17518 //
17519 // However, -fcheck-new invalidates this possible assumption, so don't add
17520 // NonNull when that is enabled.
17521 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17522 !getLangOpts().CheckNew)
17523 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17524
17525 // C++2a [basic.stc.dynamic.allocation]p2:
17526 // An allocation function attempts to allocate the requested amount of
17527 // storage. [...] If the request succeeds, the value returned by a
17528 // replaceable allocation function is a [...] pointer value p0 different
17529 // from any previously returned value p1 [...]
17530 //
17531 // However, this particular information is being added in codegen,
17532 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17533
17534 // C++2a [basic.stc.dynamic.allocation]p2:
17535 // An allocation function attempts to allocate the requested amount of
17536 // storage. If it is successful, it returns the address of the start of a
17537 // block of storage whose length in bytes is at least as large as the
17538 // requested size.
17539 if (!FD->hasAttr<AllocSizeAttr>()) {
17540 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17541 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17542 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
17543 }
17544
17545 // C++2a [basic.stc.dynamic.allocation]p3:
17546 // For an allocation function [...], the pointer returned on a successful
17547 // call shall represent the address of storage that is aligned as follows:
17548 // (3.1) If the allocation function takes an argument of type
17549 // std​::​align_­val_­t, the storage will have the alignment
17550 // specified by the value of this argument.
17551 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17552 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
17553 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
17554 }
17555
17556 // FIXME:
17557 // C++2a [basic.stc.dynamic.allocation]p3:
17558 // For an allocation function [...], the pointer returned on a successful
17559 // call shall represent the address of storage that is aligned as follows:
17560 // (3.2) Otherwise, if the allocation function is named operator new[],
17561 // the storage is aligned for any object that does not have
17562 // new-extended alignment ([basic.align]) and is no larger than the
17563 // requested size.
17564 // (3.3) Otherwise, the storage is aligned for any object that does not
17565 // have new-extended alignment and is of the requested size.
17566}
17567
17568void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17569 if (FD->isInvalidDecl())
17570 return;
17571
17572 // If this is a built-in function, map its builtin attributes to
17573 // actual attributes.
17574 if (unsigned BuiltinID = FD->getBuiltinID()) {
17575 // Handle printf-formatting attributes.
17576 unsigned FormatIdx;
17577 bool HasVAListArg;
17578 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17579 if (!FD->hasAttr<FormatAttr>()) {
17580 const char *fmt = "printf";
17581 unsigned int NumParams = FD->getNumParams();
17582 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17583 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
17584 fmt = "NSString";
17585 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17586 Type: &Context.Idents.get(Name: fmt),
17587 FormatIdx: FormatIdx+1,
17588 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17589 Range: FD->getLocation()));
17590 }
17591 }
17592 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
17593 HasVAListArg)) {
17594 if (!FD->hasAttr<FormatAttr>())
17595 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17596 Type: &Context.Idents.get(Name: "scanf"),
17597 FormatIdx: FormatIdx+1,
17598 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17599 Range: FD->getLocation()));
17600 }
17601
17602 // Handle automatically recognized callbacks.
17603 SmallVector<int, 4> Encoding;
17604 if (!FD->hasAttr<CallbackAttr>() &&
17605 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
17606 FD->addAttr(A: CallbackAttr::CreateImplicit(
17607 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
17608
17609 // Mark const if we don't care about errno and/or floating point exceptions
17610 // that are the only thing preventing the function from being const. This
17611 // allows IRgen to use LLVM intrinsics for such functions.
17612 bool NoExceptions =
17613 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17614 bool ConstWithoutErrnoAndExceptions =
17615 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
17616 bool ConstWithoutExceptions =
17617 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
17618 if (!FD->hasAttr<ConstAttr>() &&
17619 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17620 (!ConstWithoutErrnoAndExceptions ||
17621 (!getLangOpts().MathErrno && NoExceptions)) &&
17622 (!ConstWithoutExceptions || NoExceptions))
17623 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17624
17625 // We make "fma" on GNU or Windows const because we know it does not set
17626 // errno in those environments even though it could set errno based on the
17627 // C standard.
17628 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17629 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17630 !FD->hasAttr<ConstAttr>()) {
17631 switch (BuiltinID) {
17632 case Builtin::BI__builtin_fma:
17633 case Builtin::BI__builtin_fmaf:
17634 case Builtin::BI__builtin_fmal:
17635 case Builtin::BIfma:
17636 case Builtin::BIfmaf:
17637 case Builtin::BIfmal:
17638 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17639 break;
17640 default:
17641 break;
17642 }
17643 }
17644
17645 SmallVector<int, 4> Indxs;
17646 Builtin::Info::NonNullMode OptMode;
17647 if (Context.BuiltinInfo.isNonNull(ID: BuiltinID, Indxs, Mode&: OptMode) &&
17648 !FD->hasAttr<NonNullAttr>()) {
17649 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17650 for (int I : Indxs) {
17651 ParmVarDecl *PVD = FD->getParamDecl(i: I);
17652 QualType T = PVD->getType();
17653 T = Context.getAttributedType(attrKind: attr::TypeNonNull, modifiedType: T, equivalentType: T);
17654 PVD->setType(T);
17655 }
17656 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17657 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17658 for (int I : Indxs)
17659 ParamIndxs.push_back(Elt: ParamIdx(I + 1, FD));
17660 FD->addAttr(A: NonNullAttr::CreateImplicit(Ctx&: Context, Args: ParamIndxs.data(),
17661 ArgsSize: ParamIndxs.size()));
17662 }
17663 }
17664 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17665 !FD->hasAttr<ReturnsTwiceAttr>())
17666 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17667 Range: FD->getLocation()));
17668 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17669 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17670 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17671 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17672 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17673 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17674 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17675 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17676 // Add the appropriate attribute, depending on the CUDA compilation mode
17677 // and which target the builtin belongs to. For example, during host
17678 // compilation, aux builtins are __device__, while the rest are __host__.
17679 if (getLangOpts().CUDAIsDevice !=
17680 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17681 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17682 else
17683 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17684 }
17685
17686 // Add known guaranteed alignment for allocation functions.
17687 switch (BuiltinID) {
17688 case Builtin::BImemalign:
17689 case Builtin::BIaligned_alloc:
17690 if (!FD->hasAttr<AllocAlignAttr>())
17691 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17692 Range: FD->getLocation()));
17693 break;
17694 default:
17695 break;
17696 }
17697
17698 // Add allocsize attribute for allocation functions.
17699 switch (BuiltinID) {
17700 case Builtin::BIcalloc:
17701 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17702 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17703 break;
17704 case Builtin::BImemalign:
17705 case Builtin::BIaligned_alloc:
17706 case Builtin::BIrealloc:
17707 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17708 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17709 break;
17710 case Builtin::BImalloc:
17711 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17712 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17713 break;
17714 default:
17715 break;
17716 }
17717 }
17718
17719 LazyProcessLifetimeCaptureByParams(FD);
17720 inferLifetimeBoundAttribute(FD);
17721 inferLifetimeCaptureByAttribute(FD);
17722 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17723
17724 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17725 // throw, add an implicit nothrow attribute to any extern "C" function we come
17726 // across.
17727 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17728 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17729 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17730 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17731 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17732 }
17733
17734 IdentifierInfo *Name = FD->getIdentifier();
17735 if (!Name)
17736 return;
17737 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17738 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17739 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17740 LinkageSpecLanguageIDs::C)) {
17741 // Okay: this could be a libc/libm/Objective-C function we know
17742 // about.
17743 } else
17744 return;
17745
17746 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17747 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17748 // target-specific builtins, perhaps?
17749 if (!FD->hasAttr<FormatAttr>())
17750 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17751 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17752 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17753 Range: FD->getLocation()));
17754 }
17755
17756 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17757 // We already have a __builtin___CFStringMakeConstantString,
17758 // but builds that use -fno-constant-cfstrings don't go through that.
17759 if (!FD->hasAttr<FormatArgAttr>())
17760 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17761 Range: FD->getLocation()));
17762 }
17763}
17764
17765TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17766 TypeSourceInfo *TInfo) {
17767 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17768 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17769
17770 if (!TInfo) {
17771 assert(D.isInvalidType() && "no declarator info for valid type");
17772 TInfo = Context.getTrivialTypeSourceInfo(T);
17773 }
17774
17775 // Scope manipulation handled by caller.
17776 TypedefDecl *NewTD =
17777 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17778 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17779
17780 // Bail out immediately if we have an invalid declaration.
17781 if (D.isInvalidType()) {
17782 NewTD->setInvalidDecl();
17783 return NewTD;
17784 }
17785
17786 if (D.getDeclSpec().isModulePrivateSpecified()) {
17787 if (CurContext->isFunctionOrMethod())
17788 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17789 << 2 << NewTD
17790 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17791 << FixItHint::CreateRemoval(
17792 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17793 else
17794 NewTD->setModulePrivate();
17795 }
17796
17797 // C++ [dcl.typedef]p8:
17798 // If the typedef declaration defines an unnamed class (or
17799 // enum), the first typedef-name declared by the declaration
17800 // to be that class type (or enum type) is used to denote the
17801 // class type (or enum type) for linkage purposes only.
17802 // We need to check whether the type was declared in the declaration.
17803 switch (D.getDeclSpec().getTypeSpecType()) {
17804 case TST_enum:
17805 case TST_struct:
17806 case TST_interface:
17807 case TST_union:
17808 case TST_class: {
17809 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17810 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17811 break;
17812 }
17813
17814 default:
17815 break;
17816 }
17817
17818 return NewTD;
17819}
17820
17821bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17822 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17823 QualType T = TI->getType();
17824
17825 if (T->isDependentType())
17826 return false;
17827
17828 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17829 // integral type; any cv-qualification is ignored.
17830 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17831 // non-atomic version of the type specified by the type specifiers in the
17832 // specifier qualifier list.
17833 // Because of how odd C's rule is, we'll let the user know that operations
17834 // involving the enumeration type will be non-atomic.
17835 if (T->isAtomicType())
17836 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17837
17838 Qualifiers Q = T.getQualifiers();
17839 std::optional<unsigned> QualSelect;
17840 if (Q.hasConst() && Q.hasVolatile())
17841 QualSelect = diag::CVQualList::Both;
17842 else if (Q.hasConst())
17843 QualSelect = diag::CVQualList::Const;
17844 else if (Q.hasVolatile())
17845 QualSelect = diag::CVQualList::Volatile;
17846
17847 if (QualSelect)
17848 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17849
17850 T = T.getAtomicUnqualifiedType();
17851
17852 // This doesn't use 'isIntegralType' despite the error message mentioning
17853 // integral type because isIntegralType would also allow enum types in C.
17854 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17855 if (BT->isInteger())
17856 return false;
17857
17858 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17859 << T << T->isBitIntType();
17860}
17861
17862bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17863 QualType EnumUnderlyingTy, bool IsFixed,
17864 const EnumDecl *Prev) {
17865 if (IsScoped != Prev->isScoped()) {
17866 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17867 << Prev->isScoped();
17868 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17869 return true;
17870 }
17871
17872 if (IsFixed && Prev->isFixed()) {
17873 if (!EnumUnderlyingTy->isDependentType() &&
17874 !Prev->getIntegerType()->isDependentType() &&
17875 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17876 T2: Prev->getIntegerType())) {
17877 // TODO: Highlight the underlying type of the redeclaration.
17878 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17879 << EnumUnderlyingTy << Prev->getIntegerType();
17880 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17881 << Prev->getIntegerTypeRange();
17882 return true;
17883 }
17884 } else if (IsFixed != Prev->isFixed()) {
17885 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17886 << Prev->isFixed();
17887 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17888 return true;
17889 }
17890
17891 return false;
17892}
17893
17894/// Get diagnostic %select index for tag kind for
17895/// redeclaration diagnostic message.
17896/// WARNING: Indexes apply to particular diagnostics only!
17897///
17898/// \returns diagnostic %select index.
17899static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17900 switch (Tag) {
17901 case TagTypeKind::Struct:
17902 return 0;
17903 case TagTypeKind::Interface:
17904 return 1;
17905 case TagTypeKind::Class:
17906 return 2;
17907 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17908 }
17909}
17910
17911/// Determine if tag kind is a class-key compatible with
17912/// class for redeclaration (class, struct, or __interface).
17913///
17914/// \returns true iff the tag kind is compatible.
17915static bool isClassCompatTagKind(TagTypeKind Tag)
17916{
17917 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17918 Tag == TagTypeKind::Interface;
17919}
17920
17921NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17922 if (isa<TypedefDecl>(Val: PrevDecl))
17923 return NonTagKind::Typedef;
17924 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17925 return NonTagKind::TypeAlias;
17926 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17927 return NonTagKind::Template;
17928 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17929 return NonTagKind::TypeAliasTemplate;
17930 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17931 return NonTagKind::TemplateTemplateArgument;
17932 switch (TTK) {
17933 case TagTypeKind::Struct:
17934 case TagTypeKind::Interface:
17935 case TagTypeKind::Class:
17936 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17937 : NonTagKind::NonStruct;
17938 case TagTypeKind::Union:
17939 return NonTagKind::NonUnion;
17940 case TagTypeKind::Enum:
17941 return NonTagKind::NonEnum;
17942 }
17943 llvm_unreachable("invalid TTK");
17944}
17945
17946bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17947 TagTypeKind NewTag, bool isDefinition,
17948 SourceLocation NewTagLoc,
17949 const IdentifierInfo *Name) {
17950 // C++ [dcl.type.elab]p3:
17951 // The class-key or enum keyword present in the
17952 // elaborated-type-specifier shall agree in kind with the
17953 // declaration to which the name in the elaborated-type-specifier
17954 // refers. This rule also applies to the form of
17955 // elaborated-type-specifier that declares a class-name or
17956 // friend class since it can be construed as referring to the
17957 // definition of the class. Thus, in any
17958 // elaborated-type-specifier, the enum keyword shall be used to
17959 // refer to an enumeration (7.2), the union class-key shall be
17960 // used to refer to a union (clause 9), and either the class or
17961 // struct class-key shall be used to refer to a class (clause 9)
17962 // declared using the class or struct class-key.
17963 TagTypeKind OldTag = Previous->getTagKind();
17964 if (OldTag != NewTag &&
17965 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17966 return false;
17967
17968 // Tags are compatible, but we might still want to warn on mismatched tags.
17969 // Non-class tags can't be mismatched at this point.
17970 if (!isClassCompatTagKind(Tag: NewTag))
17971 return true;
17972
17973 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17974 // by our warning analysis. We don't want to warn about mismatches with (eg)
17975 // declarations in system headers that are designed to be specialized, but if
17976 // a user asks us to warn, we should warn if their code contains mismatched
17977 // declarations.
17978 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17979 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
17980 Loc);
17981 };
17982 if (IsIgnoredLoc(NewTagLoc))
17983 return true;
17984
17985 auto IsIgnored = [&](const TagDecl *Tag) {
17986 return IsIgnoredLoc(Tag->getLocation());
17987 };
17988 while (IsIgnored(Previous)) {
17989 Previous = Previous->getPreviousDecl();
17990 if (!Previous)
17991 return true;
17992 OldTag = Previous->getTagKind();
17993 }
17994
17995 bool isTemplate = false;
17996 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17997 isTemplate = Record->getDescribedClassTemplate();
17998
17999 if (inTemplateInstantiation()) {
18000 if (OldTag != NewTag) {
18001 // In a template instantiation, do not offer fix-its for tag mismatches
18002 // since they usually mess up the template instead of fixing the problem.
18003 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
18004 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18005 << getRedeclDiagFromTagKind(Tag: OldTag);
18006 // FIXME: Note previous location?
18007 }
18008 return true;
18009 }
18010
18011 if (isDefinition) {
18012 // On definitions, check all previous tags and issue a fix-it for each
18013 // one that doesn't match the current tag.
18014 if (Previous->getDefinition()) {
18015 // Don't suggest fix-its for redefinitions.
18016 return true;
18017 }
18018
18019 bool previousMismatch = false;
18020 for (const TagDecl *I : Previous->redecls()) {
18021 if (I->getTagKind() != NewTag) {
18022 // Ignore previous declarations for which the warning was disabled.
18023 if (IsIgnored(I))
18024 continue;
18025
18026 if (!previousMismatch) {
18027 previousMismatch = true;
18028 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
18029 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18030 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
18031 }
18032 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
18033 << getRedeclDiagFromTagKind(Tag: NewTag)
18034 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
18035 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
18036 }
18037 }
18038 return true;
18039 }
18040
18041 // Identify the prevailing tag kind: this is the kind of the definition (if
18042 // there is a non-ignored definition), or otherwise the kind of the prior
18043 // (non-ignored) declaration.
18044 const TagDecl *PrevDef = Previous->getDefinition();
18045 if (PrevDef && IsIgnored(PrevDef))
18046 PrevDef = nullptr;
18047 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
18048 if (Redecl->getTagKind() != NewTag) {
18049 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
18050 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
18051 << getRedeclDiagFromTagKind(Tag: OldTag);
18052 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
18053
18054 // If there is a previous definition, suggest a fix-it.
18055 if (PrevDef) {
18056 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
18057 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
18058 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
18059 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
18060 }
18061 }
18062
18063 return true;
18064}
18065
18066/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
18067/// from an outer enclosing namespace or file scope inside a friend declaration.
18068/// This should provide the commented out code in the following snippet:
18069/// namespace N {
18070/// struct X;
18071/// namespace M {
18072/// struct Y { friend struct /*N::*/ X; };
18073/// }
18074/// }
18075static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
18076 SourceLocation NameLoc) {
18077 // While the decl is in a namespace, do repeated lookup of that name and see
18078 // if we get the same namespace back. If we do not, continue until
18079 // translation unit scope, at which point we have a fully qualified NNS.
18080 SmallVector<IdentifierInfo *, 4> Namespaces;
18081 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18082 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
18083 // This tag should be declared in a namespace, which can only be enclosed by
18084 // other namespaces. Bail if there's an anonymous namespace in the chain.
18085 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
18086 if (!Namespace || Namespace->isAnonymousNamespace())
18087 return FixItHint();
18088 IdentifierInfo *II = Namespace->getIdentifier();
18089 Namespaces.push_back(Elt: II);
18090 NamedDecl *Lookup = SemaRef.LookupSingleName(
18091 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
18092 if (Lookup == Namespace)
18093 break;
18094 }
18095
18096 // Once we have all the namespaces, reverse them to go outermost first, and
18097 // build an NNS.
18098 SmallString<64> Insertion;
18099 llvm::raw_svector_ostream OS(Insertion);
18100 if (DC->isTranslationUnit())
18101 OS << "::";
18102 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
18103 for (auto *II : Namespaces)
18104 OS << II->getName() << "::";
18105 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
18106}
18107
18108/// Determine whether a tag originally declared in context \p OldDC can
18109/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
18110/// found a declaration in \p OldDC as a previous decl, perhaps through a
18111/// using-declaration).
18112static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
18113 DeclContext *NewDC) {
18114 OldDC = OldDC->getRedeclContext();
18115 NewDC = NewDC->getRedeclContext();
18116
18117 if (OldDC->Equals(DC: NewDC))
18118 return true;
18119
18120 // In MSVC mode, we allow a redeclaration if the contexts are related (either
18121 // encloses the other).
18122 if (S.getLangOpts().MSVCCompat &&
18123 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
18124 return true;
18125
18126 return false;
18127}
18128
18129DeclResult
18130Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
18131 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18132 const ParsedAttributesView &Attrs, AccessSpecifier AS,
18133 SourceLocation ModulePrivateLoc,
18134 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
18135 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
18136 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
18137 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
18138 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
18139 // If this is not a definition, it must have a name.
18140 IdentifierInfo *OrigName = Name;
18141 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
18142 "Nameless record must be a definition!");
18143 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
18144
18145 OwnedDecl = false;
18146 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18147 bool ScopedEnum = ScopedEnumKWLoc.isValid();
18148
18149 // FIXME: Check member specializations more carefully.
18150 bool isMemberSpecialization = false;
18151 bool IsInjectedClassName = false;
18152 bool Invalid = false;
18153
18154 // We only need to do this matching if we have template parameters
18155 // or a scope specifier, which also conveniently avoids this work
18156 // for non-C++ cases.
18157 if (TemplateParameterLists.size() > 0 ||
18158 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
18159 TemplateParameterList *TemplateParams =
18160 MatchTemplateParametersToScopeSpecifier(
18161 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
18162 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
18163
18164 // C++23 [dcl.type.elab] p2:
18165 // If an elaborated-type-specifier is the sole constituent of a
18166 // declaration, the declaration is ill-formed unless it is an explicit
18167 // specialization, an explicit instantiation or it has one of the
18168 // following forms: [...]
18169 // C++23 [dcl.enum] p1:
18170 // If the enum-head-name of an opaque-enum-declaration contains a
18171 // nested-name-specifier, the declaration shall be an explicit
18172 // specialization.
18173 //
18174 // FIXME: Class template partial specializations can be forward declared
18175 // per CWG2213, but the resolution failed to allow qualified forward
18176 // declarations. This is almost certainly unintentional, so we allow them.
18177 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18178 !isMemberSpecialization)
18179 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
18180 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
18181
18182 if (TemplateParams) {
18183 if (Kind == TagTypeKind::Enum) {
18184 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
18185 return true;
18186 }
18187
18188 if (TemplateParams->size() > 0) {
18189 // This is a declaration or definition of a class template (which may
18190 // be a member of another template).
18191
18192 if (Invalid)
18193 return true;
18194
18195 OwnedDecl = false;
18196 DeclResult Result = CheckClassTemplate(
18197 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
18198 AS, ModulePrivateLoc,
18199 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
18200 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization, SkipBody);
18201 return Result.get();
18202 } else {
18203 // The "template<>" header is extraneous.
18204 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18205 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18206 isMemberSpecialization = true;
18207 }
18208 }
18209
18210 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18211 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
18212 return true;
18213 }
18214
18215 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18216 // C++23 [dcl.type.elab]p4:
18217 // If an elaborated-type-specifier appears with the friend specifier as
18218 // an entire member-declaration, the member-declaration shall have one
18219 // of the following forms:
18220 // friend class-key nested-name-specifier(opt) identifier ;
18221 // friend class-key simple-template-id ;
18222 // friend class-key nested-name-specifier template(opt)
18223 // simple-template-id ;
18224 //
18225 // Since enum is not a class-key, so declarations like "friend enum E;"
18226 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18227 // invalid, most implementations accept so we issue a pedantic warning.
18228 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
18229 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18230 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18231 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
18232 << (ScopedEnum + ScopedEnumUsesClassTag);
18233 }
18234
18235 // Figure out the underlying type if this a enum declaration. We need to do
18236 // this early, because it's needed to detect if this is an incompatible
18237 // redeclaration.
18238 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18239 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18240
18241 if (Kind == TagTypeKind::Enum) {
18242 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18243 Invalid) {
18244 // No underlying type explicitly specified, or we failed to parse the
18245 // type, default to int.
18246 EnumUnderlying = Context.IntTy.getTypePtr();
18247 } else if (UnderlyingType.get()) {
18248 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18249 // integral type; any cv-qualification is ignored.
18250 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18251 // unqualified, non-atomic version of the type specified by the type
18252 // specifiers in the specifier qualifier list.
18253 TypeSourceInfo *TI = nullptr;
18254 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
18255 EnumUnderlying = TI;
18256
18257 if (CheckEnumUnderlyingType(TI))
18258 // Recover by falling back to int.
18259 EnumUnderlying = Context.IntTy.getTypePtr();
18260
18261 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
18262 UPPC: UPPC_FixedUnderlyingType))
18263 EnumUnderlying = Context.IntTy.getTypePtr();
18264
18265 // If the underlying type is atomic, we need to adjust the type before
18266 // continuing. This only happens in the case we stored a TypeSourceInfo
18267 // into EnumUnderlying because the other cases are error recovery up to
18268 // this point. But because it's not possible to gin up a TypeSourceInfo
18269 // for a non-atomic type from an atomic one, we'll store into the Type
18270 // field instead. FIXME: it would be nice to have an easy way to get a
18271 // derived TypeSourceInfo which strips qualifiers including the weird
18272 // ones like _Atomic where it forms a different type.
18273 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
18274 TI && TI->getType()->isAtomicType())
18275 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18276
18277 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18278 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18279 // of 'int'. However, if this is an unfixed forward declaration, don't set
18280 // the underlying type unless the user enables -fms-compatibility. This
18281 // makes unfixed forward declared enums incomplete and is more conforming.
18282 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18283 EnumUnderlying = Context.IntTy.getTypePtr();
18284 }
18285 }
18286
18287 DeclContext *SearchDC = CurContext;
18288 DeclContext *DC = CurContext;
18289 bool isStdBadAlloc = false;
18290 bool isStdAlignValT = false;
18291
18292 RedeclarationKind Redecl = forRedeclarationInCurContext();
18293 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18294 Redecl = RedeclarationKind::NotForRedeclaration;
18295
18296 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18297 /// implemented asks for structural equivalence checking, the returned decl
18298 /// here is passed back to the parser, allowing the tag body to be parsed.
18299 auto createTagFromNewDecl = [&]() -> TagDecl * {
18300 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18301 // If there is an identifier, use the location of the identifier as the
18302 // location of the decl, otherwise use the location of the struct/union
18303 // keyword.
18304 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18305 TagDecl *New = nullptr;
18306
18307 if (Kind == TagTypeKind::Enum) {
18308 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
18309 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18310 // If this is an undefined enum, bail.
18311 if (TUK != TagUseKind::Definition && !Invalid)
18312 return nullptr;
18313 if (EnumUnderlying) {
18314 EnumDecl *ED = cast<EnumDecl>(Val: New);
18315 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18316 ED->setIntegerTypeSourceInfo(TI);
18317 else
18318 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18319 QualType EnumTy = ED->getIntegerType();
18320 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18321 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18322 : EnumTy);
18323 }
18324 } else { // struct/union
18325 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18326 PrevDecl: nullptr);
18327 }
18328
18329 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18330 // Add alignment attributes if necessary; these attributes are checked
18331 // when the ASTContext lays out the structure.
18332 //
18333 // It is important for implementing the correct semantics that this
18334 // happen here (in ActOnTag). The #pragma pack stack is
18335 // maintained as a result of parser callbacks which can occur at
18336 // many points during the parsing of a struct declaration (because
18337 // the #pragma tokens are effectively skipped over during the
18338 // parsing of the struct).
18339 if (TUK == TagUseKind::Definition &&
18340 (!SkipBody || !SkipBody->ShouldSkip)) {
18341 if (LangOpts.HLSL)
18342 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18343 AddAlignmentAttributesForRecord(RD);
18344 AddMsStructLayoutForRecord(RD);
18345 }
18346 }
18347 New->setLexicalDeclContext(CurContext);
18348 return New;
18349 };
18350
18351 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18352 if (Name && SS.isNotEmpty()) {
18353 // We have a nested-name tag ('struct foo::bar').
18354
18355 // Check for invalid 'foo::'.
18356 if (SS.isInvalid()) {
18357 Name = nullptr;
18358 goto CreateNewDecl;
18359 }
18360
18361 // If this is a friend or a reference to a class in a dependent
18362 // context, don't try to make a decl for it.
18363 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18364 DC = computeDeclContext(SS, EnteringContext: false);
18365 if (!DC) {
18366 IsDependent = true;
18367 return true;
18368 }
18369 } else {
18370 DC = computeDeclContext(SS, EnteringContext: true);
18371 if (!DC) {
18372 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
18373 << SS.getRange();
18374 return true;
18375 }
18376 }
18377
18378 if (RequireCompleteDeclContext(SS, DC))
18379 return true;
18380
18381 SearchDC = DC;
18382 // Look-up name inside 'foo::'.
18383 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18384
18385 if (Previous.isAmbiguous())
18386 return true;
18387
18388 if (Previous.empty()) {
18389 // Name lookup did not find anything. However, if the
18390 // nested-name-specifier refers to the current instantiation,
18391 // and that current instantiation has any dependent base
18392 // classes, we might find something at instantiation time: treat
18393 // this as a dependent elaborated-type-specifier.
18394 // But this only makes any sense for reference-like lookups.
18395 if (Previous.wasNotFoundInCurrentInstantiation() &&
18396 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18397 IsDependent = true;
18398 return true;
18399 }
18400
18401 // A tag 'foo::bar' must already exist.
18402 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
18403 << Kind << Name << DC << SS.getRange();
18404 Name = nullptr;
18405 Invalid = true;
18406 goto CreateNewDecl;
18407 }
18408 } else if (Name) {
18409 // C++14 [class.mem]p14:
18410 // If T is the name of a class, then each of the following shall have a
18411 // name different from T:
18412 // -- every member of class T that is itself a type
18413 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18414 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
18415 return true;
18416
18417 // If this is a named struct, check to see if there was a previous forward
18418 // declaration or definition.
18419 // FIXME: We're looking into outer scopes here, even when we
18420 // shouldn't be. Doing so can result in ambiguities that we
18421 // shouldn't be diagnosing.
18422 LookupName(R&: Previous, S);
18423
18424 // When declaring or defining a tag, ignore ambiguities introduced
18425 // by types using'ed into this scope.
18426 if (Previous.isAmbiguous() &&
18427 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18428 LookupResult::Filter F = Previous.makeFilter();
18429 while (F.hasNext()) {
18430 NamedDecl *ND = F.next();
18431 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18432 DC: SearchDC->getRedeclContext()))
18433 F.erase();
18434 }
18435 F.done();
18436 }
18437
18438 // C++11 [namespace.memdef]p3:
18439 // If the name in a friend declaration is neither qualified nor
18440 // a template-id and the declaration is a function or an
18441 // elaborated-type-specifier, the lookup to determine whether
18442 // the entity has been previously declared shall not consider
18443 // any scopes outside the innermost enclosing namespace.
18444 //
18445 // MSVC doesn't implement the above rule for types, so a friend tag
18446 // declaration may be a redeclaration of a type declared in an enclosing
18447 // scope. They do implement this rule for friend functions.
18448 //
18449 // Does it matter that this should be by scope instead of by
18450 // semantic context?
18451 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18452 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18453 LookupResult::Filter F = Previous.makeFilter();
18454 bool FriendSawTagOutsideEnclosingNamespace = false;
18455 while (F.hasNext()) {
18456 NamedDecl *ND = F.next();
18457 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18458 if (DC->isFileContext() &&
18459 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
18460 if (getLangOpts().MSVCCompat)
18461 FriendSawTagOutsideEnclosingNamespace = true;
18462 else
18463 F.erase();
18464 }
18465 }
18466 F.done();
18467
18468 // Diagnose this MSVC extension in the easy case where lookup would have
18469 // unambiguously found something outside the enclosing namespace.
18470 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18471 NamedDecl *ND = Previous.getFoundDecl();
18472 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
18473 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
18474 }
18475 }
18476
18477 // Note: there used to be some attempt at recovery here.
18478 if (Previous.isAmbiguous())
18479 return true;
18480
18481 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18482 // FIXME: This makes sure that we ignore the contexts associated
18483 // with C structs, unions, and enums when looking for a matching
18484 // tag declaration or definition. See the similar lookup tweak
18485 // in Sema::LookupName; is there a better way to deal with this?
18486 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
18487 SearchDC = SearchDC->getParent();
18488 } else if (getLangOpts().CPlusPlus) {
18489 // Inside ObjCContainer want to keep it as a lexical decl context but go
18490 // past it (most often to TranslationUnit) to find the semantic decl
18491 // context.
18492 while (isa<ObjCContainerDecl>(Val: SearchDC))
18493 SearchDC = SearchDC->getParent();
18494 }
18495 } else if (getLangOpts().CPlusPlus) {
18496 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18497 // TagDecl the same way as we skip it for named TagDecl.
18498 while (isa<ObjCContainerDecl>(Val: SearchDC))
18499 SearchDC = SearchDC->getParent();
18500 }
18501
18502 if (Previous.isSingleResult() &&
18503 Previous.getFoundDecl()->isTemplateParameter()) {
18504 // Maybe we will complain about the shadowed template parameter.
18505 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
18506 // Just pretend that we didn't see the previous declaration.
18507 Previous.clear();
18508 }
18509
18510 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18511 DC->getRedeclContext()->Equals(DC: getStdNamespace())) {
18512 if (Name->isStr(Str: "bad_alloc")) {
18513 // This is a declaration of or a reference to "std::bad_alloc".
18514 isStdBadAlloc = true;
18515
18516 // If std::bad_alloc has been implicitly declared (but made invisible to
18517 // name lookup), fill in this implicit declaration as the previous
18518 // declaration, so that the declarations get chained appropriately.
18519 if (Previous.empty() && StdBadAlloc)
18520 Previous.addDecl(D: getStdBadAlloc());
18521 } else if (Name->isStr(Str: "align_val_t")) {
18522 isStdAlignValT = true;
18523 if (Previous.empty() && StdAlignValT)
18524 Previous.addDecl(D: getStdAlignValT());
18525 }
18526 }
18527
18528 // If we didn't find a previous declaration, and this is a reference
18529 // (or friend reference), move to the correct scope. In C++, we
18530 // also need to do a redeclaration lookup there, just in case
18531 // there's a shadow friend decl.
18532 if (Name && Previous.empty() &&
18533 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18534 IsTemplateParamOrArg)) {
18535 if (Invalid) goto CreateNewDecl;
18536 assert(SS.isEmpty());
18537
18538 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18539 // C++ [basic.scope.pdecl]p5:
18540 // -- for an elaborated-type-specifier of the form
18541 //
18542 // class-key identifier
18543 //
18544 // if the elaborated-type-specifier is used in the
18545 // decl-specifier-seq or parameter-declaration-clause of a
18546 // function defined in namespace scope, the identifier is
18547 // declared as a class-name in the namespace that contains
18548 // the declaration; otherwise, except as a friend
18549 // declaration, the identifier is declared in the smallest
18550 // non-class, non-function-prototype scope that contains the
18551 // declaration.
18552 //
18553 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18554 // C structs and unions.
18555 //
18556 // It is an error in C++ to declare (rather than define) an enum
18557 // type, including via an elaborated type specifier. We'll
18558 // diagnose that later; for now, declare the enum in the same
18559 // scope as we would have picked for any other tag type.
18560 //
18561 // GNU C also supports this behavior as part of its incomplete
18562 // enum types extension, while GNU C++ does not.
18563 //
18564 // Find the context where we'll be declaring the tag.
18565 // FIXME: We would like to maintain the current DeclContext as the
18566 // lexical context,
18567 SearchDC = getTagInjectionContext(DC: SearchDC);
18568
18569 // Find the scope where we'll be declaring the tag.
18570 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18571 } else {
18572 assert(TUK == TagUseKind::Friend);
18573 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
18574
18575 // C++ [namespace.memdef]p3:
18576 // If a friend declaration in a non-local class first declares a
18577 // class or function, the friend class or function is a member of
18578 // the innermost enclosing namespace.
18579 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18580 : SearchDC->getEnclosingNamespaceContext();
18581 }
18582
18583 // In C++, we need to do a redeclaration lookup to properly
18584 // diagnose some problems.
18585 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18586 // hidden declaration so that we don't get ambiguity errors when using a
18587 // type declared by an elaborated-type-specifier. In C that is not correct
18588 // and we should instead merge compatible types found by lookup.
18589 if (getLangOpts().CPlusPlus) {
18590 // FIXME: This can perform qualified lookups into function contexts,
18591 // which are meaningless.
18592 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18593 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
18594 } else {
18595 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18596 LookupName(R&: Previous, S);
18597 }
18598 }
18599
18600 // If we have a known previous declaration to use, then use it.
18601 if (Previous.empty() && SkipBody && SkipBody->Previous)
18602 Previous.addDecl(D: SkipBody->Previous);
18603
18604 if (!Previous.empty()) {
18605 NamedDecl *PrevDecl = Previous.getFoundDecl();
18606 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18607
18608 // It's okay to have a tag decl in the same scope as a typedef
18609 // which hides a tag decl in the same scope. Finding this
18610 // with a redeclaration lookup can only actually happen in C++.
18611 //
18612 // This is also okay for elaborated-type-specifiers, which is
18613 // technically forbidden by the current standard but which is
18614 // okay according to the likely resolution of an open issue;
18615 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18616 if (getLangOpts().CPlusPlus) {
18617 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18618 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18619 if (Tag->getDeclName() == Name &&
18620 Tag->getDeclContext()->getRedeclContext()
18621 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
18622 PrevDecl = Tag;
18623 Previous.clear();
18624 Previous.addDecl(D: Tag);
18625 Previous.resolveKind();
18626 }
18627 }
18628 }
18629 }
18630
18631 // If this is a redeclaration of a using shadow declaration, it must
18632 // declare a tag in the same context. In MSVC mode, we allow a
18633 // redefinition if either context is within the other.
18634 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
18635 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
18636 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18637 TUK != TagUseKind::Friend &&
18638 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
18639 !(OldTag && isAcceptableTagRedeclContext(
18640 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
18641 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
18642 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
18643 DiagID: diag::note_using_decl_target);
18644 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
18645 << 0;
18646 // Recover by ignoring the old declaration.
18647 Previous.clear();
18648 goto CreateNewDecl;
18649 }
18650 }
18651
18652 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
18653 // If this is a use of a previous tag, or if the tag is already declared
18654 // in the same scope (so that the definition/declaration completes or
18655 // rementions the tag), reuse the decl.
18656 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18657 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18658 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18659
18660 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: PrevDecl);
18661 RD && RD->isInjectedClassName()) {
18662 // If lookup found the injected class name, the previous declaration
18663 // is the class being injected into.
18664 Previous.clear();
18665 PrevDecl = PrevTagDecl = cast<CXXRecordDecl>(Val: RD->getDeclContext());
18666 Previous.addDecl(D: PrevDecl);
18667 Previous.resolveKind();
18668 IsInjectedClassName = true;
18669 }
18670
18671 // Make sure that this wasn't declared as an enum and now used as a
18672 // struct or something similar.
18673 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
18674 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18675 Name)) {
18676 bool SafeToContinue =
18677 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18678 Kind != TagTypeKind::Enum);
18679 if (SafeToContinue)
18680 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18681 << Name
18682 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18683 Code: PrevTagDecl->getKindName());
18684 else
18685 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18686 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18687
18688 if (SafeToContinue)
18689 Kind = PrevTagDecl->getTagKind();
18690 else {
18691 // Recover by making this an anonymous redefinition.
18692 Name = nullptr;
18693 Previous.clear();
18694 Invalid = true;
18695 }
18696 }
18697
18698 if (Kind == TagTypeKind::Enum &&
18699 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18700 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18701 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18702 return PrevTagDecl;
18703
18704 QualType EnumUnderlyingTy;
18705 if (TypeSourceInfo *TI =
18706 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18707 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18708 else if (const Type *T =
18709 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18710 EnumUnderlyingTy = QualType(T, 0);
18711
18712 // All conflicts with previous declarations are recovered by
18713 // returning the previous declaration, unless this is a definition,
18714 // in which case we want the caller to bail out.
18715 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18716 IsScoped: ScopedEnum, EnumUnderlyingTy,
18717 IsFixed, Prev: PrevEnum))
18718 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18719 }
18720
18721 // C++11 [class.mem]p1:
18722 // A member shall not be declared twice in the member-specification,
18723 // except that a nested class or member class template can be declared
18724 // and then later defined.
18725 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18726 S->isDeclScope(D: PrevDecl)) {
18727 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18728 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18729 }
18730
18731 // C++ [class.local]p3:
18732 // A class nested within a local class is a local class. A member of
18733 // a local class X shall be declared only in the definition of X or,
18734 // if the member is a nested class, in the nearest enclosing block
18735 // scope of X.
18736 if (TUK == TagUseKind::Definition && SS.isValid()) {
18737 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(Val: PrevDecl)) {
18738 while (const auto *ParentClass =
18739 dyn_cast<CXXRecordDecl>(Val: OutermostClass->getParent()))
18740 OutermostClass = ParentClass;
18741
18742 if (OutermostClass->isLocalClass() &&
18743 !S->isDeclScope(D: OutermostClass)) {
18744 Diag(Loc: NameLoc, DiagID: diag::err_local_nested_class_invalid_scope)
18745 << Name << OutermostClass;
18746 Diag(Loc: OutermostClass->getLocation(), DiagID: diag::note_defined_here)
18747 << OutermostClass;
18748 }
18749 }
18750 }
18751
18752 if (!Invalid) {
18753 // If this is a use, just return the declaration we found, unless
18754 // we have attributes.
18755 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18756 if (!Attrs.empty()) {
18757 // FIXME: Diagnose these attributes. For now, we create a new
18758 // declaration to hold them.
18759 } else if (TUK == TagUseKind::Reference &&
18760 (PrevTagDecl->getFriendObjectKind() ==
18761 Decl::FOK_Undeclared ||
18762 PrevDecl->getOwningModule() != getCurrentModule()) &&
18763 SS.isEmpty()) {
18764 // This declaration is a reference to an existing entity, but
18765 // has different visibility from that entity: it either makes
18766 // a friend visible or it makes a type visible in a new module.
18767 // In either case, create a new declaration. We only do this if
18768 // the declaration would have meant the same thing if no prior
18769 // declaration were found, that is, if it was found in the same
18770 // scope where we would have injected a declaration.
18771 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18772 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18773 return PrevTagDecl;
18774 // This is in the injected scope, create a new declaration in
18775 // that scope.
18776 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18777 } else {
18778 return PrevTagDecl;
18779 }
18780 }
18781
18782 // Diagnose attempts to redefine a tag.
18783 if (TUK == TagUseKind::Definition) {
18784 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18785 // If the type is currently being defined, complain
18786 // about a nested redefinition.
18787 if (Def->isBeingDefined()) {
18788 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18789 Diag(Loc: PrevTagDecl->getLocation(),
18790 DiagID: diag::note_previous_definition);
18791 Name = nullptr;
18792 Previous.clear();
18793 Invalid = true;
18794 } else {
18795 // If we're defining a specialization and the previous
18796 // definition is from an implicit instantiation, don't emit an
18797 // error here; we'll catch this in the general case below.
18798 bool IsExplicitSpecializationAfterInstantiation = false;
18799 if (isMemberSpecialization) {
18800 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18801 IsExplicitSpecializationAfterInstantiation =
18802 RD->getTemplateSpecializationKind() !=
18803 TSK_ExplicitSpecialization;
18804 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18805 IsExplicitSpecializationAfterInstantiation =
18806 ED->getTemplateSpecializationKind() !=
18807 TSK_ExplicitSpecialization;
18808 }
18809
18810 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18811 // do not keep more that one definition around (merge them).
18812 // However, ensure the decl passes the structural compatibility
18813 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18814 NamedDecl *Hidden = nullptr;
18815 bool HiddenDefVisible = false;
18816 if (SkipBody &&
18817 (isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible) ||
18818 getLangOpts().C23)) {
18819 // There is a definition of this tag, but it is not visible.
18820 // We explicitly make use of C++'s one definition rule here,
18821 // and assume that this definition is identical to the hidden
18822 // one we already have. Make the existing definition visible
18823 // and use it in place of this one.
18824 if (!getLangOpts().CPlusPlus) {
18825 // Postpone making the old definition visible until after we
18826 // complete parsing the new one and do the structural
18827 // comparison.
18828 SkipBody->CheckSameAsPrevious = true;
18829 SkipBody->New = createTagFromNewDecl();
18830 SkipBody->Previous = Def;
18831
18832 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18833 return Def;
18834 }
18835
18836 SkipBody->ShouldSkip = true;
18837 SkipBody->Previous = Def;
18838 if (!HiddenDefVisible && Hidden)
18839 makeMergedDefinitionVisible(ND: Hidden);
18840 // Carry on and handle it like a normal definition. We'll
18841 // skip starting the definition later.
18842
18843 } else if (!IsExplicitSpecializationAfterInstantiation) {
18844 // A redeclaration in function prototype scope in C isn't
18845 // visible elsewhere, so merely issue a warning.
18846 if (!getLangOpts().CPlusPlus &&
18847 S->containedInPrototypeScope())
18848 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list)
18849 << Name;
18850 else
18851 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18852 notePreviousDefinition(Old: Def,
18853 New: NameLoc.isValid() ? NameLoc : KWLoc);
18854 // If this is a redefinition, recover by making this
18855 // struct be anonymous, which will make any later
18856 // references get the previous definition.
18857 Name = nullptr;
18858 Previous.clear();
18859 Invalid = true;
18860 }
18861 }
18862 }
18863
18864 // Okay, this is definition of a previously declared or referenced
18865 // tag. We're going to create a new Decl for it.
18866 }
18867
18868 // Okay, we're going to make a redeclaration. If this is some kind
18869 // of reference, make sure we build the redeclaration in the same DC
18870 // as the original, and ignore the current access specifier.
18871 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference ||
18872 IsInjectedClassName) {
18873 SearchDC = PrevTagDecl->getDeclContext();
18874 AS = AS_none;
18875 }
18876 }
18877 // If we get here we have (another) forward declaration or we
18878 // have a definition. Just create a new decl.
18879
18880 } else {
18881 // If we get here, this is a definition of a new tag type in a nested
18882 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18883 // new decl/type. We set PrevDecl to NULL so that the entities
18884 // have distinct types.
18885 Previous.clear();
18886 }
18887 // If we get here, we're going to create a new Decl. If PrevDecl
18888 // is non-NULL, it's a definition of the tag declared by
18889 // PrevDecl. If it's NULL, we have a new definition.
18890
18891 // Otherwise, PrevDecl is not a tag, but was found with tag
18892 // lookup. This is only actually possible in C++, where a few
18893 // things like templates still live in the tag namespace.
18894 } else {
18895 // Use a better diagnostic if an elaborated-type-specifier
18896 // found the wrong kind of type on the first
18897 // (non-redeclaration) lookup.
18898 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18899 !Previous.isForRedeclaration()) {
18900 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18901 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18902 << PrevDecl << NTK << Kind;
18903 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18904 Invalid = true;
18905
18906 // Otherwise, only diagnose if the declaration is in scope.
18907 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18908 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18909 // do nothing
18910
18911 // Diagnose implicit declarations introduced by elaborated types.
18912 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18913 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18914 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
18915 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18916 Invalid = true;
18917
18918 // Otherwise it's a declaration. Call out a particularly common
18919 // case here.
18920 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18921 unsigned Kind = 0;
18922 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18923 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
18924 << Name << Kind << TND->getUnderlyingType();
18925 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18926 Invalid = true;
18927
18928 // Otherwise, diagnose.
18929 } else {
18930 // The tag name clashes with something else in the target scope,
18931 // issue an error and recover by making this tag be anonymous.
18932 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
18933 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18934 Name = nullptr;
18935 Invalid = true;
18936 }
18937
18938 // The existing declaration isn't relevant to us; we're in a
18939 // new scope, so clear out the previous declaration.
18940 Previous.clear();
18941 }
18942 }
18943
18944CreateNewDecl:
18945
18946 TagDecl *PrevDecl = nullptr;
18947 if (Previous.isSingleResult())
18948 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18949
18950 // If there is an identifier, use the location of the identifier as the
18951 // location of the decl, otherwise use the location of the struct/union
18952 // keyword.
18953 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18954
18955 // Otherwise, create a new declaration. If there is a previous
18956 // declaration of the same entity, the two will be linked via
18957 // PrevDecl.
18958 TagDecl *New;
18959
18960 if (Kind == TagTypeKind::Enum) {
18961 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18962 // enum X { A, B, C } D; D should chain to X.
18963 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18964 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
18965 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18966
18967 EnumDecl *ED = cast<EnumDecl>(Val: New);
18968 ED->setEnumKeyRange(SourceRange(
18969 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18970
18971 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18972 StdAlignValT = cast<EnumDecl>(Val: New);
18973
18974 // If this is an undefined enum, warn.
18975 if (TUK != TagUseKind::Definition && !Invalid) {
18976 TagDecl *Def;
18977 if (IsFixed && ED->isFixed()) {
18978 // C++0x: 7.2p2: opaque-enum-declaration.
18979 // Conflicts are diagnosed above. Do nothing.
18980 } else if (PrevDecl &&
18981 (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
18982 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
18983 << New;
18984 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
18985 } else {
18986 unsigned DiagID = diag::ext_forward_ref_enum;
18987 if (getLangOpts().MSVCCompat)
18988 DiagID = diag::ext_ms_forward_ref_enum;
18989 else if (getLangOpts().CPlusPlus)
18990 DiagID = diag::err_forward_ref_enum;
18991 Diag(Loc, DiagID);
18992 }
18993 }
18994
18995 if (EnumUnderlying) {
18996 EnumDecl *ED = cast<EnumDecl>(Val: New);
18997 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18998 ED->setIntegerTypeSourceInfo(TI);
18999 else
19000 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
19001 QualType EnumTy = ED->getIntegerType();
19002 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
19003 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
19004 : EnumTy);
19005 assert(ED->isComplete() && "enum with type should be complete");
19006 }
19007 } else {
19008 // struct/union/class
19009
19010 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19011 // struct X { int A; } D; D should chain to X.
19012 if (getLangOpts().CPlusPlus) {
19013 // FIXME: Look for a way to use RecordDecl for simple structs.
19014 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19015 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
19016
19017 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
19018 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
19019 } else
19020 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
19021 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
19022 }
19023
19024 // Only C23 and later allow defining new types in 'offsetof()'.
19025 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
19026 !getLangOpts().CPlusPlus && !getLangOpts().C23)
19027 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
19028 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
19029
19030 // C++11 [dcl.type]p3:
19031 // A type-specifier-seq shall not define a class or enumeration [...].
19032 if (!Invalid && getLangOpts().CPlusPlus &&
19033 (IsTypeSpecifier || IsTemplateParamOrArg) &&
19034 TUK == TagUseKind::Definition) {
19035 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
19036 << Context.getCanonicalTagType(TD: New);
19037 Invalid = true;
19038 }
19039
19040 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
19041 DC->getDeclKind() == Decl::Enum) {
19042 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
19043 << Context.getCanonicalTagType(TD: New);
19044 Invalid = true;
19045 }
19046
19047 // Maybe add qualifier info.
19048 if (SS.isNotEmpty()) {
19049 if (SS.isSet()) {
19050 // If this is either a declaration or a definition, check the
19051 // nested-name-specifier against the current context.
19052 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
19053 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
19054 /*TemplateId=*/nullptr,
19055 IsMemberSpecialization: isMemberSpecialization))
19056 Invalid = true;
19057
19058 New->setQualifierInfo(SS.getWithLocInContext(Context));
19059 if (TemplateParameterLists.size() > 0) {
19060 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
19061 }
19062 }
19063 else
19064 Invalid = true;
19065 }
19066
19067 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
19068 // Add alignment attributes if necessary; these attributes are checked when
19069 // the ASTContext lays out the structure.
19070 //
19071 // It is important for implementing the correct semantics that this
19072 // happen here (in ActOnTag). The #pragma pack stack is
19073 // maintained as a result of parser callbacks which can occur at
19074 // many points during the parsing of a struct declaration (because
19075 // the #pragma tokens are effectively skipped over during the
19076 // parsing of the struct).
19077 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
19078 if (LangOpts.HLSL)
19079 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
19080 AddAlignmentAttributesForRecord(RD);
19081 AddMsStructLayoutForRecord(RD);
19082 }
19083 }
19084
19085 if (ModulePrivateLoc.isValid()) {
19086 if (isMemberSpecialization)
19087 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
19088 << 2
19089 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
19090 // __module_private__ does not apply to local classes. However, we only
19091 // diagnose this as an error when the declaration specifiers are
19092 // freestanding. Here, we just ignore the __module_private__.
19093 else if (!SearchDC->isFunctionOrMethod())
19094 New->setModulePrivate();
19095 }
19096
19097 // If this is a specialization of a member class (of a class template),
19098 // check the specialization.
19099 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
19100 Invalid = true;
19101
19102 // If we're declaring or defining a tag in function prototype scope in C,
19103 // note that this type can only be used within the function and add it to
19104 // the list of decls to inject into the function definition scope. However,
19105 // in C23 and later, while the type is only visible within the function, the
19106 // function can be called with a compatible type defined in the same TU, so
19107 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
19108 if ((Name || Kind == TagTypeKind::Enum) &&
19109 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
19110 if (getLangOpts().CPlusPlus) {
19111 // C++ [dcl.fct]p6:
19112 // Types shall not be defined in return or parameter types.
19113 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
19114 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
19115 << Name;
19116 Invalid = true;
19117 }
19118 if (TUK == TagUseKind::Declaration)
19119 Invalid = true;
19120 } else if (!PrevDecl) {
19121 // In C23 mode, if the declaration is complete, we do not want to
19122 // diagnose.
19123 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
19124 Diag(Loc, DiagID: diag::warn_decl_in_param_list)
19125 << Context.getCanonicalTagType(TD: New);
19126 }
19127 }
19128
19129 if (Invalid)
19130 New->setInvalidDecl();
19131
19132 // Set the lexical context. If the tag has a C++ scope specifier, the
19133 // lexical context will be different from the semantic context.
19134 New->setLexicalDeclContext(CurContext);
19135
19136 // Mark this as a friend decl if applicable.
19137 // In Microsoft mode, a friend declaration also acts as a forward
19138 // declaration so we always pass true to setObjectOfFriendDecl to make
19139 // the tag name visible.
19140 if (TUK == TagUseKind::Friend)
19141 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
19142
19143 // Set the access specifier.
19144 if (!Invalid && SearchDC->isRecord())
19145 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
19146
19147 if (PrevDecl)
19148 CheckRedeclarationInModule(New, Old: PrevDecl);
19149
19150 if (TUK == TagUseKind::Definition) {
19151 if (!SkipBody || !SkipBody->ShouldSkip) {
19152 New->startDefinition();
19153 } else {
19154 New->setCompleteDefinition();
19155 New->demoteThisDefinitionToDeclaration();
19156 }
19157 }
19158
19159 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
19160 AddPragmaAttributes(S, D: New);
19161
19162 // If this has an identifier, add it to the scope stack.
19163 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
19164 // We might be replacing an existing declaration in the lookup tables;
19165 // if so, borrow its access specifier.
19166 if (PrevDecl)
19167 New->setAccess(PrevDecl->getAccess());
19168
19169 DeclContext *DC = New->getDeclContext()->getRedeclContext();
19170 DC->makeDeclVisibleInContext(D: New);
19171 if (Name) // can be null along some error paths
19172 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19173 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
19174 } else if (Name) {
19175 S = getNonFieldDeclScope(S);
19176 PushOnScopeChains(D: New, S, AddToContext: true);
19177 } else {
19178 CurContext->addDecl(D: New);
19179 }
19180
19181 // If this is the C FILE type, notify the AST context.
19182 if (IdentifierInfo *II = New->getIdentifier())
19183 if (!New->isInvalidDecl() &&
19184 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19185 II->isStr(Str: "FILE"))
19186 Context.setFILEDecl(New);
19187
19188 if (PrevDecl)
19189 mergeDeclAttributes(New, Old: PrevDecl);
19190
19191 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
19192 inferGslOwnerPointerAttribute(Record: CXXRD);
19193 inferNullableClassAttribute(CRD: CXXRD);
19194 }
19195
19196 // If there's a #pragma GCC visibility in scope, set the visibility of this
19197 // record.
19198 AddPushedVisibilityAttribute(RD: New);
19199
19200 // If this is not a definition, process API notes for it now.
19201 if (TUK != TagUseKind::Definition)
19202 ProcessAPINotes(D: New);
19203
19204 if (isMemberSpecialization && !New->isInvalidDecl())
19205 CompleteMemberSpecialization(Member: New, Previous);
19206
19207 OwnedDecl = true;
19208 // In C++, don't return an invalid declaration. We can't recover well from
19209 // the cases where we make the type anonymous.
19210 if (Invalid && getLangOpts().CPlusPlus) {
19211 if (New->isBeingDefined())
19212 if (auto RD = dyn_cast<RecordDecl>(Val: New))
19213 RD->completeDefinition();
19214 return true;
19215 } else if (SkipBody && SkipBody->ShouldSkip) {
19216 return SkipBody->Previous;
19217 } else {
19218 return New;
19219 }
19220}
19221
19222void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
19223 AdjustDeclIfTemplate(Decl&: TagD);
19224 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19225
19226 // Enter the tag context.
19227 PushDeclContext(S, DC: Tag);
19228
19229 ActOnDocumentableDecl(D: TagD);
19230
19231 // If there's a #pragma GCC visibility in scope, set the visibility of this
19232 // record.
19233 AddPushedVisibilityAttribute(RD: Tag);
19234}
19235
19236bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
19237 SkipBodyInfo &SkipBody) {
19238 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
19239 return false;
19240
19241 // Make the previous decl visible.
19242 makeMergedDefinitionVisible(ND: SkipBody.Previous);
19243 CleanupMergedEnum(S, New: SkipBody.New);
19244 return true;
19245}
19246
19247void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
19248 SourceLocation FinalLoc,
19249 bool IsFinalSpelledSealed,
19250 bool IsAbstract,
19251 SourceLocation LBraceLoc) {
19252 AdjustDeclIfTemplate(Decl&: TagD);
19253 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
19254
19255 FieldCollector->StartClass();
19256
19257 if (!Record->getIdentifier())
19258 return;
19259
19260 if (IsAbstract)
19261 Record->markAbstract();
19262
19263 if (FinalLoc.isValid()) {
19264 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
19265 S: IsFinalSpelledSealed
19266 ? FinalAttr::Keyword_sealed
19267 : FinalAttr::Keyword_final));
19268 }
19269
19270 // C++ [class]p2:
19271 // [...] The class-name is also inserted into the scope of the
19272 // class itself; this is known as the injected-class-name. For
19273 // purposes of access checking, the injected-class-name is treated
19274 // as if it were a public member name.
19275 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19276 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
19277 IdLoc: Record->getLocation(), Id: Record->getIdentifier());
19278 InjectedClassName->setImplicit();
19279 InjectedClassName->setAccess(AS_public);
19280 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19281 InjectedClassName->setDescribedClassTemplate(Template);
19282
19283 PushOnScopeChains(D: InjectedClassName, S);
19284 assert(InjectedClassName->isInjectedClassName() &&
19285 "Broken injected-class-name");
19286}
19287
19288void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
19289 SourceRange BraceRange) {
19290 AdjustDeclIfTemplate(Decl&: TagD);
19291 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19292 Tag->setBraceRange(BraceRange);
19293
19294 // Make sure we "complete" the definition even it is invalid.
19295 if (Tag->isBeingDefined()) {
19296 assert(Tag->isInvalidDecl() && "We should already have completed it");
19297 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19298 RD->completeDefinition();
19299 }
19300
19301 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
19302 FieldCollector->FinishClass();
19303 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19304 auto *Def = RD->getDefinition();
19305 assert(Def && "The record is expected to have a completed definition");
19306 unsigned NumInitMethods = 0;
19307 for (auto *Method : Def->methods()) {
19308 if (!Method->getIdentifier())
19309 continue;
19310 if (Method->getName() == "__init")
19311 NumInitMethods++;
19312 }
19313 if (NumInitMethods > 1 || !Def->hasInitMethod())
19314 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
19315 }
19316
19317 // If we're defining a dynamic class in a module interface unit, we always
19318 // need to produce the vtable for it, even if the vtable is not used in the
19319 // current TU.
19320 //
19321 // The case where the current class is not dynamic is handled in
19322 // MarkVTableUsed.
19323 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19324 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
19325 }
19326
19327 // Exit this scope of this tag's definition.
19328 PopDeclContext();
19329
19330 if (getCurLexicalContext()->isObjCContainer() &&
19331 Tag->getDeclContext()->isFileContext())
19332 Tag->setTopLevelDeclInObjCContainer();
19333
19334 // Notify the consumer that we've defined a tag.
19335 if (!Tag->isInvalidDecl())
19336 Consumer.HandleTagDeclDefinition(D: Tag);
19337
19338 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19339 // from XLs and instead matches the XL #pragma pack(1) behavior.
19340 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19341 AlignPackStack.hasValue()) {
19342 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19343 // Only diagnose #pragma align(packed).
19344 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19345 return;
19346 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
19347 if (!RD)
19348 return;
19349 // Only warn if there is at least 1 bitfield member.
19350 if (llvm::any_of(Range: RD->fields(),
19351 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
19352 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
19353 }
19354}
19355
19356void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
19357 AdjustDeclIfTemplate(Decl&: TagD);
19358 TagDecl *Tag = cast<TagDecl>(Val: TagD);
19359 Tag->setInvalidDecl();
19360
19361 // Make sure we "complete" the definition even it is invalid.
19362 if (Tag->isBeingDefined()) {
19363 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
19364 RD->completeDefinition();
19365 }
19366
19367 // We're undoing ActOnTagStartDefinition here, not
19368 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19369 // the FieldCollector.
19370
19371 PopDeclContext();
19372}
19373
19374// Note that FieldName may be null for anonymous bitfields.
19375ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
19376 const IdentifierInfo *FieldName,
19377 QualType FieldTy, bool IsMsStruct,
19378 Expr *BitWidth) {
19379 assert(BitWidth);
19380 if (BitWidth->containsErrors())
19381 return ExprError();
19382
19383 // C99 6.7.2.1p4 - verify the field type.
19384 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19385 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19386 // Handle incomplete and sizeless types with a specific error.
19387 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
19388 DiagID: diag::err_field_incomplete_or_sizeless))
19389 return ExprError();
19390 if (FieldName)
19391 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
19392 << FieldName << FieldTy << BitWidth->getSourceRange();
19393 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
19394 << FieldTy << BitWidth->getSourceRange();
19395 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
19396 return ExprError();
19397
19398 // If the bit-width is type- or value-dependent, don't try to check
19399 // it now.
19400 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19401 return BitWidth;
19402
19403 llvm::APSInt Value;
19404 ExprResult ICE =
19405 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
19406 if (ICE.isInvalid())
19407 return ICE;
19408 BitWidth = ICE.get();
19409
19410 // Zero-width bitfield is ok for anonymous field.
19411 if (Value == 0 && FieldName)
19412 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
19413 << FieldName << BitWidth->getSourceRange();
19414
19415 if (Value.isSigned() && Value.isNegative()) {
19416 if (FieldName)
19417 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
19418 << FieldName << toString(I: Value, Radix: 10);
19419 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
19420 << toString(I: Value, Radix: 10);
19421 }
19422
19423 // The size of the bit-field must not exceed our maximum permitted object
19424 // size.
19425 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19426 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
19427 << !FieldName << FieldName << toString(I: Value, Radix: 10);
19428 }
19429
19430 if (!FieldTy->isDependentType()) {
19431 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
19432 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
19433 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
19434
19435 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19436 // ABI.
19437 bool CStdConstraintViolation =
19438 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19439 bool MSBitfieldViolation = Value.ugt(RHS: TypeStorageSize) && IsMsStruct;
19440 if (CStdConstraintViolation || MSBitfieldViolation) {
19441 unsigned DiagWidth =
19442 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19443 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
19444 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
19445 << !CStdConstraintViolation << DiagWidth;
19446 }
19447
19448 // Warn on types where the user might conceivably expect to get all
19449 // specified bits as value bits: that's all integral types other than
19450 // 'bool'.
19451 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19452 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
19453 << FieldName << Value << (unsigned)TypeWidth;
19454 }
19455 }
19456
19457 if (isa<ConstantExpr>(Val: BitWidth))
19458 return BitWidth;
19459 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
19460}
19461
19462Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19463 Declarator &D, Expr *BitfieldWidth) {
19464 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
19465 D, BitfieldWidth,
19466 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
19467 return Res;
19468}
19469
19470FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19471 SourceLocation DeclStart,
19472 Declarator &D, Expr *BitWidth,
19473 InClassInitStyle InitStyle,
19474 AccessSpecifier AS) {
19475 if (D.isDecompositionDeclarator()) {
19476 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19477 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
19478 << Decomp.getSourceRange();
19479 return nullptr;
19480 }
19481
19482 const IdentifierInfo *II = D.getIdentifier();
19483 SourceLocation Loc = DeclStart;
19484 if (II) Loc = D.getIdentifierLoc();
19485
19486 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19487 QualType T = TInfo->getType();
19488 if (getLangOpts().CPlusPlus) {
19489 CheckExtraCXXDefaultArguments(D);
19490
19491 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19492 UPPC: UPPC_DataMemberType)) {
19493 D.setInvalidType();
19494 T = Context.IntTy;
19495 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19496 }
19497 }
19498
19499 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19500
19501 if (D.getDeclSpec().isInlineSpecified())
19502 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19503 << getLangOpts().CPlusPlus17;
19504 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19505 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19506 DiagID: diag::err_invalid_thread)
19507 << DeclSpec::getSpecifierName(S: TSCS);
19508
19509 // Check to see if this name was declared as a member previously
19510 NamedDecl *PrevDecl = nullptr;
19511 LookupResult Previous(*this, II, Loc, LookupMemberName,
19512 RedeclarationKind::ForVisibleRedeclaration);
19513 LookupName(R&: Previous, S);
19514 switch (Previous.getResultKind()) {
19515 case LookupResultKind::Found:
19516 case LookupResultKind::FoundUnresolvedValue:
19517 PrevDecl = Previous.getAsSingle<NamedDecl>();
19518 break;
19519
19520 case LookupResultKind::FoundOverloaded:
19521 PrevDecl = Previous.getRepresentativeDecl();
19522 break;
19523
19524 case LookupResultKind::NotFound:
19525 case LookupResultKind::NotFoundInCurrentInstantiation:
19526 case LookupResultKind::Ambiguous:
19527 break;
19528 }
19529 Previous.suppressDiagnostics();
19530
19531 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19532 // Maybe we will complain about the shadowed template parameter.
19533 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19534 // Just pretend that we didn't see the previous declaration.
19535 PrevDecl = nullptr;
19536 }
19537
19538 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19539 PrevDecl = nullptr;
19540
19541 bool Mutable
19542 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19543 SourceLocation TSSL = D.getBeginLoc();
19544 FieldDecl *NewFD
19545 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
19546 TSSL, AS, PrevDecl, D: &D);
19547
19548 if (NewFD->isInvalidDecl())
19549 Record->setInvalidDecl();
19550
19551 if (D.getDeclSpec().isModulePrivateSpecified())
19552 NewFD->setModulePrivate();
19553
19554 if (NewFD->isInvalidDecl() && PrevDecl) {
19555 // Don't introduce NewFD into scope; there's already something
19556 // with the same name in the same scope.
19557 } else if (II) {
19558 PushOnScopeChains(D: NewFD, S);
19559 } else
19560 Record->addDecl(D: NewFD);
19561
19562 return NewFD;
19563}
19564
19565FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19566 TypeSourceInfo *TInfo,
19567 RecordDecl *Record, SourceLocation Loc,
19568 bool Mutable, Expr *BitWidth,
19569 InClassInitStyle InitStyle,
19570 SourceLocation TSSL,
19571 AccessSpecifier AS, NamedDecl *PrevDecl,
19572 Declarator *D) {
19573 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19574 bool InvalidDecl = false;
19575 if (D) InvalidDecl = D->isInvalidType();
19576
19577 // If we receive a broken type, recover by assuming 'int' and
19578 // marking this declaration as invalid.
19579 if (T.isNull() || T->containsErrors()) {
19580 InvalidDecl = true;
19581 T = Context.IntTy;
19582 }
19583
19584 QualType EltTy = Context.getBaseElementType(QT: T);
19585 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19586 bool isIncomplete =
19587 LangOpts.HLSL // HLSL allows sizeless builtin types
19588 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
19589 : RequireCompleteSizedType(Loc, T: EltTy,
19590 DiagID: diag::err_field_incomplete_or_sizeless);
19591 if (isIncomplete) {
19592 // Fields of incomplete type force their record to be invalid.
19593 Record->setInvalidDecl();
19594 InvalidDecl = true;
19595 } else {
19596 NamedDecl *Def;
19597 EltTy->isIncompleteType(Def: &Def);
19598 if (Def && Def->isInvalidDecl()) {
19599 Record->setInvalidDecl();
19600 InvalidDecl = true;
19601 }
19602 }
19603 }
19604
19605 // TR 18037 does not allow fields to be declared with address space
19606 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19607 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19608 Diag(Loc, DiagID: diag::err_field_with_address_space);
19609 Record->setInvalidDecl();
19610 InvalidDecl = true;
19611 }
19612
19613 if (LangOpts.OpenCL) {
19614 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19615 // used as structure or union field: image, sampler, event or block types.
19616 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19617 T->isBlockPointerType()) {
19618 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
19619 Record->setInvalidDecl();
19620 InvalidDecl = true;
19621 }
19622 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19623 // is enabled.
19624 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19625 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
19626 Diag(Loc, DiagID: diag::err_opencl_bitfields);
19627 InvalidDecl = true;
19628 }
19629 }
19630
19631 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19632 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19633 T.hasQualifiers()) {
19634 InvalidDecl = true;
19635 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
19636 }
19637
19638 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19639 // than a variably modified type.
19640 if (!InvalidDecl && T->isVariablyModifiedType()) {
19641 if (!tryToFixVariablyModifiedVarType(
19642 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
19643 InvalidDecl = true;
19644 }
19645
19646 // Fields can not have abstract class types
19647 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19648 DiagID: diag::err_abstract_type_in_decl,
19649 Args: AbstractFieldType))
19650 InvalidDecl = true;
19651
19652 if (InvalidDecl)
19653 BitWidth = nullptr;
19654 // If this is declared as a bit-field, check the bit-field.
19655 if (BitWidth) {
19656 BitWidth =
19657 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
19658 if (!BitWidth) {
19659 InvalidDecl = true;
19660 BitWidth = nullptr;
19661 }
19662 }
19663
19664 // Check that 'mutable' is consistent with the type of the declaration.
19665 if (!InvalidDecl && Mutable) {
19666 unsigned DiagID = 0;
19667 if (T->isReferenceType())
19668 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19669 : diag::err_mutable_reference;
19670 else if (T.isConstQualified())
19671 DiagID = diag::err_mutable_const;
19672
19673 if (DiagID) {
19674 SourceLocation ErrLoc = Loc;
19675 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19676 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19677 Diag(Loc: ErrLoc, DiagID);
19678 if (DiagID != diag::ext_mutable_reference) {
19679 Mutable = false;
19680 InvalidDecl = true;
19681 }
19682 }
19683 }
19684
19685 // C++11 [class.union]p8 (DR1460):
19686 // At most one variant member of a union may have a
19687 // brace-or-equal-initializer.
19688 if (InitStyle != ICIS_NoInit)
19689 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
19690
19691 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
19692 BW: BitWidth, Mutable, InitStyle);
19693 if (InvalidDecl)
19694 NewFD->setInvalidDecl();
19695
19696 if (!InvalidDecl)
19697 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
19698
19699 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
19700 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
19701 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
19702 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
19703 NewFD->setInvalidDecl();
19704 }
19705
19706 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19707 if (Record->isUnion()) {
19708 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19709 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19710
19711 // C++ [class.union]p1: An object of a class with a non-trivial
19712 // constructor, a non-trivial copy constructor, a non-trivial
19713 // destructor, or a non-trivial copy assignment operator
19714 // cannot be a member of a union, nor can an array of such
19715 // objects.
19716 if (CheckNontrivialField(FD: NewFD))
19717 NewFD->setInvalidDecl();
19718 }
19719
19720 // C++ [class.union]p1: If a union contains a member of reference type,
19721 // the program is ill-formed, except when compiling with MSVC extensions
19722 // enabled.
19723 if (EltTy->isReferenceType()) {
19724 const bool HaveMSExt =
19725 getLangOpts().MicrosoftExt &&
19726 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19727
19728 Diag(Loc: NewFD->getLocation(),
19729 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19730 : diag::err_union_member_of_reference_type)
19731 << NewFD->getDeclName() << EltTy;
19732 if (!HaveMSExt)
19733 NewFD->setInvalidDecl();
19734 }
19735 }
19736 }
19737
19738 // FIXME: We need to pass in the attributes given an AST
19739 // representation, not a parser representation.
19740 if (D) {
19741 // FIXME: The current scope is almost... but not entirely... correct here.
19742 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19743
19744 if (NewFD->hasAttrs())
19745 CheckAlignasUnderalignment(D: NewFD);
19746 }
19747
19748 // In auto-retain/release, infer strong retension for fields of
19749 // retainable type.
19750 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19751 NewFD->setInvalidDecl();
19752
19753 if (T.isObjCGCWeak())
19754 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19755
19756 // PPC MMA non-pointer types are not allowed as field types.
19757 if (Context.getTargetInfo().getTriple().isPPC64() &&
19758 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19759 NewFD->setInvalidDecl();
19760
19761 if (Context.getTargetInfo().hasAMDGPUTypes()) {
19762 if (!AMDGPU().checkAMDGPUTypeSupport(Ty: T, Loc: NewFD->getLocation()))
19763 NewFD->setInvalidDecl();
19764 }
19765
19766 NewFD->setAccess(AS);
19767 return NewFD;
19768}
19769
19770bool Sema::CheckNontrivialField(FieldDecl *FD) {
19771 assert(FD);
19772 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19773
19774 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19775 return false;
19776
19777 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19778 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19779 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19780 // We check for copy constructors before constructors
19781 // because otherwise we'll never get complaints about
19782 // copy constructors.
19783
19784 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19785 // We're required to check for any non-trivial constructors. Since the
19786 // implicit default constructor is suppressed if there are any
19787 // user-declared constructors, we just need to check that there is a
19788 // trivial default constructor and a trivial copy constructor. (We don't
19789 // worry about move constructors here, since this is a C++98 check.)
19790 if (RDecl->hasNonTrivialCopyConstructor())
19791 member = CXXSpecialMemberKind::CopyConstructor;
19792 else if (!RDecl->hasTrivialDefaultConstructor())
19793 member = CXXSpecialMemberKind::DefaultConstructor;
19794 else if (RDecl->hasNonTrivialCopyAssignment())
19795 member = CXXSpecialMemberKind::CopyAssignment;
19796 else if (RDecl->hasNonTrivialDestructor())
19797 member = CXXSpecialMemberKind::Destructor;
19798
19799 if (member != CXXSpecialMemberKind::Invalid) {
19800 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19801 RDecl->hasObjectMember()) {
19802 // Objective-C++ ARC: it is an error to have a non-trivial field of
19803 // a union. However, system headers in Objective-C programs
19804 // occasionally have Objective-C lifetime objects within unions,
19805 // and rather than cause the program to fail, we make those
19806 // members unavailable.
19807 SourceLocation Loc = FD->getLocation();
19808 if (getSourceManager().isInSystemHeader(Loc)) {
19809 if (!FD->hasAttr<UnavailableAttr>())
19810 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19811 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19812 return false;
19813 }
19814 }
19815
19816 Diag(Loc: FD->getLocation(),
19817 DiagID: getLangOpts().CPlusPlus11
19818 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19819 : diag::err_illegal_union_or_anon_struct_member)
19820 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19821 DiagnoseNontrivial(Record: RDecl, CSM: member);
19822 return !getLangOpts().CPlusPlus11;
19823 }
19824 }
19825
19826 return false;
19827}
19828
19829void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19830 SmallVectorImpl<Decl *> &AllIvarDecls) {
19831 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19832 return;
19833
19834 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19835 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19836
19837 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19838 return;
19839 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19840 if (!ID) {
19841 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19842 if (!CD->IsClassExtension())
19843 return;
19844 }
19845 // No need to add this to end of @implementation.
19846 else
19847 return;
19848 }
19849 // All conditions are met. Add a new bitfield to the tail end of ivars.
19850 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19851 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19852 Expr *BitWidth =
19853 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19854
19855 Ivar = ObjCIvarDecl::Create(
19856 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19857 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19858 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19859 AllIvarDecls.push_back(Elt: Ivar);
19860}
19861
19862/// [class.dtor]p4:
19863/// At the end of the definition of a class, overload resolution is
19864/// performed among the prospective destructors declared in that class with
19865/// an empty argument list to select the destructor for the class, also
19866/// known as the selected destructor.
19867///
19868/// We do the overload resolution here, then mark the selected constructor in the AST.
19869/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19870static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19871 if (!Record->hasUserDeclaredDestructor()) {
19872 return;
19873 }
19874
19875 SourceLocation Loc = Record->getLocation();
19876 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19877
19878 for (auto *Decl : Record->decls()) {
19879 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19880 if (DD->isInvalidDecl())
19881 continue;
19882 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19883 CandidateSet&: OCS);
19884 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19885 }
19886 }
19887
19888 if (OCS.empty()) {
19889 return;
19890 }
19891 OverloadCandidateSet::iterator Best;
19892 unsigned Msg = 0;
19893 OverloadCandidateDisplayKind DisplayKind;
19894
19895 switch (OCS.BestViableFunction(S, Loc, Best)) {
19896 case OR_Success:
19897 case OR_Deleted:
19898 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19899 break;
19900
19901 case OR_Ambiguous:
19902 Msg = diag::err_ambiguous_destructor;
19903 DisplayKind = OCD_AmbiguousCandidates;
19904 break;
19905
19906 case OR_No_Viable_Function:
19907 Msg = diag::err_no_viable_destructor;
19908 DisplayKind = OCD_AllCandidates;
19909 break;
19910 }
19911
19912 if (Msg) {
19913 // OpenCL have got their own thing going with destructors. It's slightly broken,
19914 // but we allow it.
19915 if (!S.LangOpts.OpenCL) {
19916 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19917 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19918 Record->setInvalidDecl();
19919 }
19920 // It's a bit hacky: At this point we've raised an error but we want the
19921 // rest of the compiler to continue somehow working. However almost
19922 // everything we'll try to do with the class will depend on there being a
19923 // destructor. So let's pretend the first one is selected and hope for the
19924 // best.
19925 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19926 }
19927}
19928
19929/// [class.mem.special]p5
19930/// Two special member functions are of the same kind if:
19931/// - they are both default constructors,
19932/// - they are both copy or move constructors with the same first parameter
19933/// type, or
19934/// - they are both copy or move assignment operators with the same first
19935/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19936static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19937 CXXMethodDecl *M1,
19938 CXXMethodDecl *M2,
19939 CXXSpecialMemberKind CSM) {
19940 // We don't want to compare templates to non-templates: See
19941 // https://github.com/llvm/llvm-project/issues/59206
19942 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19943 return bool(M1->getDescribedFunctionTemplate()) ==
19944 bool(M2->getDescribedFunctionTemplate());
19945 // FIXME: better resolve CWG
19946 // https://cplusplus.github.io/CWG/issues/2787.html
19947 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
19948 T2: M2->getNonObjectParameter(I: 0)->getType()))
19949 return false;
19950 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19951 T2: M2->getFunctionObjectParameterReferenceType()))
19952 return false;
19953
19954 return true;
19955}
19956
19957/// [class.mem.special]p6:
19958/// An eligible special member function is a special member function for which:
19959/// - the function is not deleted,
19960/// - the associated constraints, if any, are satisfied, and
19961/// - no special member function of the same kind whose associated constraints
19962/// [CWG2595], if any, are satisfied is more constrained.
19963static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19964 ArrayRef<CXXMethodDecl *> Methods,
19965 CXXSpecialMemberKind CSM) {
19966 SmallVector<bool, 4> SatisfactionStatus;
19967
19968 for (CXXMethodDecl *Method : Methods) {
19969 if (!Method->getTrailingRequiresClause())
19970 SatisfactionStatus.push_back(Elt: true);
19971 else {
19972 ConstraintSatisfaction Satisfaction;
19973 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
19974 SatisfactionStatus.push_back(Elt: false);
19975 else
19976 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19977 }
19978 }
19979
19980 for (size_t i = 0; i < Methods.size(); i++) {
19981 if (!SatisfactionStatus[i])
19982 continue;
19983 CXXMethodDecl *Method = Methods[i];
19984 CXXMethodDecl *OrigMethod = Method;
19985 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19986 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19987
19988 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
19989 bool AnotherMethodIsMoreConstrained = false;
19990 for (size_t j = 0; j < Methods.size(); j++) {
19991 if (i == j || !SatisfactionStatus[j])
19992 continue;
19993 CXXMethodDecl *OtherMethod = Methods[j];
19994 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19995 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19996
19997 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19998 CSM))
19999 continue;
20000
20001 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
20002 if (!Other)
20003 continue;
20004 if (!Orig) {
20005 AnotherMethodIsMoreConstrained = true;
20006 break;
20007 }
20008 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
20009 Result&: AnotherMethodIsMoreConstrained)) {
20010 // There was an error with the constraints comparison. Exit the loop
20011 // and don't consider this function eligible.
20012 AnotherMethodIsMoreConstrained = true;
20013 }
20014 if (AnotherMethodIsMoreConstrained)
20015 break;
20016 }
20017 // FIXME: Do not consider deleted methods as eligible after implementing
20018 // DR1734 and DR1496.
20019 if (!AnotherMethodIsMoreConstrained) {
20020 Method->setIneligibleOrNotSelected(false);
20021 Record->addedEligibleSpecialMemberFunction(MD: Method,
20022 SMKind: 1 << llvm::to_underlying(E: CSM));
20023 }
20024 }
20025}
20026
20027static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
20028 CXXRecordDecl *Record) {
20029 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
20030 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
20031 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
20032 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
20033 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
20034
20035 for (auto *Decl : Record->decls()) {
20036 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
20037 if (!MD) {
20038 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
20039 if (FTD)
20040 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
20041 }
20042 if (!MD)
20043 continue;
20044 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
20045 if (CD->isInvalidDecl())
20046 continue;
20047 if (CD->isDefaultConstructor())
20048 DefaultConstructors.push_back(Elt: MD);
20049 else if (CD->isCopyConstructor())
20050 CopyConstructors.push_back(Elt: MD);
20051 else if (CD->isMoveConstructor())
20052 MoveConstructors.push_back(Elt: MD);
20053 } else if (MD->isCopyAssignmentOperator()) {
20054 CopyAssignmentOperators.push_back(Elt: MD);
20055 } else if (MD->isMoveAssignmentOperator()) {
20056 MoveAssignmentOperators.push_back(Elt: MD);
20057 }
20058 }
20059
20060 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
20061 CSM: CXXSpecialMemberKind::DefaultConstructor);
20062 SetEligibleMethods(S, Record, Methods: CopyConstructors,
20063 CSM: CXXSpecialMemberKind::CopyConstructor);
20064 SetEligibleMethods(S, Record, Methods: MoveConstructors,
20065 CSM: CXXSpecialMemberKind::MoveConstructor);
20066 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
20067 CSM: CXXSpecialMemberKind::CopyAssignment);
20068 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
20069 CSM: CXXSpecialMemberKind::MoveAssignment);
20070}
20071
20072bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
20073 // Check to see if a FieldDecl is a pointer to a function.
20074 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
20075 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
20076 if (!FD) {
20077 // Check whether this is a forward declaration that was inserted by
20078 // Clang. This happens when a non-forward declared / defined type is
20079 // used, e.g.:
20080 //
20081 // struct foo {
20082 // struct bar *(*f)();
20083 // struct bar *(*g)();
20084 // };
20085 //
20086 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
20087 // incomplete definition.
20088 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
20089 return !TD->isCompleteDefinition();
20090 return false;
20091 }
20092 QualType FieldType = FD->getType().getDesugaredType(Context);
20093 if (isa<PointerType>(Val: FieldType)) {
20094 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
20095 return PointeeType.getDesugaredType(Context)->isFunctionType();
20096 }
20097 // If a member is a struct entirely of function pointers, that counts too.
20098 if (const auto *Record = FieldType->getAsRecordDecl();
20099 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
20100 return true;
20101 return false;
20102 };
20103
20104 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
20105}
20106
20107void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
20108 ArrayRef<Decl *> Fields, SourceLocation LBrac,
20109 SourceLocation RBrac,
20110 const ParsedAttributesView &Attrs) {
20111 assert(EnclosingDecl && "missing record or interface decl");
20112
20113 // If this is an Objective-C @implementation or category and we have
20114 // new fields here we should reset the layout of the interface since
20115 // it will now change.
20116 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
20117 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
20118 switch (DC->getKind()) {
20119 default: break;
20120 case Decl::ObjCCategory:
20121 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
20122 break;
20123 case Decl::ObjCImplementation:
20124 Context.
20125 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
20126 break;
20127 }
20128 }
20129
20130 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
20131 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
20132
20133 // Start counting up the number of named members; make sure to include
20134 // members of anonymous structs and unions in the total.
20135 unsigned NumNamedMembers = 0;
20136 if (Record) {
20137 for (const auto *I : Record->decls()) {
20138 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
20139 if (IFD->getDeclName())
20140 ++NumNamedMembers;
20141 }
20142 }
20143
20144 // Verify that all the fields are okay.
20145 SmallVector<FieldDecl*, 32> RecFields;
20146 const FieldDecl *PreviousField = nullptr;
20147 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
20148 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
20149 FieldDecl *FD = cast<FieldDecl>(Val: *i);
20150
20151 // Get the type for the field.
20152 const Type *FDTy = FD->getType().getTypePtr();
20153
20154 if (!FD->isAnonymousStructOrUnion()) {
20155 // Remember all fields written by the user.
20156 RecFields.push_back(Elt: FD);
20157 }
20158
20159 // If the field is already invalid for some reason, don't emit more
20160 // diagnostics about it.
20161 if (FD->isInvalidDecl()) {
20162 EnclosingDecl->setInvalidDecl();
20163 continue;
20164 }
20165
20166 // C99 6.7.2.1p2:
20167 // A structure or union shall not contain a member with
20168 // incomplete or function type (hence, a structure shall not
20169 // contain an instance of itself, but may contain a pointer to
20170 // an instance of itself), except that the last member of a
20171 // structure with more than one named member may have incomplete
20172 // array type; such a structure (and any union containing,
20173 // possibly recursively, a member that is such a structure)
20174 // shall not be a member of a structure or an element of an
20175 // array.
20176 bool IsLastField = (i + 1 == Fields.end());
20177 if (FDTy->isFunctionType()) {
20178 // Field declared as a function.
20179 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
20180 << FD->getDeclName();
20181 FD->setInvalidDecl();
20182 EnclosingDecl->setInvalidDecl();
20183 continue;
20184 } else if (FDTy->isIncompleteArrayType() &&
20185 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
20186 if (Record) {
20187 // Flexible array member.
20188 // Microsoft and g++ is more permissive regarding flexible array.
20189 // It will accept flexible array in union and also
20190 // as the sole element of a struct/class.
20191 unsigned DiagID = 0;
20192 if (!Record->isUnion() && !IsLastField) {
20193 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
20194 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20195 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
20196 FD->setInvalidDecl();
20197 EnclosingDecl->setInvalidDecl();
20198 continue;
20199 } else if (Record->isUnion())
20200 DiagID = getLangOpts().MicrosoftExt
20201 ? diag::ext_flexible_array_union_ms
20202 : diag::ext_flexible_array_union_gnu;
20203 else if (NumNamedMembers < 1)
20204 DiagID = getLangOpts().MicrosoftExt
20205 ? diag::ext_flexible_array_empty_aggregate_ms
20206 : diag::ext_flexible_array_empty_aggregate_gnu;
20207
20208 if (DiagID)
20209 Diag(Loc: FD->getLocation(), DiagID)
20210 << FD->getDeclName() << Record->getTagKind();
20211 // While the layout of types that contain virtual bases is not specified
20212 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20213 // virtual bases after the derived members. This would make a flexible
20214 // array member declared at the end of an object not adjacent to the end
20215 // of the type.
20216 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20217 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
20218 << FD->getDeclName() << Record->getTagKind();
20219 if (!getLangOpts().C99)
20220 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
20221 << FD->getDeclName() << Record->getTagKind();
20222
20223 // If the element type has a non-trivial destructor, we would not
20224 // implicitly destroy the elements, so disallow it for now.
20225 //
20226 // FIXME: GCC allows this. We should probably either implicitly delete
20227 // the destructor of the containing class, or just allow this.
20228 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
20229 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20230 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
20231 << FD->getDeclName() << FD->getType();
20232 FD->setInvalidDecl();
20233 EnclosingDecl->setInvalidDecl();
20234 continue;
20235 }
20236 // Okay, we have a legal flexible array member at the end of the struct.
20237 Record->setHasFlexibleArrayMember(true);
20238 } else {
20239 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20240 // unless they are followed by another ivar. That check is done
20241 // elsewhere, after synthesized ivars are known.
20242 }
20243 } else if (!FDTy->isDependentType() &&
20244 (LangOpts.HLSL // HLSL allows sizeless builtin types
20245 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
20246 DiagID: diag::err_incomplete_type)
20247 : RequireCompleteSizedType(
20248 Loc: FD->getLocation(), T: FD->getType(),
20249 DiagID: diag::err_field_incomplete_or_sizeless))) {
20250 // Incomplete type
20251 FD->setInvalidDecl();
20252 EnclosingDecl->setInvalidDecl();
20253 continue;
20254 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20255 if (Record && RD->hasFlexibleArrayMember()) {
20256 // A type which contains a flexible array member is considered to be a
20257 // flexible array member.
20258 Record->setHasFlexibleArrayMember(true);
20259 if (!Record->isUnion()) {
20260 // If this is a struct/class and this is not the last element, reject
20261 // it. Note that GCC supports variable sized arrays in the middle of
20262 // structures.
20263 if (!IsLastField)
20264 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
20265 << FD->getDeclName() << FD->getType();
20266 else {
20267 // We support flexible arrays at the end of structs in
20268 // other structs as an extension.
20269 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
20270 << FD->getDeclName();
20271 }
20272 }
20273 }
20274 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
20275 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
20276 DiagID: diag::err_abstract_type_in_decl,
20277 Args: AbstractIvarType)) {
20278 // Ivars can not have abstract class types
20279 FD->setInvalidDecl();
20280 }
20281 if (Record && RD->hasObjectMember())
20282 Record->setHasObjectMember(true);
20283 if (Record && RD->hasVolatileMember())
20284 Record->setHasVolatileMember(true);
20285 } else if (FDTy->isObjCObjectType()) {
20286 /// A field cannot be an Objective-c object
20287 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
20288 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
20289 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
20290 FD->setType(T);
20291 } else if (Record && Record->isUnion() &&
20292 FD->getType().hasNonTrivialObjCLifetime() &&
20293 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
20294 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20295 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
20296 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
20297 // For backward compatibility, fields of C unions declared in system
20298 // headers that have non-trivial ObjC ownership qualifications are marked
20299 // as unavailable unless the qualifier is explicit and __strong. This can
20300 // break ABI compatibility between programs compiled with ARC and MRR, but
20301 // is a better option than rejecting programs using those unions under
20302 // ARC.
20303 FD->addAttr(A: UnavailableAttr::CreateImplicit(
20304 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
20305 Range: FD->getLocation()));
20306 } else if (getLangOpts().ObjC &&
20307 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20308 !Record->hasObjectMember()) {
20309 if (FD->getType()->isObjCObjectPointerType() ||
20310 FD->getType().isObjCGCStrong())
20311 Record->setHasObjectMember(true);
20312 else if (Context.getAsArrayType(T: FD->getType())) {
20313 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
20314 if (const auto *RD = BaseType->getAsRecordDecl();
20315 RD && RD->hasObjectMember())
20316 Record->setHasObjectMember(true);
20317 else if (BaseType->isObjCObjectPointerType() ||
20318 BaseType.isObjCGCStrong())
20319 Record->setHasObjectMember(true);
20320 }
20321 }
20322
20323 if (Record && !getLangOpts().CPlusPlus &&
20324 !shouldIgnoreForRecordTriviality(FD)) {
20325 QualType FT = FD->getType();
20326 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
20327 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20328 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
20329 Record->isUnion())
20330 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20331 }
20332 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
20333 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
20334 Record->setNonTrivialToPrimitiveCopy(true);
20335 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20336 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20337 }
20338 if (FD->hasAttr<ExplicitInitAttr>())
20339 Record->setHasUninitializedExplicitInitFields(true);
20340 if (FT.isDestructedType()) {
20341 Record->setNonTrivialToPrimitiveDestroy(true);
20342 Record->setParamDestroyedInCallee(true);
20343 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20344 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20345 }
20346
20347 if (const auto *RD = FT->getAsRecordDecl()) {
20348 if (RD->getArgPassingRestrictions() ==
20349 RecordArgPassingKind::CanNeverPassInRegs)
20350 Record->setArgPassingRestrictions(
20351 RecordArgPassingKind::CanNeverPassInRegs);
20352 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20353 Record->setArgPassingRestrictions(
20354 RecordArgPassingKind::CanNeverPassInRegs);
20355 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20356 Q && Q.isAddressDiscriminated()) {
20357 Record->setArgPassingRestrictions(
20358 RecordArgPassingKind::CanNeverPassInRegs);
20359 Record->setNonTrivialToPrimitiveCopy(true);
20360 }
20361 }
20362
20363 if (Record && FD->getType().isVolatileQualified())
20364 Record->setHasVolatileMember(true);
20365 bool ReportMSBitfieldStoragePacking =
20366 Record && PreviousField &&
20367 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
20368 Loc: Record->getLocation());
20369 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20370 return FD->isBitField() && !FD->getType()->isDependentType();
20371 };
20372
20373 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20374 IsNonDependentBitField(PreviousField)) {
20375 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
20376 CharUnits PreviousFieldStorageSize =
20377 Context.getTypeSizeInChars(T: PreviousField->getType());
20378 if (FDStorageSize != PreviousFieldStorageSize) {
20379 Diag(Loc: FD->getLocation(),
20380 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
20381 << FD << FD->getType() << FDStorageSize.getQuantity()
20382 << PreviousFieldStorageSize.getQuantity();
20383 Diag(Loc: PreviousField->getLocation(),
20384 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
20385 << PreviousField << PreviousField->getType();
20386 }
20387 }
20388 // Keep track of the number of named members.
20389 if (FD->getIdentifier())
20390 ++NumNamedMembers;
20391 }
20392
20393 // Okay, we successfully defined 'Record'.
20394 if (Record) {
20395 bool Completed = false;
20396 if (S) {
20397 Scope *Parent = S->getParent();
20398 if (Parent && Parent->isTypeAliasScope() &&
20399 Parent->isTemplateParamScope())
20400 Record->setInvalidDecl();
20401 }
20402
20403 if (CXXRecord) {
20404 if (!CXXRecord->isInvalidDecl()) {
20405 // Set access bits correctly on the directly-declared conversions.
20406 for (CXXRecordDecl::conversion_iterator
20407 I = CXXRecord->conversion_begin(),
20408 E = CXXRecord->conversion_end(); I != E; ++I)
20409 I.setAccess((*I)->getAccess());
20410 }
20411
20412 // Add any implicitly-declared members to this class.
20413 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
20414
20415 if (!CXXRecord->isDependentType()) {
20416 if (!CXXRecord->isInvalidDecl()) {
20417 // If we have virtual base classes, we may end up finding multiple
20418 // final overriders for a given virtual function. Check for this
20419 // problem now.
20420 if (CXXRecord->getNumVBases()) {
20421 CXXFinalOverriderMap FinalOverriders;
20422 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
20423
20424 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20425 MEnd = FinalOverriders.end();
20426 M != MEnd; ++M) {
20427 for (OverridingMethods::iterator SO = M->second.begin(),
20428 SOEnd = M->second.end();
20429 SO != SOEnd; ++SO) {
20430 assert(SO->second.size() > 0 &&
20431 "Virtual function without overriding functions?");
20432 if (SO->second.size() == 1)
20433 continue;
20434
20435 // C++ [class.virtual]p2:
20436 // In a derived class, if a virtual member function of a base
20437 // class subobject has more than one final overrider the
20438 // program is ill-formed.
20439 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
20440 << (const NamedDecl *)M->first << Record;
20441 Diag(Loc: M->first->getLocation(),
20442 DiagID: diag::note_overridden_virtual_function);
20443 for (OverridingMethods::overriding_iterator
20444 OM = SO->second.begin(),
20445 OMEnd = SO->second.end();
20446 OM != OMEnd; ++OM)
20447 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
20448 << (const NamedDecl *)M->first << OM->Method->getParent();
20449
20450 Record->setInvalidDecl();
20451 }
20452 }
20453 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
20454 Completed = true;
20455 }
20456 }
20457 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
20458 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
20459 }
20460 }
20461
20462 if (!Completed)
20463 Record->completeDefinition();
20464
20465 // Handle attributes before checking the layout.
20466 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
20467
20468 // Maybe randomize the record's decls. We automatically randomize a record
20469 // of function pointers, unless it has the "no_randomize_layout" attribute.
20470 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20471 !Record->isRandomized() && !Record->isUnion() &&
20472 (Record->hasAttr<RandomizeLayoutAttr>() ||
20473 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20474 EntirelyFunctionPointers(Record)))) {
20475 SmallVector<Decl *, 32> NewDeclOrdering;
20476 if (randstruct::randomizeStructureLayout(Context, RD: Record,
20477 FinalOrdering&: NewDeclOrdering))
20478 Record->reorderDecls(Decls: NewDeclOrdering);
20479 }
20480
20481 // We may have deferred checking for a deleted destructor. Check now.
20482 if (CXXRecord) {
20483 auto *Dtor = CXXRecord->getDestructor();
20484 if (Dtor && Dtor->isImplicit() &&
20485 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
20486 CXXRecord->setImplicitDestructorIsDeleted();
20487 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
20488 }
20489 }
20490
20491 if (Record->hasAttrs()) {
20492 CheckAlignasUnderalignment(D: Record);
20493
20494 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20495 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
20496 Range: IA->getRange(), BestCase: IA->getBestCase(),
20497 SemanticSpelling: IA->getInheritanceModel());
20498 }
20499
20500 // Check if the structure/union declaration is a type that can have zero
20501 // size in C. For C this is a language extension, for C++ it may cause
20502 // compatibility problems.
20503 bool CheckForZeroSize;
20504 if (!getLangOpts().CPlusPlus) {
20505 CheckForZeroSize = true;
20506 } else {
20507 // For C++ filter out types that cannot be referenced in C code.
20508 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
20509 CheckForZeroSize =
20510 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20511 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20512 CXXRecord->isCLike();
20513 }
20514 if (CheckForZeroSize) {
20515 bool ZeroSize = true;
20516 bool IsEmpty = true;
20517 unsigned NonBitFields = 0;
20518 for (RecordDecl::field_iterator I = Record->field_begin(),
20519 E = Record->field_end();
20520 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20521 IsEmpty = false;
20522 if (I->isUnnamedBitField()) {
20523 if (!I->isZeroLengthBitField())
20524 ZeroSize = false;
20525 } else {
20526 ++NonBitFields;
20527 QualType FieldType = I->getType();
20528 if (FieldType->isIncompleteType() ||
20529 !Context.getTypeSizeInChars(T: FieldType).isZero())
20530 ZeroSize = false;
20531 }
20532 }
20533
20534 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20535 // allowed in C++, but warn if its declaration is inside
20536 // extern "C" block.
20537 if (ZeroSize) {
20538 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
20539 diag::warn_zero_size_struct_union_in_extern_c :
20540 diag::warn_zero_size_struct_union_compat)
20541 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20542 }
20543
20544 // Structs without named members are extension in C (C99 6.7.2.1p7),
20545 // but are accepted by GCC. In C2y, this became implementation-defined
20546 // (C2y 6.7.3.2p10).
20547 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20548 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
20549 : diag::ext_no_named_members_in_struct_union)
20550 << Record->isUnion();
20551 }
20552 }
20553 } else {
20554 ObjCIvarDecl **ClsFields =
20555 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20556 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
20557 ID->setEndOfDefinitionLoc(RBrac);
20558 // Add ivar's to class's DeclContext.
20559 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20560 ClsFields[i]->setLexicalDeclContext(ID);
20561 ID->addDecl(D: ClsFields[i]);
20562 }
20563 // Must enforce the rule that ivars in the base classes may not be
20564 // duplicates.
20565 if (ID->getSuperClass())
20566 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
20567 } else if (ObjCImplementationDecl *IMPDecl =
20568 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
20569 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20570 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20571 // Ivar declared in @implementation never belongs to the implementation.
20572 // Only it is in implementation's lexical context.
20573 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20574 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
20575 Loc: RBrac);
20576 IMPDecl->setIvarLBraceLoc(LBrac);
20577 IMPDecl->setIvarRBraceLoc(RBrac);
20578 } else if (ObjCCategoryDecl *CDecl =
20579 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
20580 // case of ivars in class extension; all other cases have been
20581 // reported as errors elsewhere.
20582 // FIXME. Class extension does not have a LocEnd field.
20583 // CDecl->setLocEnd(RBrac);
20584 // Add ivar's to class extension's DeclContext.
20585 // Diagnose redeclaration of private ivars.
20586 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20587 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20588 if (IDecl) {
20589 if (const ObjCIvarDecl *ClsIvar =
20590 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20591 Diag(Loc: ClsFields[i]->getLocation(),
20592 DiagID: diag::err_duplicate_ivar_declaration);
20593 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
20594 continue;
20595 }
20596 for (const auto *Ext : IDecl->known_extensions()) {
20597 if (const ObjCIvarDecl *ClsExtIvar
20598 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20599 Diag(Loc: ClsFields[i]->getLocation(),
20600 DiagID: diag::err_duplicate_ivar_declaration);
20601 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
20602 continue;
20603 }
20604 }
20605 }
20606 ClsFields[i]->setLexicalDeclContext(CDecl);
20607 CDecl->addDecl(D: ClsFields[i]);
20608 }
20609 CDecl->setIvarLBraceLoc(LBrac);
20610 CDecl->setIvarRBraceLoc(RBrac);
20611 }
20612 }
20613
20614 if (Record)
20615 AMDGPU().checkNamedBarrierWrapper(R: Record);
20616
20617 if (Record && !isa<ClassTemplateSpecializationDecl>(Val: Record))
20618 ProcessAPINotes(D: Record);
20619}
20620
20621// Given an integral type, return the next larger integral type
20622// (or a NULL type of no such type exists).
20623static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20624 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20625 // enum checking below.
20626 assert((T->isIntegralType(Context) ||
20627 T->isEnumeralType()) && "Integral type required!");
20628 const unsigned NumTypes = 4;
20629 QualType SignedIntegralTypes[NumTypes] = {
20630 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20631 };
20632 QualType UnsignedIntegralTypes[NumTypes] = {
20633 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20634 Context.UnsignedLongLongTy
20635 };
20636
20637 // Compare value widths, not storage sizes: a _BitInt(33) is stored in 64
20638 // bits but a 64-bit standard type can still represent its incremented
20639 // value. C23 6.7.3.3p12 does not allow the widened type to be a
20640 // bit-precise type either.
20641 unsigned BitWidth = Context.getIntWidth(T);
20642 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20643 : UnsignedIntegralTypes;
20644 for (unsigned I = 0; I != NumTypes; ++I)
20645 if (Context.getTypeSize(T: Types[I]) > BitWidth)
20646 return Types[I];
20647
20648 return QualType();
20649}
20650
20651EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20652 EnumConstantDecl *LastEnumConst,
20653 SourceLocation IdLoc,
20654 IdentifierInfo *Id,
20655 Expr *Val) {
20656 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20657 llvm::APSInt EnumVal(IntWidth);
20658 QualType EltTy;
20659
20660 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
20661 Val = nullptr;
20662
20663 if (Val)
20664 Val = DefaultLvalueConversion(E: Val).get();
20665
20666 if (Val) {
20667 if (Enum->isDependentType() || Val->isTypeDependent() ||
20668 Val->containsErrors())
20669 EltTy = Context.DependentTy;
20670 else {
20671 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20672 // underlying type, but do allow it in all other contexts.
20673 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20674 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20675 // constant-expression in the enumerator-definition shall be a converted
20676 // constant expression of the underlying type.
20677 EltTy = Enum->getIntegerType();
20678 ExprResult Converted = CheckConvertedConstantExpression(
20679 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
20680 if (Converted.isInvalid())
20681 Val = nullptr;
20682 else
20683 Val = Converted.get();
20684 } else if (!Val->isValueDependent() &&
20685 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
20686 CanFold: AllowFoldKind::Allow)
20687 .get())) {
20688 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20689 } else {
20690 if (Enum->isComplete()) {
20691 EltTy = Enum->getIntegerType();
20692
20693 // In Obj-C and Microsoft mode, require the enumeration value to be
20694 // representable in the underlying type of the enumeration. In C++11,
20695 // we perform a non-narrowing conversion as part of converted constant
20696 // expression checking.
20697 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20698 if (Context.getTargetInfo()
20699 .getTriple()
20700 .isWindowsMSVCEnvironment()) {
20701 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
20702 } else {
20703 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
20704 }
20705 }
20706
20707 // Cast to the underlying type.
20708 Val = ImpCastExprToType(E: Val, Type: EltTy,
20709 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
20710 : CK_IntegralCast)
20711 .get();
20712 } else if (getLangOpts().CPlusPlus) {
20713 // C++11 [dcl.enum]p5:
20714 // If the underlying type is not fixed, the type of each enumerator
20715 // is the type of its initializing value:
20716 // - If an initializer is specified for an enumerator, the
20717 // initializing value has the same type as the expression.
20718 EltTy = Val->getType();
20719 } else {
20720 // C99 6.7.2.2p2:
20721 // The expression that defines the value of an enumeration constant
20722 // shall be an integer constant expression that has a value
20723 // representable as an int.
20724
20725 // Complain if the value is not representable in an int.
20726 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20727 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20728 ? diag::warn_c17_compat_enum_value_not_int
20729 : diag::ext_c23_enum_value_not_int)
20730 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20731 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20732 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20733 // Force the type of the expression to 'int'.
20734 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20735 }
20736 EltTy = Val->getType();
20737 }
20738 }
20739 }
20740 }
20741
20742 if (!Val) {
20743 if (Enum->isDependentType())
20744 EltTy = Context.DependentTy;
20745 else if (!LastEnumConst) {
20746 // C++0x [dcl.enum]p5:
20747 // If the underlying type is not fixed, the type of each enumerator
20748 // is the type of its initializing value:
20749 // - If no initializer is specified for the first enumerator, the
20750 // initializing value has an unspecified integral type.
20751 //
20752 // GCC uses 'int' for its unspecified integral type, as does
20753 // C99 6.7.2.2p3.
20754 if (Enum->isFixed()) {
20755 EltTy = Enum->getIntegerType();
20756 }
20757 else {
20758 EltTy = Context.IntTy;
20759 }
20760 } else {
20761 // Assign the last value + 1.
20762 EnumVal = LastEnumConst->getInitVal();
20763 ++EnumVal;
20764 EltTy = LastEnumConst->getType();
20765
20766 // Check for overflow on increment.
20767 if (EnumVal < LastEnumConst->getInitVal()) {
20768 // C++0x [dcl.enum]p5:
20769 // If the underlying type is not fixed, the type of each enumerator
20770 // is the type of its initializing value:
20771 //
20772 // - Otherwise the type of the initializing value is the same as
20773 // the type of the initializing value of the preceding enumerator
20774 // unless the incremented value is not representable in that type,
20775 // in which case the type is an unspecified integral type
20776 // sufficient to contain the incremented value. If no such type
20777 // exists, the program is ill-formed.
20778 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20779 if (T.isNull() || Enum->isFixed()) {
20780 // There is no integral type larger enough to represent this
20781 // value. Complain, then allow the value to wrap around.
20782 EnumVal = LastEnumConst->getInitVal();
20783 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20784 ++EnumVal;
20785 if (Enum->isFixed())
20786 // When the underlying type is fixed, this is ill-formed.
20787 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20788 << toString(I: EnumVal, Radix: 10)
20789 << EltTy;
20790 else
20791 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20792 << toString(I: EnumVal, Radix: 10);
20793 } else {
20794 EltTy = T;
20795 }
20796
20797 // Retrieve the last enumerator's value, extent that type to the
20798 // type that is supposed to be large enough to represent the incremented
20799 // value, then increment.
20800 EnumVal = LastEnumConst->getInitVal();
20801 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20802 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20803 ++EnumVal;
20804
20805 // If we're not in C++, diagnose the overflow of enumerator values,
20806 // which in C99 means that the enumerator value is not representable in
20807 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20808 // are representable in some larger integral type and we allow it in
20809 // older language modes as an extension.
20810 // Exclude fixed enumerators since they are diagnosed with an error for
20811 // this case.
20812 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20813 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20814 ? diag::warn_c17_compat_enum_value_not_int
20815 : diag::ext_c23_enum_value_not_int)
20816 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20817 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20818 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20819 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20820 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20821 : diag::ext_c23_enum_value_not_int)
20822 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20823 }
20824 }
20825 }
20826
20827 if (!EltTy->isDependentType()) {
20828 // Make the enumerator value match the signedness and size of the
20829 // enumerator's type.
20830 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20831 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20832 }
20833
20834 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20835 E: Val, V: EnumVal);
20836}
20837
20838SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20839 SourceLocation IILoc) {
20840 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20841 !getLangOpts().CPlusPlus)
20842 return SkipBodyInfo();
20843
20844 // We have an anonymous enum definition. Look up the first enumerator to
20845 // determine if we should merge the definition with an existing one and
20846 // skip the body.
20847 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20848 Redecl: forRedeclarationInCurContext());
20849 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20850 if (!PrevECD)
20851 return SkipBodyInfo();
20852
20853 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20854 NamedDecl *Hidden;
20855 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20856 SkipBodyInfo Skip;
20857 Skip.Previous = Hidden;
20858 return Skip;
20859 }
20860
20861 return SkipBodyInfo();
20862}
20863
20864Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20865 SourceLocation IdLoc, IdentifierInfo *Id,
20866 const ParsedAttributesView &Attrs,
20867 SourceLocation EqualLoc, Expr *Val,
20868 SkipBodyInfo *SkipBody) {
20869 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20870 EnumConstantDecl *LastEnumConst =
20871 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20872
20873 // The scope passed in may not be a decl scope. Zip up the scope tree until
20874 // we find one that is.
20875 S = getNonFieldDeclScope(S);
20876
20877 // Verify that there isn't already something declared with this name in this
20878 // scope.
20879 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20880 RedeclarationKind::ForVisibleRedeclaration);
20881 LookupName(R, S);
20882 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20883
20884 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20885 // Maybe we will complain about the shadowed template parameter.
20886 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20887 // Just pretend that we didn't see the previous declaration.
20888 PrevDecl = nullptr;
20889 }
20890
20891 // C++ [class.mem]p15:
20892 // If T is the name of a class, then each of the following shall have a name
20893 // different from T:
20894 // - every enumerator of every member of class T that is an unscoped
20895 // enumerated type
20896 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20897 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20898 NameInfo: DeclarationNameInfo(Id, IdLoc)))
20899 return nullptr;
20900
20901 EnumConstantDecl *New =
20902 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20903 if (!New)
20904 return nullptr;
20905
20906 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20907 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20908 // Check for other kinds of shadowing not already handled.
20909 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
20910 }
20911
20912 // When in C++, we may get a TagDecl with the same name; in this case the
20913 // enum constant will 'hide' the tag.
20914 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20915 "Received TagDecl when not in C++!");
20916 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20917 if (isa<EnumConstantDecl>(Val: PrevDecl))
20918 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
20919 else
20920 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
20921 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20922 return nullptr;
20923 }
20924 }
20925
20926 // Process attributes.
20927 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
20928 AddPragmaAttributes(S, D: New);
20929 ProcessAPINotes(D: New);
20930
20931 // Register this decl in the current scope stack.
20932 New->setAccess(TheEnumDecl->getAccess());
20933 PushOnScopeChains(D: New, S);
20934
20935 ActOnDocumentableDecl(D: New);
20936
20937 return New;
20938}
20939
20940// Returns true when the enum initial expression does not trigger the
20941// duplicate enum warning. A few common cases are exempted as follows:
20942// Element2 = Element1
20943// Element2 = Element1 + 1
20944// Element2 = Element1 - 1
20945// Where Element2 and Element1 are from the same enum.
20946static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20947 Expr *InitExpr = ECD->getInitExpr();
20948 if (!InitExpr)
20949 return true;
20950 InitExpr = InitExpr->IgnoreImpCasts();
20951
20952 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20953 if (!BO->isAdditiveOp())
20954 return true;
20955 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20956 if (!IL)
20957 return true;
20958 if (IL->getValue() != 1)
20959 return true;
20960
20961 InitExpr = BO->getLHS();
20962 }
20963
20964 // This checks if the elements are from the same enum.
20965 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20966 if (!DRE)
20967 return true;
20968
20969 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20970 if (!EnumConstant)
20971 return true;
20972
20973 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20974 Enum)
20975 return true;
20976
20977 return false;
20978}
20979
20980// Emits a warning when an element is implicitly set a value that
20981// a previous element has already been set to.
20982static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20983 EnumDecl *Enum, QualType EnumType) {
20984 // Avoid anonymous enums
20985 if (!Enum->getIdentifier())
20986 return;
20987
20988 // Only check for small enums.
20989 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20990 return;
20991
20992 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
20993 return;
20994
20995 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20996 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20997
20998 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20999
21000 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
21001 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
21002
21003 // Use int64_t as a key to avoid needing special handling for map keys.
21004 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
21005 llvm::APSInt Val = D->getInitVal();
21006 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
21007 };
21008
21009 DuplicatesVector DupVector;
21010 ValueToVectorMap EnumMap;
21011
21012 // Populate the EnumMap with all values represented by enum constants without
21013 // an initializer.
21014 for (auto *Element : Elements) {
21015 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
21016
21017 // Null EnumConstantDecl means a previous diagnostic has been emitted for
21018 // this constant. Skip this enum since it may be ill-formed.
21019 if (!ECD) {
21020 return;
21021 }
21022
21023 // Constants with initializers are handled in the next loop.
21024 if (ECD->getInitExpr())
21025 continue;
21026
21027 // Duplicate values are handled in the next loop.
21028 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
21029 }
21030
21031 if (EnumMap.size() == 0)
21032 return;
21033
21034 // Create vectors for any values that has duplicates.
21035 for (auto *Element : Elements) {
21036 // The last loop returned if any constant was null.
21037 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
21038 if (!ValidDuplicateEnum(ECD, Enum))
21039 continue;
21040
21041 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
21042 if (Iter == EnumMap.end())
21043 continue;
21044
21045 DeclOrVector& Entry = Iter->second;
21046 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
21047 // Ensure constants are different.
21048 if (D == ECD)
21049 continue;
21050
21051 // Create new vector and push values onto it.
21052 auto Vec = std::make_unique<ECDVector>();
21053 Vec->push_back(Elt: D);
21054 Vec->push_back(Elt: ECD);
21055
21056 // Update entry to point to the duplicates vector.
21057 Entry = Vec.get();
21058
21059 // Store the vector somewhere we can consult later for quick emission of
21060 // diagnostics.
21061 DupVector.emplace_back(Args: std::move(Vec));
21062 continue;
21063 }
21064
21065 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
21066 // Make sure constants are not added more than once.
21067 if (*Vec->begin() == ECD)
21068 continue;
21069
21070 Vec->push_back(Elt: ECD);
21071 }
21072
21073 // Emit diagnostics.
21074 for (const auto &Vec : DupVector) {
21075 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
21076
21077 // Emit warning for one enum constant.
21078 auto *FirstECD = Vec->front();
21079 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
21080 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
21081 << FirstECD->getSourceRange();
21082
21083 // Emit one note for each of the remaining enum constants with
21084 // the same value.
21085 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
21086 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
21087 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
21088 << ECD->getSourceRange();
21089 }
21090}
21091
21092bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
21093 bool AllowMask) const {
21094 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
21095 assert(ED->isCompleteDefinition() && "expected enum definition");
21096
21097 llvm::APInt FlagBits = FlagBitsCache.at(Val: ED);
21098
21099 // A value is in a flag enum if either its bits are a subset of the enum's
21100 // flag bits (the first condition) or we are allowing masks and the same is
21101 // true of its complement (the second condition). When masks are allowed, we
21102 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
21103 //
21104 // While it's true that any value could be used as a mask, the assumption is
21105 // that a mask will have all of the insignificant bits set. Anything else is
21106 // likely a logic error.
21107 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
21108 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
21109}
21110
21111// Emits a warning when a suspicious comparison operator is used along side
21112// binary operators in enum initializers.
21113static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
21114 const EnumDecl *Enum) {
21115 bool HasBitwiseOp = false;
21116 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
21117
21118 // Iterate over all the enum values, gather suspisious comparison ops and
21119 // whether any enum initialisers contain a binary operator.
21120 for (const auto *ECD : Enum->enumerators()) {
21121 const Expr *InitExpr = ECD->getInitExpr();
21122 if (!InitExpr)
21123 continue;
21124
21125 const Expr *E = InitExpr->IgnoreParenImpCasts();
21126
21127 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
21128 BinaryOperatorKind Op = BinOp->getOpcode();
21129
21130 // Check for bitwise ops (<<, >>, &, |)
21131 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
21132 HasBitwiseOp = true;
21133 } else if (Op == BO_LT || Op == BO_GT) {
21134 // Check for the typo pattern (Comparison < or >)
21135 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
21136 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHS)) {
21137 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
21138 if (IntLiteral->getValue() == 1)
21139 SuspiciousCompares.push_back(Elt: BinOp);
21140 }
21141 }
21142 }
21143 }
21144
21145 // If we found a bitwise op and some sus compares, iterate over the compares
21146 // and warn.
21147 if (HasBitwiseOp) {
21148 for (const auto *BinOp : SuspiciousCompares) {
21149 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
21150 ? BinaryOperator::getOpcodeStr(Op: BO_Shl)
21151 : BinaryOperator::getOpcodeStr(Op: BO_Shr);
21152 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
21153
21154 Sema.Diag(Loc: OperatorLoc, DiagID: diag::warn_comparison_in_enum_initializer)
21155 << BinOp->getOpcodeStr() << SuggestedOp;
21156
21157 Sema.Diag(Loc: OperatorLoc, DiagID: diag::note_enum_compare_typo_suggest)
21158 << SuggestedOp
21159 << FixItHint::CreateReplacement(RemoveRange: OperatorLoc, Code: SuggestedOp);
21160 }
21161 }
21162}
21163
21164void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
21165 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
21166 const ParsedAttributesView &Attrs) {
21167 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
21168 CanQualType EnumType = Context.getCanonicalTagType(TD: Enum);
21169
21170 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
21171 ProcessAPINotes(D: Enum);
21172
21173 if (Enum->isDependentType()) {
21174 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
21175 EnumConstantDecl *ECD =
21176 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
21177 if (!ECD) continue;
21178
21179 ECD->setType(EnumType);
21180 }
21181
21182 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
21183 return;
21184 }
21185
21186 // Verify that all the values are okay, compute the size of the values, and
21187 // reverse the list.
21188 unsigned NumNegativeBits = 0;
21189 unsigned NumPositiveBits = 0;
21190 bool MembersRepresentableByInt =
21191 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
21192
21193 // Figure out the type that should be used for this enum.
21194 QualType BestType;
21195 unsigned BestWidth;
21196
21197 // C++0x N3000 [conv.prom]p3:
21198 // An rvalue of an unscoped enumeration type whose underlying
21199 // type is not fixed can be converted to an rvalue of the first
21200 // of the following types that can represent all the values of
21201 // the enumeration: int, unsigned int, long int, unsigned long
21202 // int, long long int, or unsigned long long int.
21203 // C99 6.4.4.3p2:
21204 // An identifier declared as an enumeration constant has type int.
21205 // The C99 rule is modified by C23.
21206 QualType BestPromotionType;
21207
21208 bool Packed = Enum->hasAttr<PackedAttr>();
21209 // -fshort-enums is the equivalent to specifying the packed attribute on all
21210 // enum definitions.
21211 if (LangOpts.ShortEnums)
21212 Packed = true;
21213
21214 // If the enum already has a type because it is fixed or dictated by the
21215 // target, promote that type instead of analyzing the enumerators.
21216 if (Enum->isComplete()) {
21217 BestType = Enum->getIntegerType();
21218 if (Context.isPromotableIntegerType(T: BestType))
21219 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
21220 else
21221 BestPromotionType = BestType;
21222
21223 BestWidth = Context.getIntWidth(T: BestType);
21224 } else {
21225 bool EnumTooLarge = Context.computeBestEnumTypes(
21226 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21227 BestWidth = Context.getIntWidth(T: BestType);
21228 if (EnumTooLarge)
21229 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
21230 }
21231
21232 // Loop over all of the enumerator constants, changing their types to match
21233 // the type of the enum if needed.
21234 for (auto *D : Elements) {
21235 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21236 if (!ECD) continue; // Already issued a diagnostic.
21237
21238 // C99 says the enumerators have int type, but we allow, as an
21239 // extension, the enumerators to be larger than int size. If each
21240 // enumerator value fits in an int, type it as an int, otherwise type it the
21241 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21242 // that X has type 'int', not 'unsigned'.
21243
21244 // Determine whether the value fits into an int.
21245 llvm::APSInt InitVal = ECD->getInitVal();
21246
21247 // If it fits into an integer type, force it. Otherwise force it to match
21248 // the enum decl type.
21249 QualType NewTy;
21250 unsigned NewWidth;
21251 bool NewSign;
21252 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21253 MembersRepresentableByInt) {
21254 // C23 6.7.3.3.3p15:
21255 // The enumeration member type for an enumerated type without fixed
21256 // underlying type upon completion is:
21257 // - int if all the values of the enumeration are representable as an
21258 // int; or,
21259 // - the enumerated type
21260 NewTy = Context.IntTy;
21261 NewWidth = Context.getTargetInfo().getIntWidth();
21262 NewSign = true;
21263 } else if (ECD->getType() == BestType) {
21264 // Already the right type!
21265 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21266 // C++ [dcl.enum]p4: Following the closing brace of an
21267 // enum-specifier, each enumerator has the type of its
21268 // enumeration.
21269 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21270 // with fixed underlying type is the enumerated type.
21271 ECD->setType(EnumType);
21272 continue;
21273 } else {
21274 NewTy = BestType;
21275 NewWidth = BestWidth;
21276 NewSign = BestType->isSignedIntegerOrEnumerationType();
21277 }
21278
21279 // Adjust the APSInt value.
21280 InitVal = InitVal.extOrTrunc(width: NewWidth);
21281 InitVal.setIsSigned(NewSign);
21282 ECD->setInitVal(C: Context, V: InitVal);
21283
21284 // Adjust the Expr initializer and type.
21285 if (ECD->getInitExpr() &&
21286 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
21287 ECD->setInitExpr(ImplicitCastExpr::Create(
21288 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
21289 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
21290 if (getLangOpts().CPlusPlus ||
21291 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21292 // C++ [dcl.enum]p4: Following the closing brace of an
21293 // enum-specifier, each enumerator has the type of its
21294 // enumeration.
21295 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21296 // with fixed underlying type is the enumerated type.
21297 ECD->setType(EnumType);
21298 else
21299 ECD->setType(NewTy);
21300 }
21301
21302 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
21303 NumPositiveBits, NumNegativeBits);
21304
21305 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
21306 CheckForComparisonInEnumInitializer(Sema&: *this, Enum);
21307
21308 if (Enum->hasAttr<FlagEnumAttr>()) {
21309 auto R = FlagBitsCache.try_emplace(Key: Enum);
21310 llvm::APInt &FlagBits = R.first->second;
21311
21312 if (R.second) {
21313 for (auto *E : Enum->enumerators()) {
21314 const auto &EVal = E->getInitVal();
21315 // Only single-bit enumerators introduce new flag values.
21316 if (EVal.isPowerOf2())
21317 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
21318 }
21319 }
21320 }
21321
21322 if (Enum->isClosedFlag()) {
21323 for (Decl *D : Elements) {
21324 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
21325 if (!ECD) continue; // Already issued a diagnostic.
21326
21327 llvm::APSInt InitVal = ECD->getInitVal();
21328 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21329 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
21330 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
21331 << ECD << Enum;
21332 }
21333 }
21334
21335 // Now that the enum type is defined, ensure it's not been underaligned.
21336 if (Enum->hasAttrs())
21337 CheckAlignasUnderalignment(D: Enum);
21338}
21339
21340Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
21341 SourceLocation EndLoc) {
21342
21343 FileScopeAsmDecl *New =
21344 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
21345 CurContext->addDecl(D: New);
21346 return New;
21347}
21348
21349TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
21350 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
21351 CurContext->addDecl(D: New);
21352 PushDeclContext(S, DC: New);
21353 PushFunctionScope();
21354 PushCompoundScope(IsStmtExpr: false);
21355 return New;
21356}
21357
21358void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
21359 if (Statement)
21360 D->setStmt(Statement);
21361 PopCompoundScope();
21362 PopFunctionScopeInfo();
21363 PopDeclContext();
21364}
21365
21366void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
21367 IdentifierInfo* AliasName,
21368 SourceLocation PragmaLoc,
21369 SourceLocation NameLoc,
21370 SourceLocation AliasNameLoc) {
21371 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
21372 NameKind: LookupOrdinaryName);
21373 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21374 AttributeCommonInfo::Form::Pragma());
21375 AsmLabelAttr *Attr =
21376 AsmLabelAttr::CreateImplicit(Ctx&: Context, Label: AliasName->getName(), CommonInfo: Info);
21377
21378 // If a declaration that:
21379 // 1) declares a function or a variable
21380 // 2) has external linkage
21381 // already exists, add a label attribute to it.
21382 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21383 if (isDeclExternC(D: PrevDecl))
21384 PrevDecl->addAttr(A: Attr);
21385 else
21386 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
21387 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
21388 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21389 } else
21390 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
21391}
21392
21393void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
21394 SourceLocation PragmaLoc,
21395 SourceLocation NameLoc) {
21396 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
21397
21398 if (PrevDecl) {
21399 PrevDecl->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc));
21400 } else {
21401 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
21402 }
21403}
21404
21405void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
21406 IdentifierInfo* AliasName,
21407 SourceLocation PragmaLoc,
21408 SourceLocation NameLoc,
21409 SourceLocation AliasNameLoc) {
21410 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
21411 NameKind: LookupOrdinaryName);
21412 WeakInfo W = WeakInfo(Name, NameLoc);
21413
21414 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21415 if (!PrevDecl->hasAttr<AliasAttr>())
21416 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
21417 DeclApplyPragmaWeak(S: TUScope, ND, W);
21418 } else {
21419 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
21420 }
21421}
21422
21423Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21424 bool Final) {
21425 assert(FD && "Expected non-null FunctionDecl");
21426
21427 // Templates are emitted when they're instantiated.
21428 if (FD->isDependentContext())
21429 return FunctionEmissionStatus::TemplateDiscarded;
21430
21431 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21432 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21433 FD->hasAttr<SYCLExternalAttr>()))
21434 return FunctionEmissionStatus::Emitted;
21435
21436 // Check whether this function is an externally visible definition.
21437 auto IsEmittedForExternalSymbol = [this, FD]() {
21438 // We have to check the GVA linkage of the function's *definition* -- if we
21439 // only have a declaration, we don't know whether or not the function will
21440 // be emitted, because (say) the definition could include "inline".
21441 const FunctionDecl *Def = FD->getDefinition();
21442
21443 // We can't compute linkage when we skip function bodies.
21444 return Def && !Def->hasSkippedBody() &&
21445 !isDiscardableGVALinkage(
21446 L: getASTContext().GetGVALinkageForFunction(FD: Def));
21447 };
21448
21449 if (LangOpts.OpenMPIsTargetDevice) {
21450 // In OpenMP device mode we will not emit host only functions, or functions
21451 // we don't need due to their linkage.
21452 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21453 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21454 // DevTy may be changed later by
21455 // #pragma omp declare target to(*) device_type(*).
21456 // Therefore DevTy having no value does not imply host. The emission status
21457 // will be checked again at the end of compilation unit with Final = true.
21458 if (DevTy)
21459 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21460 return FunctionEmissionStatus::OMPDiscarded;
21461 // If we have an explicit value for the device type, or we are in a target
21462 // declare context, we need to emit all extern and used symbols.
21463 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21464 if (IsEmittedForExternalSymbol())
21465 return FunctionEmissionStatus::Emitted;
21466 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21467 // we'll omit it.
21468 if (Final)
21469 return FunctionEmissionStatus::OMPDiscarded;
21470 } else if (LangOpts.OpenMP > 45) {
21471 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21472 // function. In 5.0, no_host was introduced which might cause a function to
21473 // be omitted.
21474 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21475 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21476 if (DevTy)
21477 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21478 return FunctionEmissionStatus::OMPDiscarded;
21479 }
21480
21481 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21482 return FunctionEmissionStatus::Emitted;
21483
21484 if (LangOpts.CUDA) {
21485 // When compiling for device, host functions are never emitted. Similarly,
21486 // when compiling for host, device and global functions are never emitted.
21487 // (Technically, we do emit a host-side stub for global functions, but this
21488 // doesn't count for our purposes here.)
21489 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
21490 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21491 return FunctionEmissionStatus::CUDADiscarded;
21492 if (!LangOpts.CUDAIsDevice &&
21493 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21494 return FunctionEmissionStatus::CUDADiscarded;
21495
21496 if (IsEmittedForExternalSymbol())
21497 return FunctionEmissionStatus::Emitted;
21498 }
21499
21500 // Otherwise, the function is known-emitted if it's in our set of
21501 // known-emitted functions.
21502 return FunctionEmissionStatus::Unknown;
21503}
21504
21505bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21506 // Host-side references to a __global__ function refer to the stub, so the
21507 // function itself is never emitted and therefore should not be marked.
21508 // If we have host fn calls kernel fn calls host+device, the HD function
21509 // does not get instantiated on the host. We model this by omitting at the
21510 // call to the kernel from the callgraph. This ensures that, when compiling
21511 // for host, only HD functions actually called from the host get marked as
21512 // known-emitted.
21513 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21514 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
21515}
21516
21517bool Sema::isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
21518 bool &Visible) {
21519 Visible = hasVisibleDefinition(D, Suggested);
21520 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21521 // for declaratins which is attached to named modules.
21522 // We only did this if the current module is named module as we have better
21523 // diagnostics for declarations in global module and named modules.
21524 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21525 D->isInNamedModule())
21526 return false;
21527 // The redefinition of D in the **current** TU is allowed if D is invisible or
21528 // D is defined in the global module of other module units.
21529 return D->isInAnotherModuleUnit() || !Visible;
21530}
21531