1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/MangleNumberingContext.h"
27#include "clang/AST/NonTrivialTypeVisitor.h"
28#include "clang/AST/Randstruct.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
31#include "clang/Basic/Builtins.h"
32#include "clang/Basic/DiagnosticComment.h"
33#include "clang/Basic/HLSLRuntime.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/TargetInfo.h"
37#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
38#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
39#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
40#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/CXXFieldCollector.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/DelayedDiagnostic.h"
44#include "clang/Sema/Initialization.h"
45#include "clang/Sema/Lookup.h"
46#include "clang/Sema/ParsedTemplate.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/ScopeInfo.h"
49#include "clang/Sema/SemaARM.h"
50#include "clang/Sema/SemaCUDA.h"
51#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaInternal.h"
53#include "clang/Sema/SemaObjC.h"
54#include "clang/Sema/SemaOpenACC.h"
55#include "clang/Sema/SemaOpenMP.h"
56#include "clang/Sema/SemaPPC.h"
57#include "clang/Sema/SemaRISCV.h"
58#include "clang/Sema/SemaSYCL.h"
59#include "clang/Sema/SemaSwift.h"
60#include "clang/Sema/SemaWasm.h"
61#include "clang/Sema/Template.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/STLForwardCompat.h"
64#include "llvm/ADT/ScopeExit.h"
65#include "llvm/ADT/SmallPtrSet.h"
66#include "llvm/ADT/SmallString.h"
67#include "llvm/ADT/StringExtras.h"
68#include "llvm/ADT/StringRef.h"
69#include "llvm/Support/SaveAndRestore.h"
70#include "llvm/TargetParser/Triple.h"
71#include <algorithm>
72#include <cstring>
73#include <optional>
74#include <unordered_map>
75
76using namespace clang;
77using namespace sema;
78
79Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
80 if (OwnedType) {
81 Decl *Group[2] = { OwnedType, Ptr };
82 return DeclGroupPtrTy::make(P: DeclGroupRef::Create(C&: Context, Decls: Group, NumDecls: 2));
83 }
84
85 return DeclGroupPtrTy::make(P: DeclGroupRef(Ptr));
86}
87
88namespace {
89
90class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
91 public:
92 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
93 bool AllowTemplates = false,
94 bool AllowNonTemplates = true)
95 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
96 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
97 WantExpressionKeywords = false;
98 WantCXXNamedCasts = false;
99 WantRemainingKeywords = false;
100 }
101
102 bool ValidateCandidate(const TypoCorrection &candidate) override {
103 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
104 if (!AllowInvalidDecl && ND->isInvalidDecl())
105 return false;
106
107 if (getAsTypeTemplateDecl(D: ND))
108 return AllowTemplates;
109
110 bool IsType = isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND);
111 if (!IsType)
112 return false;
113
114 if (AllowNonTemplates)
115 return true;
116
117 // An injected-class-name of a class template (specialization) is valid
118 // as a template or as a non-template.
119 if (AllowTemplates) {
120 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
121 if (!RD || !RD->isInjectedClassName())
122 return false;
123 RD = cast<CXXRecordDecl>(Val: RD->getDeclContext());
124 return RD->getDescribedClassTemplate() ||
125 isa<ClassTemplateSpecializationDecl>(Val: RD);
126 }
127
128 return false;
129 }
130
131 return !WantClassName && candidate.isKeyword();
132 }
133
134 std::unique_ptr<CorrectionCandidateCallback> clone() override {
135 return std::make_unique<TypeNameValidatorCCC>(args&: *this);
136 }
137
138 private:
139 bool AllowInvalidDecl;
140 bool WantClassName;
141 bool AllowTemplates;
142 bool AllowNonTemplates;
143};
144
145} // end anonymous namespace
146
147void Sema::checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK,
148 TypeDecl *TD, SourceLocation NameLoc) {
149 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
150 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: TD);
151 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
152 FoundRD->isInjectedClassName() &&
153 declaresSameEntity(D1: LookupRD, D2: cast<Decl>(Val: FoundRD->getParent()))) {
154 Diag(Loc: NameLoc,
155 DiagID: DCK == DiagCtorKind::Typename
156 ? diag::ext_out_of_line_qualified_id_type_names_constructor
157 : diag::err_out_of_line_qualified_id_type_names_constructor)
158 << TD->getIdentifier() << /*Type=*/1
159 << 0 /*if any keyword was present, it was 'typename'*/;
160 }
161
162 DiagnoseUseOfDecl(D: TD, Locs: NameLoc);
163 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
164}
165
166namespace {
167enum class UnqualifiedTypeNameLookupResult {
168 NotFound,
169 FoundNonType,
170 FoundType
171};
172} // end anonymous namespace
173
174/// Tries to perform unqualified lookup of the type decls in bases for
175/// dependent class.
176/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
177/// type decl, \a FoundType if only type decls are found.
178static UnqualifiedTypeNameLookupResult
179lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
180 SourceLocation NameLoc,
181 const CXXRecordDecl *RD) {
182 if (!RD->hasDefinition())
183 return UnqualifiedTypeNameLookupResult::NotFound;
184 // Look for type decls in base classes.
185 UnqualifiedTypeNameLookupResult FoundTypeDecl =
186 UnqualifiedTypeNameLookupResult::NotFound;
187 for (const auto &Base : RD->bases()) {
188 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
189 if (BaseRD) {
190 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
191 Val: Base.getType().getCanonicalType())) {
192 // Look for type decls in dependent base classes that have known primary
193 // templates.
194 if (!TST->isDependentType())
195 continue;
196 auto *TD = TST->getTemplateName().getAsTemplateDecl();
197 if (!TD)
198 continue;
199 if (auto *BasePrimaryTemplate =
200 dyn_cast_or_null<CXXRecordDecl>(Val: TD->getTemplatedDecl())) {
201 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
202 BaseRD = BasePrimaryTemplate;
203 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) {
204 if (const ClassTemplatePartialSpecializationDecl *PS =
205 CTD->findPartialSpecialization(T: Base.getType()))
206 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
207 BaseRD = PS;
208 }
209 }
210 }
211 if (BaseRD) {
212 for (NamedDecl *ND : BaseRD->lookup(Name: &II)) {
213 if (!isa<TypeDecl>(Val: ND))
214 return UnqualifiedTypeNameLookupResult::FoundNonType;
215 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
216 }
217 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
218 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD: BaseRD)) {
219 case UnqualifiedTypeNameLookupResult::FoundNonType:
220 return UnqualifiedTypeNameLookupResult::FoundNonType;
221 case UnqualifiedTypeNameLookupResult::FoundType:
222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
223 break;
224 case UnqualifiedTypeNameLookupResult::NotFound:
225 break;
226 }
227 }
228 }
229 }
230
231 return FoundTypeDecl;
232}
233
234static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
235 const IdentifierInfo &II,
236 SourceLocation NameLoc) {
237 // Lookup in the parent class template context, if any.
238 const CXXRecordDecl *RD = nullptr;
239 UnqualifiedTypeNameLookupResult FoundTypeDecl =
240 UnqualifiedTypeNameLookupResult::NotFound;
241 for (DeclContext *DC = S.CurContext;
242 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
243 DC = DC->getParent()) {
244 // Look for type decls in dependent base classes that have known primary
245 // templates.
246 RD = dyn_cast<CXXRecordDecl>(Val: DC);
247 if (RD && RD->getDescribedClassTemplate())
248 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
249 }
250 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
251 return nullptr;
252
253 // We found some types in dependent base classes. Recover as if the user
254 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
255 // allowed. We'll fully resolve the lookup during template instantiation.
256 S.Diag(Loc: NameLoc, DiagID: diag::ext_found_in_dependent_base) << &II;
257
258 ASTContext &Context = S.Context;
259 NestedNameSpecifier NNS(Context.getCanonicalTagType(TD: RD).getTypePtr());
260 QualType T =
261 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
262
263 CXXScopeSpec SS;
264 SS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
265
266 TypeLocBuilder Builder;
267 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
268 DepTL.setNameLoc(NameLoc);
269 DepTL.setElaboratedKeywordLoc(SourceLocation());
270 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
271 return S.CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
272}
273
274ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
275 Scope *S, CXXScopeSpec *SS, bool isClassName,
276 bool HasTrailingDot, ParsedType ObjectTypePtr,
277 bool IsCtorOrDtorName,
278 bool WantNontrivialTypeSourceInfo,
279 bool IsClassTemplateDeductionContext,
280 ImplicitTypenameContext AllowImplicitTypename,
281 IdentifierInfo **CorrectedII) {
282 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
283 // FIXME: Consider allowing this outside C++1z mode as an extension.
284 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
285 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
286 !HasTrailingDot;
287
288 // Determine where we will perform name lookup.
289 DeclContext *LookupCtx = nullptr;
290 if (ObjectTypePtr) {
291 QualType ObjectType = ObjectTypePtr.get();
292 if (ObjectType->isRecordType())
293 LookupCtx = computeDeclContext(T: ObjectType);
294 } else if (SS && SS->isNotEmpty()) {
295 LookupCtx = computeDeclContext(SS: *SS, EnteringContext: false);
296
297 if (!LookupCtx) {
298 if (isDependentScopeSpecifier(SS: *SS)) {
299 // C++ [temp.res]p3:
300 // A qualified-id that refers to a type and in which the
301 // nested-name-specifier depends on a template-parameter (14.6.2)
302 // shall be prefixed by the keyword typename to indicate that the
303 // qualified-id denotes a type, forming an
304 // elaborated-type-specifier (7.1.5.3).
305 //
306 // We therefore do not perform any name lookup if the result would
307 // refer to a member of an unknown specialization.
308 // In C++2a, in several contexts a 'typename' is not required. Also
309 // allow this as an extension.
310 if (IsImplicitTypename) {
311 if (AllowImplicitTypename == ImplicitTypenameContext::No)
312 return nullptr;
313 SourceLocation QualifiedLoc = SS->getRange().getBegin();
314 // FIXME: Defer the diagnostic after we build the type and use it.
315 auto DB = DiagCompat(Loc: QualifiedLoc, CompatDiagId: diag_compat::implicit_typename)
316 << Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
317 NNS: SS->getScopeRep(), Name: &II);
318 if (!getLangOpts().CPlusPlus20)
319 DB << FixItHint::CreateInsertion(InsertionLoc: QualifiedLoc, Code: "typename ");
320 }
321
322 // We know from the grammar that this name refers to a type,
323 // so build a dependent node to describe the type.
324 if (WantNontrivialTypeSourceInfo)
325 return ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II, IdLoc: NameLoc,
326 IsImplicitTypename: (ImplicitTypenameContext)IsImplicitTypename)
327 .get();
328
329 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
330 QualType T = CheckTypenameType(
331 Keyword: IsImplicitTypename ? ElaboratedTypeKeyword::Typename
332 : ElaboratedTypeKeyword::None,
333 KeywordLoc: SourceLocation(), QualifierLoc, II, IILoc: NameLoc);
334 return ParsedType::make(P: T);
335 }
336
337 return nullptr;
338 }
339
340 if (!LookupCtx->isDependentContext() &&
341 RequireCompleteDeclContext(SS&: *SS, DC: LookupCtx))
342 return nullptr;
343 }
344
345 // In the case where we know that the identifier is a class name, we know that
346 // it is a type declaration (struct, class, union or enum) so we can use tag
347 // name lookup.
348 //
349 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
350 // the component name of the type-name or simple-template-id is type-only.
351 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
352 LookupResult Result(*this, &II, NameLoc, Kind);
353 if (LookupCtx) {
354 // Perform "qualified" name lookup into the declaration context we
355 // computed, which is either the type of the base of a member access
356 // expression or the declaration context associated with a prior
357 // nested-name-specifier.
358 LookupQualifiedName(R&: Result, LookupCtx);
359
360 if (ObjectTypePtr && Result.empty()) {
361 // C++ [basic.lookup.classref]p3:
362 // If the unqualified-id is ~type-name, the type-name is looked up
363 // in the context of the entire postfix-expression. If the type T of
364 // the object expression is of a class type C, the type-name is also
365 // looked up in the scope of class C. At least one of the lookups shall
366 // find a name that refers to (possibly cv-qualified) T.
367 LookupName(R&: Result, S);
368 }
369 } else {
370 // Perform unqualified name lookup.
371 LookupName(R&: Result, S);
372
373 // For unqualified lookup in a class template in MSVC mode, look into
374 // dependent base classes where the primary class template is known.
375 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
376 if (ParsedType TypeInBase =
377 recoverFromTypeInKnownDependentBase(S&: *this, II, NameLoc))
378 return TypeInBase;
379 }
380 }
381
382 NamedDecl *IIDecl = nullptr;
383 UsingShadowDecl *FoundUsingShadow = nullptr;
384 switch (Result.getResultKind()) {
385 case LookupResultKind::NotFound:
386 if (CorrectedII) {
387 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
388 AllowDeducedTemplate);
389 TypoCorrection Correction =
390 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Kind, S, SS, CCC,
391 Mode: CorrectTypoKind::ErrorRecovery);
392 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
393 TemplateTy Template;
394 bool MemberOfUnknownSpecialization;
395 UnqualifiedId TemplateName;
396 TemplateName.setIdentifier(Id: NewII, IdLoc: NameLoc);
397 NestedNameSpecifier NNS = Correction.getCorrectionSpecifier();
398 CXXScopeSpec NewSS, *NewSSPtr = SS;
399 if (SS && NNS) {
400 NewSS.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
401 NewSSPtr = &NewSS;
402 }
403 if (Correction && (NNS || NewII != &II) &&
404 // Ignore a correction to a template type as the to-be-corrected
405 // identifier is not a template (typo correction for template names
406 // is handled elsewhere).
407 !(getLangOpts().CPlusPlus && NewSSPtr &&
408 isTemplateName(S, SS&: *NewSSPtr, hasTemplateKeyword: false, Name: TemplateName, ObjectType: nullptr, EnteringContext: false,
409 Template, MemberOfUnknownSpecialization))) {
410 ParsedType Ty = getTypeName(II: *NewII, NameLoc, S, SS: NewSSPtr,
411 isClassName, HasTrailingDot, ObjectTypePtr,
412 IsCtorOrDtorName,
413 WantNontrivialTypeSourceInfo,
414 IsClassTemplateDeductionContext);
415 if (Ty) {
416 diagnoseTypo(Correction,
417 TypoDiag: PDiag(DiagID: diag::err_unknown_type_or_class_name_suggest)
418 << Result.getLookupName() << isClassName);
419 if (SS && NNS)
420 SS->MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
421 *CorrectedII = NewII;
422 return Ty;
423 }
424 }
425 }
426 Result.suppressDiagnostics();
427 return nullptr;
428 case LookupResultKind::NotFoundInCurrentInstantiation:
429 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
430 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
431 NNS: SS->getScopeRep(), Name: &II);
432 TypeLocBuilder TLB;
433 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
434 TL.setElaboratedKeywordLoc(SourceLocation());
435 TL.setQualifierLoc(SS->getWithLocInContext(Context));
436 TL.setNameLoc(NameLoc);
437 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
438 }
439 [[fallthrough]];
440 case LookupResultKind::FoundOverloaded:
441 case LookupResultKind::FoundUnresolvedValue:
442 Result.suppressDiagnostics();
443 return nullptr;
444
445 case LookupResultKind::Ambiguous:
446 // Recover from type-hiding ambiguities by hiding the type. We'll
447 // do the lookup again when looking for an object, and we can
448 // diagnose the error then. If we don't do this, then the error
449 // about hiding the type will be immediately followed by an error
450 // that only makes sense if the identifier was treated like a type.
451 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
452 Result.suppressDiagnostics();
453 return nullptr;
454 }
455
456 // Look to see if we have a type anywhere in the list of results.
457 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
458 Res != ResEnd; ++Res) {
459 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
460 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
461 Val: RealRes) ||
462 (AllowDeducedTemplate && getAsTypeTemplateDecl(D: RealRes))) {
463 if (!IIDecl ||
464 // Make the selection of the recovery decl deterministic.
465 RealRes->getLocation() < IIDecl->getLocation()) {
466 IIDecl = RealRes;
467 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Res);
468 }
469 }
470 }
471
472 if (!IIDecl) {
473 // None of the entities we found is a type, so there is no way
474 // to even assume that the result is a type. In this case, don't
475 // complain about the ambiguity. The parser will either try to
476 // perform this lookup again (e.g., as an object name), which
477 // will produce the ambiguity, or will complain that it expected
478 // a type name.
479 Result.suppressDiagnostics();
480 return nullptr;
481 }
482
483 // We found a type within the ambiguous lookup; diagnose the
484 // ambiguity and then return that type. This might be the right
485 // answer, or it might not be, but it suppresses any attempt to
486 // perform the name lookup again.
487 break;
488
489 case LookupResultKind::Found:
490 IIDecl = Result.getFoundDecl();
491 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *Result.begin());
492 break;
493 }
494
495 assert(IIDecl && "Didn't find decl");
496
497 TypeLocBuilder TLB;
498 if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: IIDecl)) {
499 checkTypeDeclType(LookupCtx,
500 DCK: IsImplicitTypename ? DiagCtorKind::Implicit
501 : DiagCtorKind::None,
502 TD, NameLoc);
503 QualType T;
504 if (FoundUsingShadow) {
505 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None,
506 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
507 D: FoundUsingShadow);
508 if (!WantNontrivialTypeSourceInfo)
509 return ParsedType::make(P: T);
510 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
511 QualifierLoc: SS ? SS->getWithLocInContext(Context)
512 : NestedNameSpecifierLoc(),
513 NameLoc);
514 } else if (auto *Tag = dyn_cast<TagDecl>(Val: TD)) {
515 T = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
516 Qualifier: SS ? SS->getScopeRep() : std::nullopt, TD: Tag,
517 /*OwnsTag=*/false);
518 if (!WantNontrivialTypeSourceInfo)
519 return ParsedType::make(P: T);
520 auto TL = TLB.push<TagTypeLoc>(T);
521 TL.setElaboratedKeywordLoc(SourceLocation());
522 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
523 : NestedNameSpecifierLoc());
524 TL.setNameLoc(NameLoc);
525 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD);
526 TN && !isa<ObjCTypeParamDecl>(Val: TN)) {
527 T = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
528 Qualifier: SS ? SS->getScopeRep() : std::nullopt, Decl: TN);
529 if (!WantNontrivialTypeSourceInfo)
530 return ParsedType::make(P: T);
531 TLB.push<TypedefTypeLoc>(T).set(
532 /*ElaboratedKeywordLoc=*/SourceLocation(),
533 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
534 NameLoc);
535 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD)) {
536 T = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
537 Qualifier: SS ? SS->getScopeRep() : std::nullopt,
538 D: UD);
539 if (!WantNontrivialTypeSourceInfo)
540 return ParsedType::make(P: T);
541 TLB.push<UnresolvedUsingTypeLoc>(T).set(
542 /*ElaboratedKeywordLoc=*/SourceLocation(),
543 QualifierLoc: SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
544 NameLoc);
545 } else {
546 T = Context.getTypeDeclType(Decl: TD);
547 if (!WantNontrivialTypeSourceInfo)
548 return ParsedType::make(P: T);
549 if (isa<ObjCTypeParamType>(Val: T))
550 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
551 else
552 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
553 }
554 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
555 }
556 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(Val: IIDecl)) {
557 (void)DiagnoseUseOfDecl(D: IDecl, Locs: NameLoc);
558 if (!HasTrailingDot) {
559 // FIXME: Support UsingType for this case.
560 QualType T = Context.getObjCInterfaceType(Decl: IDecl);
561 if (!WantNontrivialTypeSourceInfo)
562 return ParsedType::make(P: T);
563 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
564 TL.setNameLoc(NameLoc);
565 // FIXME: Pass in this source location.
566 TL.setNameEndLoc(NameLoc);
567 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
568 }
569 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: IIDecl)) {
570 (void)DiagnoseUseOfDecl(D: UD, Locs: NameLoc);
571 // Recover with 'int'
572 return ParsedType::make(P: Context.IntTy);
573 } else if (AllowDeducedTemplate) {
574 if (auto *TD = getAsTypeTemplateDecl(D: IIDecl)) {
575 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
576 // FIXME: Support UsingType here.
577 TemplateName Template = Context.getQualifiedTemplateName(
578 Qualifier: SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
579 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
580 QualType T = Context.getDeducedTemplateSpecializationType(
581 Keyword: ElaboratedTypeKeyword::None, Template, DeducedType: QualType(), IsDependent: false);
582 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
583 TL.setElaboratedKeywordLoc(SourceLocation());
584 TL.setNameLoc(NameLoc);
585 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
586 : NestedNameSpecifierLoc());
587 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
588 }
589 }
590
591 // As it's not plausibly a type, suppress diagnostics.
592 Result.suppressDiagnostics();
593 return nullptr;
594}
595
596// Builds a fake NNS for the given decl context.
597static NestedNameSpecifier
598synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
599 for (;; DC = DC->getLookupParent()) {
600 DC = DC->getPrimaryContext();
601 auto *ND = dyn_cast<NamespaceDecl>(Val: DC);
602 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
603 return NestedNameSpecifier(Context, ND, std::nullopt);
604 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
605 return NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
606 if (isa<TranslationUnitDecl>(Val: DC))
607 return NestedNameSpecifier::getGlobal();
608 }
609 llvm_unreachable("something isn't in TU scope?");
610}
611
612/// Find the parent class with dependent bases of the innermost enclosing method
613/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
614/// up allowing unqualified dependent type names at class-level, which MSVC
615/// correctly rejects.
616static const CXXRecordDecl *
617findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
618 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
619 DC = DC->getPrimaryContext();
620 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
621 if (MD->getParent()->hasAnyDependentBases())
622 return MD->getParent();
623 }
624 return nullptr;
625}
626
627ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
628 SourceLocation NameLoc,
629 bool IsTemplateTypeArg) {
630 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
631
632 NestedNameSpecifier NNS = std::nullopt;
633 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
634 // If we weren't able to parse a default template argument, delay lookup
635 // until instantiation time by making a non-dependent DependentTypeName. We
636 // pretend we saw a NestedNameSpecifier referring to the current scope, and
637 // lookup is retried.
638 // FIXME: This hurts our diagnostic quality, since we get errors like "no
639 // type named 'Foo' in 'current_namespace'" when the user didn't write any
640 // name specifiers.
641 NNS = synthesizeCurrentNestedNameSpecifier(Context, DC: CurContext);
642 Diag(Loc: NameLoc, DiagID: diag::ext_ms_delayed_template_argument) << &II;
643 } else if (const CXXRecordDecl *RD =
644 findRecordWithDependentBasesOfEnclosingMethod(DC: CurContext)) {
645 // Build a DependentNameType that will perform lookup into RD at
646 // instantiation time.
647 NNS = NestedNameSpecifier(Context.getCanonicalTagType(TD: RD)->getTypePtr());
648
649 // Diagnose that this identifier was undeclared, and retry the lookup during
650 // template instantiation.
651 Diag(Loc: NameLoc, DiagID: diag::ext_undeclared_unqual_id_with_dependent_base) << &II
652 << RD;
653 } else {
654 // This is not a situation that we should recover from.
655 return ParsedType();
656 }
657
658 QualType T =
659 Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None, NNS, Name: &II);
660
661 // Build type location information. We synthesized the qualifier, so we have
662 // to build a fake NestedNameSpecifierLoc.
663 NestedNameSpecifierLocBuilder NNSLocBuilder;
664 NNSLocBuilder.MakeTrivial(Context, Qualifier: NNS, R: SourceRange(NameLoc));
665 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
666
667 TypeLocBuilder Builder;
668 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
669 DepTL.setNameLoc(NameLoc);
670 DepTL.setElaboratedKeywordLoc(SourceLocation());
671 DepTL.setQualifierLoc(QualifierLoc);
672 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
673}
674
675DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
676 // Do a tag name lookup in this scope.
677 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
678 LookupName(R, S, AllowBuiltinCreation: false);
679 R.suppressDiagnostics();
680 if (R.getResultKind() == LookupResultKind::Found)
681 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
682 switch (TD->getTagKind()) {
683 case TagTypeKind::Struct:
684 return DeclSpec::TST_struct;
685 case TagTypeKind::Interface:
686 return DeclSpec::TST_interface;
687 case TagTypeKind::Union:
688 return DeclSpec::TST_union;
689 case TagTypeKind::Class:
690 return DeclSpec::TST_class;
691 case TagTypeKind::Enum:
692 return DeclSpec::TST_enum;
693 }
694 }
695
696 return DeclSpec::TST_unspecified;
697}
698
699bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
700 if (!CurContext->isRecord())
701 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
702
703 switch (SS->getScopeRep().getKind()) {
704 case NestedNameSpecifier::Kind::MicrosoftSuper:
705 return true;
706 case NestedNameSpecifier::Kind::Type: {
707 QualType T(SS->getScopeRep().getAsType(), 0);
708 for (const auto &Base : cast<CXXRecordDecl>(Val: CurContext)->bases())
709 if (Context.hasSameUnqualifiedType(T1: T, T2: Base.getType()))
710 return true;
711 [[fallthrough]];
712 }
713 default:
714 return S->isFunctionPrototypeScope();
715 }
716}
717
718void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
719 SourceLocation IILoc,
720 Scope *S,
721 CXXScopeSpec *SS,
722 ParsedType &SuggestedType,
723 bool IsTemplateName) {
724 // Don't report typename errors for editor placeholders.
725 if (II->isEditorPlaceholder())
726 return;
727 // We don't have anything to suggest (yet).
728 SuggestedType = nullptr;
729
730 // There may have been a typo in the name of the type. Look up typo
731 // results, in case we have something that we can suggest.
732 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
733 /*AllowTemplates=*/IsTemplateName,
734 /*AllowNonTemplates=*/!IsTemplateName);
735 if (TypoCorrection Corrected =
736 CorrectTypo(Typo: DeclarationNameInfo(II, IILoc), LookupKind: LookupOrdinaryName, S, SS,
737 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
738 // FIXME: Support error recovery for the template-name case.
739 bool CanRecover = !IsTemplateName;
740 if (Corrected.isKeyword()) {
741 // We corrected to a keyword.
742 diagnoseTypo(Correction: Corrected,
743 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
744 : diag::err_unknown_typename_suggest)
745 << II);
746 II = Corrected.getCorrectionAsIdentifierInfo();
747 } else {
748 // We found a similarly-named type or interface; suggest that.
749 if (!SS || !SS->isSet()) {
750 diagnoseTypo(Correction: Corrected,
751 TypoDiag: PDiag(DiagID: IsTemplateName ? diag::err_no_template_suggest
752 : diag::err_unknown_typename_suggest)
753 << II, ErrorRecovery: CanRecover);
754 } else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false)) {
755 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
756 bool DroppedSpecifier =
757 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
758 diagnoseTypo(Correction: Corrected,
759 TypoDiag: PDiag(DiagID: IsTemplateName
760 ? diag::err_no_member_template_suggest
761 : diag::err_unknown_nested_typename_suggest)
762 << II << DC << DroppedSpecifier << SS->getRange(),
763 ErrorRecovery: CanRecover);
764 } else {
765 llvm_unreachable("could not have corrected a typo here");
766 }
767
768 if (!CanRecover)
769 return;
770
771 CXXScopeSpec tmpSS;
772 if (Corrected.getCorrectionSpecifier())
773 tmpSS.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
774 R: SourceRange(IILoc));
775 // FIXME: Support class template argument deduction here.
776 SuggestedType =
777 getTypeName(II: *Corrected.getCorrectionAsIdentifierInfo(), NameLoc: IILoc, S,
778 SS: tmpSS.isSet() ? &tmpSS : SS, isClassName: false, HasTrailingDot: false, ObjectTypePtr: nullptr,
779 /*IsCtorOrDtorName=*/false,
780 /*WantNontrivialTypeSourceInfo=*/true);
781 }
782 return;
783 }
784
785 if (getLangOpts().CPlusPlus && !IsTemplateName) {
786 // See if II is a class template that the user forgot to pass arguments to.
787 UnqualifiedId Name;
788 Name.setIdentifier(Id: II, IdLoc: IILoc);
789 CXXScopeSpec EmptySS;
790 TemplateTy TemplateResult;
791 bool MemberOfUnknownSpecialization;
792 if (isTemplateName(S, SS&: SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
793 Name, ObjectType: nullptr, EnteringContext: true, Template&: TemplateResult,
794 MemberOfUnknownSpecialization) == TNK_Type_template) {
795 diagnoseMissingTemplateArguments(Name: TemplateResult.get(), Loc: IILoc);
796 return;
797 }
798 }
799
800 // FIXME: Should we move the logic that tries to recover from a missing tag
801 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
802
803 if (!SS || (!SS->isSet() && !SS->isInvalid()))
804 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_template
805 : diag::err_unknown_typename)
806 << II;
807 else if (DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: false))
808 Diag(Loc: IILoc, DiagID: IsTemplateName ? diag::err_no_member_template
809 : diag::err_typename_nested_not_found)
810 << II << DC << SS->getRange();
811 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
812 SuggestedType =
813 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
814 } else if (isDependentScopeSpecifier(SS: *SS)) {
815 unsigned DiagID = diag::err_typename_missing;
816 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
817 DiagID = diag::ext_typename_missing;
818
819 SuggestedType =
820 ActOnTypenameType(S, TypenameLoc: SourceLocation(), SS: *SS, II: *II, IdLoc: IILoc).get();
821
822 Diag(Loc: SS->getRange().getBegin(), DiagID)
823 << GetTypeFromParser(Ty: SuggestedType)
824 << SourceRange(SS->getRange().getBegin(), IILoc)
825 << FixItHint::CreateInsertion(InsertionLoc: SS->getRange().getBegin(), Code: "typename ");
826 } else {
827 assert(SS && SS->isInvalid() &&
828 "Invalid scope specifier has already been diagnosed");
829 }
830}
831
832/// Determine whether the given result set contains either a type name
833/// or
834static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
835 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
836 NextToken.is(K: tok::less);
837
838 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
839 if (isa<TypeDecl>(Val: *I) || isa<ObjCInterfaceDecl>(Val: *I))
840 return true;
841
842 if (CheckTemplate && isa<TemplateDecl>(Val: *I))
843 return true;
844 }
845
846 return false;
847}
848
849static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
850 Scope *S, CXXScopeSpec &SS,
851 IdentifierInfo *&Name,
852 SourceLocation NameLoc) {
853 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
854 SemaRef.LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
855 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
856 StringRef FixItTagName;
857 switch (Tag->getTagKind()) {
858 case TagTypeKind::Class:
859 FixItTagName = "class ";
860 break;
861
862 case TagTypeKind::Enum:
863 FixItTagName = "enum ";
864 break;
865
866 case TagTypeKind::Struct:
867 FixItTagName = "struct ";
868 break;
869
870 case TagTypeKind::Interface:
871 FixItTagName = "__interface ";
872 break;
873
874 case TagTypeKind::Union:
875 FixItTagName = "union ";
876 break;
877 }
878
879 StringRef TagName = FixItTagName.drop_back();
880 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_use_of_tag_name_without_tag)
881 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
882 << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: FixItTagName);
883
884 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
885 I != IEnd; ++I)
886 SemaRef.Diag(Loc: (*I)->getLocation(), DiagID: diag::note_decl_hiding_tag_type)
887 << Name << TagName;
888
889 // Replace lookup results with just the tag decl.
890 Result.clear(Kind: Sema::LookupTagName);
891 SemaRef.LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType());
892 return true;
893 }
894
895 return false;
896}
897
898Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
899 IdentifierInfo *&Name,
900 SourceLocation NameLoc,
901 const Token &NextToken,
902 CorrectionCandidateCallback *CCC) {
903 DeclarationNameInfo NameInfo(Name, NameLoc);
904 ObjCMethodDecl *CurMethod = getCurMethodDecl();
905
906 assert(NextToken.isNot(tok::coloncolon) &&
907 "parse nested name specifiers before calling ClassifyName");
908 if (getLangOpts().CPlusPlus && SS.isSet() &&
909 isCurrentClassName(II: *Name, S, SS: &SS)) {
910 // Per [class.qual]p2, this names the constructors of SS, not the
911 // injected-class-name. We don't have a classification for that.
912 // There's not much point caching this result, since the parser
913 // will reject it later.
914 return NameClassification::Unknown();
915 }
916
917 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
918 LookupParsedName(R&: Result, S, SS: &SS, /*ObjectType=*/QualType(),
919 /*AllowBuiltinCreation=*/!CurMethod);
920
921 if (SS.isInvalid())
922 return NameClassification::Error();
923
924 // For unqualified lookup in a class template in MSVC mode, look into
925 // dependent base classes where the primary class template is known.
926 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
927 if (ParsedType TypeInBase =
928 recoverFromTypeInKnownDependentBase(S&: *this, II: *Name, NameLoc))
929 return TypeInBase;
930 }
931
932 // Perform lookup for Objective-C instance variables (including automatically
933 // synthesized instance variables), if we're in an Objective-C method.
934 // FIXME: This lookup really, really needs to be folded in to the normal
935 // unqualified lookup mechanism.
936 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(R&: Result, NextToken)) {
937 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Name);
938 if (Ivar.isInvalid())
939 return NameClassification::Error();
940 if (Ivar.isUsable())
941 return NameClassification::NonType(D: cast<NamedDecl>(Val: Ivar.get()));
942
943 // We defer builtin creation until after ivar lookup inside ObjC methods.
944 if (Result.empty())
945 LookupBuiltin(R&: Result);
946 }
947
948 bool SecondTry = false;
949 bool IsFilteredTemplateName = false;
950
951Corrected:
952 switch (Result.getResultKind()) {
953 case LookupResultKind::NotFound:
954 // If an unqualified-id is followed by a '(', then we have a function
955 // call.
956 if (SS.isEmpty() && NextToken.is(K: tok::l_paren)) {
957 // In C++, this is an ADL-only call.
958 // FIXME: Reference?
959 if (getLangOpts().CPlusPlus)
960 return NameClassification::UndeclaredNonType();
961
962 // C90 6.3.2.2:
963 // If the expression that precedes the parenthesized argument list in a
964 // function call consists solely of an identifier, and if no
965 // declaration is visible for this identifier, the identifier is
966 // implicitly declared exactly as if, in the innermost block containing
967 // the function call, the declaration
968 //
969 // extern int identifier ();
970 //
971 // appeared.
972 //
973 // We also allow this in C99 as an extension. However, this is not
974 // allowed in all language modes as functions without prototypes may not
975 // be supported.
976 if (getLangOpts().implicitFunctionsAllowed()) {
977 if (NamedDecl *D = ImplicitlyDefineFunction(Loc: NameLoc, II&: *Name, S))
978 return NameClassification::NonType(D);
979 }
980 }
981
982 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(K: tok::less)) {
983 // In C++20 onwards, this could be an ADL-only call to a function
984 // template, and we're required to assume that this is a template name.
985 //
986 // FIXME: Find a way to still do typo correction in this case.
987 TemplateName Template =
988 Context.getAssumedTemplateName(Name: NameInfo.getName());
989 return NameClassification::UndeclaredTemplate(Name: Template);
990 }
991
992 // In C, we first see whether there is a tag type by the same name, in
993 // which case it's likely that the user just forgot to write "enum",
994 // "struct", or "union".
995 if (!getLangOpts().CPlusPlus && !SecondTry &&
996 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
997 break;
998 }
999
1000 // Perform typo correction to determine if there is another name that is
1001 // close to this name.
1002 if (!SecondTry && CCC) {
1003 SecondTry = true;
1004 if (TypoCorrection Corrected =
1005 CorrectTypo(Typo: Result.getLookupNameInfo(), LookupKind: Result.getLookupKind(), S,
1006 SS: &SS, CCC&: *CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
1007 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1008 unsigned QualifiedDiag = diag::err_no_member_suggest;
1009
1010 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1011 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1012 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1013 UnderlyingFirstDecl && isa<TemplateDecl>(Val: UnderlyingFirstDecl)) {
1014 UnqualifiedDiag = diag::err_no_template_suggest;
1015 QualifiedDiag = diag::err_no_member_template_suggest;
1016 } else if (UnderlyingFirstDecl &&
1017 (isa<TypeDecl>(Val: UnderlyingFirstDecl) ||
1018 isa<ObjCInterfaceDecl>(Val: UnderlyingFirstDecl) ||
1019 isa<ObjCCompatibleAliasDecl>(Val: UnderlyingFirstDecl))) {
1020 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1021 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1022 }
1023
1024 if (SS.isEmpty()) {
1025 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: UnqualifiedDiag) << Name);
1026 } else {// FIXME: is this even reachable? Test it.
1027 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
1028 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1029 Name->getName() == CorrectedStr;
1030 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: QualifiedDiag)
1031 << Name << computeDeclContext(SS, EnteringContext: false)
1032 << DroppedSpecifier << SS.getRange());
1033 }
1034
1035 // Update the name, so that the caller has the new name.
1036 Name = Corrected.getCorrectionAsIdentifierInfo();
1037
1038 // Typo correction corrected to a keyword.
1039 if (Corrected.isKeyword())
1040 return Name;
1041
1042 // Also update the LookupResult...
1043 // FIXME: This should probably go away at some point
1044 Result.clear();
1045 Result.setLookupName(Corrected.getCorrection());
1046 if (FirstDecl)
1047 Result.addDecl(D: FirstDecl);
1048
1049 // If we found an Objective-C instance variable, let
1050 // LookupInObjCMethod build the appropriate expression to
1051 // reference the ivar.
1052 // FIXME: This is a gross hack.
1053 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1054 DeclResult R =
1055 ObjC().LookupIvarInObjCMethod(Lookup&: Result, S, II: Ivar->getIdentifier());
1056 if (R.isInvalid())
1057 return NameClassification::Error();
1058 if (R.isUsable())
1059 return NameClassification::NonType(D: Ivar);
1060 }
1061
1062 goto Corrected;
1063 }
1064 }
1065
1066 // We failed to correct; just fall through and let the parser deal with it.
1067 Result.suppressDiagnostics();
1068 return NameClassification::Unknown();
1069
1070 case LookupResultKind::NotFoundInCurrentInstantiation: {
1071 // We performed name lookup into the current instantiation, and there were
1072 // dependent bases, so we treat this result the same way as any other
1073 // dependent nested-name-specifier.
1074
1075 // C++ [temp.res]p2:
1076 // A name used in a template declaration or definition and that is
1077 // dependent on a template-parameter is assumed not to name a type
1078 // unless the applicable name lookup finds a type name or the name is
1079 // qualified by the keyword typename.
1080 //
1081 // FIXME: If the next token is '<', we might want to ask the parser to
1082 // perform some heroics to see if we actually have a
1083 // template-argument-list, which would indicate a missing 'template'
1084 // keyword here.
1085 return NameClassification::DependentNonType();
1086 }
1087
1088 case LookupResultKind::Found:
1089 case LookupResultKind::FoundOverloaded:
1090 case LookupResultKind::FoundUnresolvedValue:
1091 break;
1092
1093 case LookupResultKind::Ambiguous:
1094 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1095 hasAnyAcceptableTemplateNames(R&: Result, /*AllowFunctionTemplates=*/true,
1096 /*AllowDependent=*/false)) {
1097 // C++ [temp.local]p3:
1098 // A lookup that finds an injected-class-name (10.2) can result in an
1099 // ambiguity in certain cases (for example, if it is found in more than
1100 // one base class). If all of the injected-class-names that are found
1101 // refer to specializations of the same class template, and if the name
1102 // is followed by a template-argument-list, the reference refers to the
1103 // class template itself and not a specialization thereof, and is not
1104 // ambiguous.
1105 //
1106 // This filtering can make an ambiguous result into an unambiguous one,
1107 // so try again after filtering out template names.
1108 FilterAcceptableTemplateNames(R&: Result);
1109 if (!Result.isAmbiguous()) {
1110 IsFilteredTemplateName = true;
1111 break;
1112 }
1113 }
1114
1115 // Diagnose the ambiguity and return an error.
1116 return NameClassification::Error();
1117 }
1118
1119 if (getLangOpts().CPlusPlus && NextToken.is(K: tok::less) &&
1120 (IsFilteredTemplateName ||
1121 hasAnyAcceptableTemplateNames(
1122 R&: Result, /*AllowFunctionTemplates=*/true,
1123 /*AllowDependent=*/false,
1124 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1125 getLangOpts().CPlusPlus20))) {
1126 // C++ [temp.names]p3:
1127 // After name lookup (3.4) finds that a name is a template-name or that
1128 // an operator-function-id or a literal- operator-id refers to a set of
1129 // overloaded functions any member of which is a function template if
1130 // this is followed by a <, the < is always taken as the delimiter of a
1131 // template-argument-list and never as the less-than operator.
1132 // C++2a [temp.names]p2:
1133 // A name is also considered to refer to a template if it is an
1134 // unqualified-id followed by a < and name lookup finds either one
1135 // or more functions or finds nothing.
1136 if (!IsFilteredTemplateName)
1137 FilterAcceptableTemplateNames(R&: Result);
1138
1139 bool IsFunctionTemplate;
1140 bool IsVarTemplate;
1141 TemplateName Template;
1142 if (Result.end() - Result.begin() > 1) {
1143 IsFunctionTemplate = true;
1144 Template = Context.getOverloadedTemplateName(Begin: Result.begin(),
1145 End: Result.end());
1146 } else if (!Result.empty()) {
1147 auto *TD = cast<TemplateDecl>(Val: getAsTemplateNameDecl(
1148 D: *Result.begin(), /*AllowFunctionTemplates=*/true,
1149 /*AllowDependent=*/false));
1150 IsFunctionTemplate = isa<FunctionTemplateDecl>(Val: TD);
1151 IsVarTemplate = isa<VarTemplateDecl>(Val: TD);
1152
1153 UsingShadowDecl *FoundUsingShadow =
1154 dyn_cast<UsingShadowDecl>(Val: *Result.begin());
1155 assert(!FoundUsingShadow ||
1156 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1157 Template = Context.getQualifiedTemplateName(
1158 Qualifier: SS.getScopeRep(),
1159 /*TemplateKeyword=*/false,
1160 Template: FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1161 } else {
1162 // All results were non-template functions. This is a function template
1163 // name.
1164 IsFunctionTemplate = true;
1165 Template = Context.getAssumedTemplateName(Name: NameInfo.getName());
1166 }
1167
1168 if (IsFunctionTemplate) {
1169 // Function templates always go through overload resolution, at which
1170 // point we'll perform the various checks (e.g., accessibility) we need
1171 // to based on which function we selected.
1172 Result.suppressDiagnostics();
1173
1174 return NameClassification::FunctionTemplate(Name: Template);
1175 }
1176
1177 return IsVarTemplate ? NameClassification::VarTemplate(Name: Template)
1178 : NameClassification::TypeTemplate(Name: Template);
1179 }
1180
1181 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1182 QualType T;
1183 TypeLocBuilder TLB;
1184 if (const auto *USD = dyn_cast<UsingShadowDecl>(Val: Found)) {
1185 T = Context.getUsingType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1186 D: USD);
1187 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1188 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1189 } else {
1190 T = Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
1191 Decl: Type);
1192 if (isa<TagType>(Val: T)) {
1193 auto TTL = TLB.push<TagTypeLoc>(T);
1194 TTL.setElaboratedKeywordLoc(SourceLocation());
1195 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1196 TTL.setNameLoc(NameLoc);
1197 } else if (isa<TypedefType>(Val: T)) {
1198 TLB.push<TypedefTypeLoc>(T).set(
1199 /*ElaboratedKeywordLoc=*/SourceLocation(),
1200 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1201 } else if (isa<UnresolvedUsingType>(Val: T)) {
1202 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1203 /*ElaboratedKeywordLoc=*/SourceLocation(),
1204 QualifierLoc: SS.getWithLocInContext(Context), NameLoc);
1205 } else {
1206 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1207 }
1208 }
1209 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
1210 };
1211
1212 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1213 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: FirstDecl)) {
1214 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1215 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
1216 return BuildTypeFor(Type, *Result.begin());
1217 }
1218
1219 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(Val: FirstDecl);
1220 if (!Class) {
1221 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1222 if (ObjCCompatibleAliasDecl *Alias =
1223 dyn_cast<ObjCCompatibleAliasDecl>(Val: FirstDecl))
1224 Class = Alias->getClassInterface();
1225 }
1226
1227 if (Class) {
1228 DiagnoseUseOfDecl(D: Class, Locs: NameLoc);
1229
1230 if (NextToken.is(K: tok::period)) {
1231 // Interface. <something> is parsed as a property reference expression.
1232 // Just return "unknown" as a fall-through for now.
1233 Result.suppressDiagnostics();
1234 return NameClassification::Unknown();
1235 }
1236
1237 QualType T = Context.getObjCInterfaceType(Decl: Class);
1238 return ParsedType::make(P: T);
1239 }
1240
1241 if (isa<ConceptDecl>(Val: FirstDecl)) {
1242 // We want to preserve the UsingShadowDecl for concepts.
1243 if (auto *USD = dyn_cast<UsingShadowDecl>(Val: Result.getRepresentativeDecl()))
1244 return NameClassification::Concept(Name: TemplateName(USD));
1245 return NameClassification::Concept(
1246 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1247 }
1248
1249 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: FirstDecl)) {
1250 (void)DiagnoseUseOfDecl(D: EmptyD, Locs: NameLoc);
1251 return NameClassification::Error();
1252 }
1253
1254 // We can have a type template here if we're classifying a template argument.
1255 if (isa<TemplateDecl>(Val: FirstDecl) && !isa<FunctionTemplateDecl>(Val: FirstDecl) &&
1256 !isa<VarTemplateDecl>(Val: FirstDecl))
1257 return NameClassification::TypeTemplate(
1258 Name: TemplateName(cast<TemplateDecl>(Val: FirstDecl)));
1259
1260 // Check for a tag type hidden by a non-type decl in a few cases where it
1261 // seems likely a type is wanted instead of the non-type that was found.
1262 bool NextIsOp = NextToken.isOneOf(Ks: tok::amp, Ks: tok::star);
1263 if ((NextToken.is(K: tok::identifier) ||
1264 (NextIsOp &&
1265 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1266 isTagTypeWithMissingTag(SemaRef&: *this, Result, S, SS, Name, NameLoc)) {
1267 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1268 DiagnoseUseOfDecl(D: Type, Locs: NameLoc);
1269 return BuildTypeFor(Type, *Result.begin());
1270 }
1271
1272 // If we already know which single declaration is referenced, just annotate
1273 // that declaration directly. Defer resolving even non-overloaded class
1274 // member accesses, as we need to defer certain access checks until we know
1275 // the context.
1276 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1277 if (Result.isSingleResult() && !ADL &&
1278 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(Val: FirstDecl)))
1279 return NameClassification::NonType(D: Result.getRepresentativeDecl());
1280
1281 // Otherwise, this is an overload set that we will need to resolve later.
1282 Result.suppressDiagnostics();
1283 return NameClassification::OverloadSet(E: UnresolvedLookupExpr::Create(
1284 Context, NamingClass: Result.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
1285 NameInfo: Result.getLookupNameInfo(), RequiresADL: ADL, Begin: Result.begin(), End: Result.end(),
1286 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1287}
1288
1289ExprResult
1290Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1291 SourceLocation NameLoc) {
1292 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1293 CXXScopeSpec SS;
1294 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1295 return BuildDeclarationNameExpr(SS, R&: Result, /*ADL=*/NeedsADL: true);
1296}
1297
1298ExprResult
1299Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1300 IdentifierInfo *Name,
1301 SourceLocation NameLoc,
1302 bool IsAddressOfOperand) {
1303 DeclarationNameInfo NameInfo(Name, NameLoc);
1304 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1305 NameInfo, isAddressOfOperand: IsAddressOfOperand,
1306 /*TemplateArgs=*/nullptr);
1307}
1308
1309ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1310 NamedDecl *Found,
1311 SourceLocation NameLoc,
1312 const Token &NextToken) {
1313 if (getCurMethodDecl() && SS.isEmpty())
1314 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: Found->getUnderlyingDecl()))
1315 return ObjC().BuildIvarRefExpr(S, Loc: NameLoc, IV: Ivar);
1316
1317 // Reconstruct the lookup result.
1318 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1319 Result.addDecl(D: Found);
1320 Result.resolveKind();
1321
1322 bool ADL = UseArgumentDependentLookup(SS, R: Result, HasTrailingLParen: NextToken.is(K: tok::l_paren));
1323 return BuildDeclarationNameExpr(SS, R&: Result, NeedsADL: ADL, /*AcceptInvalidDecl=*/true);
1324}
1325
1326ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1327 // For an implicit class member access, transform the result into a member
1328 // access expression if necessary.
1329 auto *ULE = cast<UnresolvedLookupExpr>(Val: E);
1330 if ((*ULE->decls_begin())->isCXXClassMember()) {
1331 CXXScopeSpec SS;
1332 SS.Adopt(Other: ULE->getQualifierLoc());
1333
1334 // Reconstruct the lookup result.
1335 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1336 LookupOrdinaryName);
1337 Result.setNamingClass(ULE->getNamingClass());
1338 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1339 Result.addDecl(D: *I, AS: I.getAccess());
1340 Result.resolveKind();
1341 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc: SourceLocation(), R&: Result,
1342 TemplateArgs: nullptr, S);
1343 }
1344
1345 // Otherwise, this is already in the form we needed, and no further checks
1346 // are necessary.
1347 return ULE;
1348}
1349
1350Sema::TemplateNameKindForDiagnostics
1351Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1352 auto *TD = Name.getAsTemplateDecl();
1353 if (!TD)
1354 return TemplateNameKindForDiagnostics::DependentTemplate;
1355 if (isa<ClassTemplateDecl>(Val: TD))
1356 return TemplateNameKindForDiagnostics::ClassTemplate;
1357 if (isa<FunctionTemplateDecl>(Val: TD))
1358 return TemplateNameKindForDiagnostics::FunctionTemplate;
1359 if (isa<VarTemplateDecl>(Val: TD))
1360 return TemplateNameKindForDiagnostics::VarTemplate;
1361 if (isa<TypeAliasTemplateDecl>(Val: TD))
1362 return TemplateNameKindForDiagnostics::AliasTemplate;
1363 if (isa<TemplateTemplateParmDecl>(Val: TD))
1364 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1365 if (isa<ConceptDecl>(Val: TD))
1366 return TemplateNameKindForDiagnostics::Concept;
1367 return TemplateNameKindForDiagnostics::DependentTemplate;
1368}
1369
1370void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1371 assert(DC->getLexicalParent() == CurContext &&
1372 "The next DeclContext should be lexically contained in the current one.");
1373 CurContext = DC;
1374 S->setEntity(DC);
1375}
1376
1377void Sema::PopDeclContext() {
1378 assert(CurContext && "DeclContext imbalance!");
1379
1380 CurContext = CurContext->getLexicalParent();
1381 assert(CurContext && "Popped translation unit!");
1382}
1383
1384Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1385 Decl *D) {
1386 // Unlike PushDeclContext, the context to which we return is not necessarily
1387 // the containing DC of TD, because the new context will be some pre-existing
1388 // TagDecl definition instead of a fresh one.
1389 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1390 CurContext = cast<TagDecl>(Val: D)->getDefinition();
1391 assert(CurContext && "skipping definition of undefined tag");
1392 // Start lookups from the parent of the current context; we don't want to look
1393 // into the pre-existing complete definition.
1394 S->setEntity(CurContext->getLookupParent());
1395 return Result;
1396}
1397
1398void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1399 CurContext = static_cast<decltype(CurContext)>(Context);
1400}
1401
1402void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1403 // C++0x [basic.lookup.unqual]p13:
1404 // A name used in the definition of a static data member of class
1405 // X (after the qualified-id of the static member) is looked up as
1406 // if the name was used in a member function of X.
1407 // C++0x [basic.lookup.unqual]p14:
1408 // If a variable member of a namespace is defined outside of the
1409 // scope of its namespace then any name used in the definition of
1410 // the variable member (after the declarator-id) is looked up as
1411 // if the definition of the variable member occurred in its
1412 // namespace.
1413 // Both of these imply that we should push a scope whose context
1414 // is the semantic context of the declaration. We can't use
1415 // PushDeclContext here because that context is not necessarily
1416 // lexically contained in the current context. Fortunately,
1417 // the containing scope should have the appropriate information.
1418
1419 assert(!S->getEntity() && "scope already has entity");
1420
1421#ifndef NDEBUG
1422 Scope *Ancestor = S->getParent();
1423 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1424 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1425#endif
1426
1427 CurContext = DC;
1428 S->setEntity(DC);
1429
1430 if (S->getParent()->isTemplateParamScope()) {
1431 // Also set the corresponding entities for all immediately-enclosing
1432 // template parameter scopes.
1433 EnterTemplatedContext(S: S->getParent(), DC);
1434 }
1435}
1436
1437void Sema::ExitDeclaratorContext(Scope *S) {
1438 assert(S->getEntity() == CurContext && "Context imbalance!");
1439
1440 // Switch back to the lexical context. The safety of this is
1441 // enforced by an assert in EnterDeclaratorContext.
1442 Scope *Ancestor = S->getParent();
1443 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1444 CurContext = Ancestor->getEntity();
1445
1446 // We don't need to do anything with the scope, which is going to
1447 // disappear.
1448}
1449
1450void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1451 assert(S->isTemplateParamScope() &&
1452 "expected to be initializing a template parameter scope");
1453
1454 // C++20 [temp.local]p7:
1455 // In the definition of a member of a class template that appears outside
1456 // of the class template definition, the name of a member of the class
1457 // template hides the name of a template-parameter of any enclosing class
1458 // templates (but not a template-parameter of the member if the member is a
1459 // class or function template).
1460 // C++20 [temp.local]p9:
1461 // In the definition of a class template or in the definition of a member
1462 // of such a template that appears outside of the template definition, for
1463 // each non-dependent base class (13.8.2.1), if the name of the base class
1464 // or the name of a member of the base class is the same as the name of a
1465 // template-parameter, the base class name or member name hides the
1466 // template-parameter name (6.4.10).
1467 //
1468 // This means that a template parameter scope should be searched immediately
1469 // after searching the DeclContext for which it is a template parameter
1470 // scope. For example, for
1471 // template<typename T> template<typename U> template<typename V>
1472 // void N::A<T>::B<U>::f(...)
1473 // we search V then B<U> (and base classes) then U then A<T> (and base
1474 // classes) then T then N then ::.
1475 unsigned ScopeDepth = getTemplateDepth(S);
1476 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1477 DeclContext *SearchDCAfterScope = DC;
1478 for (; DC; DC = DC->getLookupParent()) {
1479 if (const TemplateParameterList *TPL =
1480 cast<Decl>(Val: DC)->getDescribedTemplateParams()) {
1481 unsigned DCDepth = TPL->getDepth() + 1;
1482 if (DCDepth > ScopeDepth)
1483 continue;
1484 if (ScopeDepth == DCDepth)
1485 SearchDCAfterScope = DC = DC->getLookupParent();
1486 break;
1487 }
1488 }
1489 S->setLookupEntity(SearchDCAfterScope);
1490 }
1491}
1492
1493void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1494 // We assume that the caller has already called
1495 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1496 FunctionDecl *FD = D->getAsFunction();
1497 if (!FD)
1498 return;
1499
1500 // Same implementation as PushDeclContext, but enters the context
1501 // from the lexical parent, rather than the top-level class.
1502 assert(CurContext == FD->getLexicalParent() &&
1503 "The next DeclContext should be lexically contained in the current one.");
1504 CurContext = FD;
1505 S->setEntity(CurContext);
1506
1507 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1508 ParmVarDecl *Param = FD->getParamDecl(i: P);
1509 // If the parameter has an identifier, then add it to the scope
1510 if (Param->getIdentifier()) {
1511 S->AddDecl(D: Param);
1512 IdResolver.AddDecl(D: Param);
1513 }
1514 }
1515}
1516
1517void Sema::ActOnExitFunctionContext() {
1518 // Same implementation as PopDeclContext, but returns to the lexical parent,
1519 // rather than the top-level class.
1520 assert(CurContext && "DeclContext imbalance!");
1521 CurContext = CurContext->getLexicalParent();
1522 assert(CurContext && "Popped translation unit!");
1523}
1524
1525/// Determine whether overloading is allowed for a new function
1526/// declaration considering prior declarations of the same name.
1527///
1528/// This routine determines whether overloading is possible, not
1529/// whether a new declaration actually overloads a previous one.
1530/// It will return true in C++ (where overloads are always permitted)
1531/// or, as a C extension, when either the new declaration or a
1532/// previous one is declared with the 'overloadable' attribute.
1533static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1534 ASTContext &Context,
1535 const FunctionDecl *New) {
1536 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1537 return true;
1538
1539 // Multiversion function declarations are not overloads in the
1540 // usual sense of that term, but lookup will report that an
1541 // overload set was found if more than one multiversion function
1542 // declaration is present for the same name. It is therefore
1543 // inadequate to assume that some prior declaration(s) had
1544 // the overloadable attribute; checking is required. Since one
1545 // declaration is permitted to omit the attribute, it is necessary
1546 // to check at least two; hence the 'any_of' check below. Note that
1547 // the overloadable attribute is implicitly added to declarations
1548 // that were required to have it but did not.
1549 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1550 return llvm::any_of(Range: Previous, P: [](const NamedDecl *ND) {
1551 return ND->hasAttr<OverloadableAttr>();
1552 });
1553 } else if (Previous.getResultKind() == LookupResultKind::Found)
1554 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1555
1556 return false;
1557}
1558
1559void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1560 // Move up the scope chain until we find the nearest enclosing
1561 // non-transparent context. The declaration will be introduced into this
1562 // scope.
1563 while (S->getEntity() && S->getEntity()->isTransparentContext())
1564 S = S->getParent();
1565
1566 // Add scoped declarations into their context, so that they can be
1567 // found later. Declarations without a context won't be inserted
1568 // into any context.
1569 if (AddToContext)
1570 CurContext->addDecl(D);
1571
1572 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1573 // are function-local declarations.
1574 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1575 return;
1576
1577 // Template instantiations should also not be pushed into scope.
1578 if (isa<FunctionDecl>(Val: D) &&
1579 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization())
1580 return;
1581
1582 if (isa<UsingEnumDecl>(Val: D) && D->getDeclName().isEmpty()) {
1583 S->AddDecl(D);
1584 return;
1585 }
1586 // If this replaces anything in the current scope,
1587 IdentifierResolver::iterator I = IdResolver.begin(Name: D->getDeclName()),
1588 IEnd = IdResolver.end();
1589 for (; I != IEnd; ++I) {
1590 if (S->isDeclScope(D: *I) && D->declarationReplaces(OldD: *I)) {
1591 S->RemoveDecl(D: *I);
1592 IdResolver.RemoveDecl(D: *I);
1593
1594 // Should only need to replace one decl.
1595 break;
1596 }
1597 }
1598
1599 S->AddDecl(D);
1600
1601 if (isa<LabelDecl>(Val: D) && !cast<LabelDecl>(Val: D)->isGnuLocal()) {
1602 // Implicitly-generated labels may end up getting generated in an order that
1603 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1604 // the label at the appropriate place in the identifier chain.
1605 for (I = IdResolver.begin(Name: D->getDeclName()); I != IEnd; ++I) {
1606 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1607 if (IDC == CurContext) {
1608 if (!S->isDeclScope(D: *I))
1609 continue;
1610 } else if (IDC->Encloses(DC: CurContext))
1611 break;
1612 }
1613
1614 IdResolver.InsertDeclAfter(Pos: I, D);
1615 } else {
1616 IdResolver.AddDecl(D);
1617 }
1618 warnOnReservedIdentifier(D);
1619}
1620
1621bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1622 bool AllowInlineNamespace) const {
1623 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1624}
1625
1626Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1627 DeclContext *TargetDC = DC->getPrimaryContext();
1628 do {
1629 if (DeclContext *ScopeDC = S->getEntity())
1630 if (ScopeDC->getPrimaryContext() == TargetDC)
1631 return S;
1632 } while ((S = S->getParent()));
1633
1634 return nullptr;
1635}
1636
1637static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1638 DeclContext*,
1639 ASTContext&);
1640
1641void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1642 bool ConsiderLinkage,
1643 bool AllowInlineNamespace) {
1644 LookupResult::Filter F = R.makeFilter();
1645 while (F.hasNext()) {
1646 NamedDecl *D = F.next();
1647
1648 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1649 continue;
1650
1651 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1652 continue;
1653
1654 F.erase();
1655 }
1656
1657 F.done();
1658}
1659
1660static bool isImplicitInstantiation(NamedDecl *D) {
1661 if (auto *VD = dyn_cast<VarDecl>(Val: D))
1662 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1663 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
1664 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1665 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1666 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1667
1668 return false;
1669}
1670
1671bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1672 // [module.interface]p7:
1673 // A declaration is attached to a module as follows:
1674 // - If the declaration is a non-dependent friend declaration that nominates a
1675 // function with a declarator-id that is a qualified-id or template-id or that
1676 // nominates a class other than with an elaborated-type-specifier with neither
1677 // a nested-name-specifier nor a simple-template-id, it is attached to the
1678 // module to which the friend is attached ([basic.link]).
1679 if (New->getFriendObjectKind() &&
1680 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1681 New->setLocalOwningModule(Old->getOwningModule());
1682 makeMergedDefinitionVisible(ND: New);
1683 return false;
1684 }
1685
1686 // Although we have questions for the module ownership of implicit
1687 // instantiations, it should be sure that we shouldn't diagnose the
1688 // redeclaration of incorrect module ownership for different implicit
1689 // instantiations in different modules. We will diagnose the redeclaration of
1690 // incorrect module ownership for the template itself.
1691 if (isImplicitInstantiation(D: New) || isImplicitInstantiation(D: Old))
1692 return false;
1693
1694 Module *NewM = New->getOwningModule();
1695 Module *OldM = Old->getOwningModule();
1696
1697 if (NewM && NewM->isPrivateModule())
1698 NewM = NewM->Parent;
1699 if (OldM && OldM->isPrivateModule())
1700 OldM = OldM->Parent;
1701
1702 if (NewM == OldM)
1703 return false;
1704
1705 if (NewM && OldM) {
1706 // A module implementation unit has visibility of the decls in its
1707 // implicitly imported interface.
1708 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1709 return false;
1710
1711 // Partitions are part of the module, but a partition could import another
1712 // module, so verify that the PMIs agree.
1713 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1714 getASTContext().isInSameModule(M1: NewM, M2: OldM))
1715 return false;
1716 }
1717
1718 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1719 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1720 if (NewIsModuleInterface || OldIsModuleInterface) {
1721 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1722 // if a declaration of D [...] appears in the purview of a module, all
1723 // other such declarations shall appear in the purview of the same module
1724 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_owning_module)
1725 << New
1726 << NewIsModuleInterface
1727 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1728 << OldIsModuleInterface
1729 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1730 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1731 New->setInvalidDecl();
1732 return true;
1733 }
1734
1735 return false;
1736}
1737
1738bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1739 // [module.interface]p1:
1740 // An export-declaration shall inhabit a namespace scope.
1741 //
1742 // So it is meaningless to talk about redeclaration which is not at namespace
1743 // scope.
1744 if (!New->getLexicalDeclContext()
1745 ->getNonTransparentContext()
1746 ->isFileContext() ||
1747 !Old->getLexicalDeclContext()
1748 ->getNonTransparentContext()
1749 ->isFileContext())
1750 return false;
1751
1752 bool IsNewExported = New->isInExportDeclContext();
1753 bool IsOldExported = Old->isInExportDeclContext();
1754
1755 // It should be irrevelant if both of them are not exported.
1756 if (!IsNewExported && !IsOldExported)
1757 return false;
1758
1759 if (IsOldExported)
1760 return false;
1761
1762 // If the Old declaration are not attached to named modules
1763 // and the New declaration are attached to global module.
1764 // It should be fine to allow the export since it doesn't change
1765 // the linkage of declarations. See
1766 // https://github.com/llvm/llvm-project/issues/98583 for details.
1767 if (!Old->isInNamedModule() && New->getOwningModule() &&
1768 New->getOwningModule()->isImplicitGlobalModule())
1769 return false;
1770
1771 assert(IsNewExported);
1772
1773 auto Lk = Old->getFormalLinkage();
1774 int S = 0;
1775 if (Lk == Linkage::Internal)
1776 S = 1;
1777 else if (Lk == Linkage::Module)
1778 S = 2;
1779 Diag(Loc: New->getLocation(), DiagID: diag::err_redeclaration_non_exported) << New << S;
1780 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
1781 return true;
1782}
1783
1784bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1785 if (CheckRedeclarationModuleOwnership(New, Old))
1786 return true;
1787
1788 if (CheckRedeclarationExported(New, Old))
1789 return true;
1790
1791 return false;
1792}
1793
1794bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1795 const NamedDecl *Old) const {
1796 assert(getASTContext().isSameEntity(New, Old) &&
1797 "New and Old are not the same definition, we should diagnostic it "
1798 "immediately instead of checking it.");
1799 assert(const_cast<Sema *>(this)->isReachable(New) &&
1800 const_cast<Sema *>(this)->isReachable(Old) &&
1801 "We shouldn't see unreachable definitions here.");
1802
1803 Module *NewM = New->getOwningModule();
1804 Module *OldM = Old->getOwningModule();
1805
1806 // We only checks for named modules here. The header like modules is skipped.
1807 // FIXME: This is not right if we import the header like modules in the module
1808 // purview.
1809 //
1810 // For example, assuming "header.h" provides definition for `D`.
1811 // ```C++
1812 // //--- M.cppm
1813 // export module M;
1814 // import "header.h"; // or #include "header.h" but import it by clang modules
1815 // actually.
1816 //
1817 // //--- Use.cpp
1818 // import M;
1819 // import "header.h"; // or uses clang modules.
1820 // ```
1821 //
1822 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1823 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1824 // reject it. But the current implementation couldn't detect the case since we
1825 // don't record the information about the importee modules.
1826 //
1827 // But this might not be painful in practice. Since the design of C++20 Named
1828 // Modules suggests us to use headers in global module fragment instead of
1829 // module purview.
1830 if (NewM && NewM->isHeaderLikeModule())
1831 NewM = nullptr;
1832 if (OldM && OldM->isHeaderLikeModule())
1833 OldM = nullptr;
1834
1835 if (!NewM && !OldM)
1836 return true;
1837
1838 // [basic.def.odr]p14.3
1839 // Each such definition shall not be attached to a named module
1840 // ([module.unit]).
1841 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1842 return true;
1843
1844 // Then New and Old lives in the same TU if their share one same module unit.
1845 if (NewM)
1846 NewM = NewM->getTopLevelModule();
1847 if (OldM)
1848 OldM = OldM->getTopLevelModule();
1849 return OldM == NewM;
1850}
1851
1852static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1853 if (D->getDeclContext()->isFileContext())
1854 return false;
1855
1856 return isa<UsingShadowDecl>(Val: D) ||
1857 isa<UnresolvedUsingTypenameDecl>(Val: D) ||
1858 isa<UnresolvedUsingValueDecl>(Val: D);
1859}
1860
1861/// Removes using shadow declarations not at class scope from the lookup
1862/// results.
1863static void RemoveUsingDecls(LookupResult &R) {
1864 LookupResult::Filter F = R.makeFilter();
1865 while (F.hasNext())
1866 if (isUsingDeclNotAtClassScope(D: F.next()))
1867 F.erase();
1868
1869 F.done();
1870}
1871
1872/// Check for this common pattern:
1873/// @code
1874/// class S {
1875/// S(const S&); // DO NOT IMPLEMENT
1876/// void operator=(const S&); // DO NOT IMPLEMENT
1877/// };
1878/// @endcode
1879static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1880 // FIXME: Should check for private access too but access is set after we get
1881 // the decl here.
1882 if (D->doesThisDeclarationHaveABody())
1883 return false;
1884
1885 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: D))
1886 return CD->isCopyConstructor();
1887 return D->isCopyAssignmentOperator();
1888}
1889
1890bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1891 const DeclContext *DC = D->getDeclContext();
1892 while (!DC->isTranslationUnit()) {
1893 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Val: DC)){
1894 if (!RD->hasNameForLinkage())
1895 return true;
1896 }
1897 DC = DC->getParent();
1898 }
1899
1900 return !D->isExternallyVisible();
1901}
1902
1903// FIXME: This needs to be refactored; some other isInMainFile users want
1904// these semantics.
1905static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1906 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1907 return false;
1908 return S.SourceMgr.isInMainFile(Loc);
1909}
1910
1911bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1912 assert(D);
1913
1914 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1915 return false;
1916
1917 // Ignore all entities declared within templates, and out-of-line definitions
1918 // of members of class templates.
1919 if (D->getDeclContext()->isDependentContext() ||
1920 D->getLexicalDeclContext()->isDependentContext())
1921 return false;
1922
1923 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1924 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1925 return false;
1926 // A non-out-of-line declaration of a member specialization was implicitly
1927 // instantiated; it's the out-of-line declaration that we're interested in.
1928 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1929 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1930 return false;
1931
1932 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
1933 if (MD->isVirtual() || IsDisallowedCopyOrAssign(D: MD))
1934 return false;
1935 } else {
1936 // 'static inline' functions are defined in headers; don't warn.
1937 if (FD->isInlined() && !isMainFileLoc(S: *this, Loc: FD->getLocation()))
1938 return false;
1939 }
1940
1941 if (FD->doesThisDeclarationHaveABody() &&
1942 Context.DeclMustBeEmitted(D: FD))
1943 return false;
1944 } else if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1945 // Constants and utility variables are defined in headers with internal
1946 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1947 // like "inline".)
1948 if (!isMainFileLoc(S: *this, Loc: VD->getLocation()))
1949 return false;
1950
1951 if (Context.DeclMustBeEmitted(D: VD))
1952 return false;
1953
1954 if (VD->isStaticDataMember() &&
1955 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1956 return false;
1957 if (VD->isStaticDataMember() &&
1958 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1959 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1960 return false;
1961
1962 if (VD->isInline() && !isMainFileLoc(S: *this, Loc: VD->getLocation()))
1963 return false;
1964 } else {
1965 return false;
1966 }
1967
1968 // Only warn for unused decls internal to the translation unit.
1969 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1970 // for inline functions defined in the main source file, for instance.
1971 return mightHaveNonExternalLinkage(D);
1972}
1973
1974void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1975 if (!D)
1976 return;
1977
1978 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
1979 const FunctionDecl *First = FD->getFirstDecl();
1980 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1981 return; // First should already be in the vector.
1982 }
1983
1984 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
1985 const VarDecl *First = VD->getFirstDecl();
1986 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(D: First))
1987 return; // First should already be in the vector.
1988 }
1989
1990 if (ShouldWarnIfUnusedFileScopedDecl(D))
1991 UnusedFileScopedDecls.push_back(LocalValue: D);
1992}
1993
1994static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1995 const NamedDecl *D) {
1996 if (D->isInvalidDecl())
1997 return false;
1998
1999 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: D)) {
2000 // For a decomposition declaration, warn if none of the bindings are
2001 // referenced, instead of if the variable itself is referenced (which
2002 // it is, by the bindings' expressions).
2003 bool IsAllIgnored = true;
2004 for (const auto *BD : DD->bindings()) {
2005 if (BD->isReferenced())
2006 return false;
2007 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2008 BD->hasAttr<UnusedAttr>());
2009 }
2010 if (IsAllIgnored)
2011 return false;
2012 } else if (!D->getDeclName()) {
2013 return false;
2014 } else if (D->isReferenced() || D->isUsed()) {
2015 return false;
2016 }
2017
2018 if (D->isPlaceholderVar(LangOpts))
2019 return false;
2020
2021 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2022 D->hasAttr<CleanupAttr>())
2023 return false;
2024
2025 if (isa<LabelDecl>(Val: D))
2026 return true;
2027
2028 // Except for labels, we only care about unused decls that are local to
2029 // functions.
2030 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2031 if (const auto *R = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()))
2032 // For dependent types, the diagnostic is deferred.
2033 WithinFunction =
2034 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2035 if (!WithinFunction)
2036 return false;
2037
2038 if (isa<TypedefNameDecl>(Val: D))
2039 return true;
2040
2041 // White-list anything that isn't a local variable.
2042 if (!isa<VarDecl>(Val: D) || isa<ParmVarDecl>(Val: D) || isa<ImplicitParamDecl>(Val: D))
2043 return false;
2044
2045 // Types of valid local variables should be complete, so this should succeed.
2046 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2047
2048 const Expr *Init = VD->getInit();
2049 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Val: Init))
2050 Init = Cleanups->getSubExpr();
2051
2052 const auto *Ty = VD->getType().getTypePtr();
2053
2054 // Only look at the outermost level of typedef.
2055 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2056 // Allow anything marked with __attribute__((unused)).
2057 if (TT->getDecl()->hasAttr<UnusedAttr>())
2058 return false;
2059 }
2060
2061 // Warn for reference variables whose initializtion performs lifetime
2062 // extension.
2063 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Val: Init);
2064 MTE && MTE->getExtendingDecl()) {
2065 Ty = VD->getType().getNonReferenceType().getTypePtr();
2066 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2067 }
2068
2069 // If we failed to complete the type for some reason, or if the type is
2070 // dependent, don't diagnose the variable.
2071 if (Ty->isIncompleteType() || Ty->isDependentType())
2072 return false;
2073
2074 // Look at the element type to ensure that the warning behaviour is
2075 // consistent for both scalars and arrays.
2076 Ty = Ty->getBaseElementTypeUnsafe();
2077
2078 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2079 if (Tag->hasAttr<UnusedAttr>())
2080 return false;
2081
2082 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
2083 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2084 return false;
2085
2086 if (Init) {
2087 const auto *Construct =
2088 dyn_cast<CXXConstructExpr>(Val: Init->IgnoreImpCasts());
2089 if (Construct && !Construct->isElidable()) {
2090 const CXXConstructorDecl *CD = Construct->getConstructor();
2091 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2092 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2093 return false;
2094 }
2095
2096 // Suppress the warning if we don't know how this is constructed, and
2097 // it could possibly be non-trivial constructor.
2098 if (Init->isTypeDependent()) {
2099 for (const CXXConstructorDecl *Ctor : RD->ctors())
2100 if (!Ctor->isTrivial())
2101 return false;
2102 }
2103
2104 // Suppress the warning if the constructor is unresolved because
2105 // its arguments are dependent.
2106 if (isa<CXXUnresolvedConstructExpr>(Val: Init))
2107 return false;
2108 }
2109 }
2110 }
2111
2112 // TODO: __attribute__((unused)) templates?
2113 }
2114
2115 return true;
2116}
2117
2118static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2119 FixItHint &Hint) {
2120 if (isa<LabelDecl>(Val: D)) {
2121 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2122 loc: D->getEndLoc(), TKind: tok::colon, SM: Ctx.getSourceManager(), LangOpts: Ctx.getLangOpts(),
2123 /*SkipTrailingWhitespaceAndNewline=*/SkipTrailingWhitespaceAndNewLine: false);
2124 if (AfterColon.isInvalid())
2125 return;
2126 Hint = FixItHint::CreateRemoval(
2127 RemoveRange: CharSourceRange::getCharRange(B: D->getBeginLoc(), E: AfterColon));
2128 }
2129}
2130
2131void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2132 DiagnoseUnusedNestedTypedefs(
2133 D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2134}
2135
2136void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2137 DiagReceiverTy DiagReceiver) {
2138 if (D->isDependentType())
2139 return;
2140
2141 for (auto *TmpD : D->decls()) {
2142 if (const auto *T = dyn_cast<TypedefNameDecl>(Val: TmpD))
2143 DiagnoseUnusedDecl(ND: T, DiagReceiver);
2144 else if(const auto *R = dyn_cast<RecordDecl>(Val: TmpD))
2145 DiagnoseUnusedNestedTypedefs(D: R, DiagReceiver);
2146 }
2147}
2148
2149void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2150 DiagnoseUnusedDecl(
2151 ND: D, DiagReceiver: [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2152}
2153
2154void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2155 if (!ShouldDiagnoseUnusedDecl(LangOpts: getLangOpts(), D))
2156 return;
2157
2158 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2159 // typedefs can be referenced later on, so the diagnostics are emitted
2160 // at end-of-translation-unit.
2161 UnusedLocalTypedefNameCandidates.insert(X: TD);
2162 return;
2163 }
2164
2165 FixItHint Hint;
2166 GenerateFixForUnusedDecl(D, Ctx&: Context, Hint);
2167
2168 unsigned DiagID;
2169 if (isa<VarDecl>(Val: D) && cast<VarDecl>(Val: D)->isExceptionVariable())
2170 DiagID = diag::warn_unused_exception_param;
2171 else if (isa<LabelDecl>(Val: D))
2172 DiagID = diag::warn_unused_label;
2173 else
2174 DiagID = diag::warn_unused_variable;
2175
2176 SourceLocation DiagLoc = D->getLocation();
2177 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2178}
2179
2180void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2181 DiagReceiverTy DiagReceiver) {
2182 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2183 // it's not really unused.
2184 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2185 return;
2186
2187 // In C++, `_` variables behave as if they were maybe_unused
2188 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(LangOpts: getLangOpts()))
2189 return;
2190
2191 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2192
2193 if (Ty->isReferenceType() || Ty->isDependentType())
2194 return;
2195
2196 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2197 if (Tag->hasAttr<UnusedAttr>())
2198 return;
2199 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2200 // mimic gcc's behavior.
2201 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag);
2202 RD && !RD->hasAttr<WarnUnusedAttr>())
2203 return;
2204 }
2205
2206 // Don't warn about __block Objective-C pointer variables, as they might
2207 // be assigned in the block but not used elsewhere for the purpose of lifetime
2208 // extension.
2209 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2210 return;
2211
2212 // Don't warn about Objective-C pointer variables with precise lifetime
2213 // semantics; they can be used to ensure ARC releases the object at a known
2214 // time, which may mean assignment but no other references.
2215 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2216 return;
2217
2218 auto iter = RefsMinusAssignments.find(Val: VD);
2219 if (iter == RefsMinusAssignments.end())
2220 return;
2221
2222 assert(iter->getSecond() >= 0 &&
2223 "Found a negative number of references to a VarDecl");
2224 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2225 // Assume the given VarDecl is "used" if its ref count stored in
2226 // `RefMinusAssignments` is positive, with one exception.
2227 //
2228 // For a C++ variable whose decl (with initializer) entirely consist the
2229 // condition expression of a if/while/for construct,
2230 // Clang creates a DeclRefExpr for the condition expression rather than a
2231 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2232 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2233 // used in the body of the if/while/for construct.
2234 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2235 if (!UnusedCXXCondDecl)
2236 return;
2237 }
2238
2239 unsigned DiagID = isa<ParmVarDecl>(Val: VD) ? diag::warn_unused_but_set_parameter
2240 : diag::warn_unused_but_set_variable;
2241 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2242}
2243
2244static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2245 Sema::DiagReceiverTy DiagReceiver) {
2246 // Verify that we have no forward references left. If so, there was a goto
2247 // or address of a label taken, but no definition of it. Label fwd
2248 // definitions are indicated with a null substmt which is also not a resolved
2249 // MS inline assembly label name.
2250 bool Diagnose = false;
2251 if (L->isMSAsmLabel())
2252 Diagnose = !L->isResolvedMSAsmLabel();
2253 else
2254 Diagnose = L->getStmt() == nullptr;
2255 if (Diagnose)
2256 DiagReceiver(L->getLocation(), S.PDiag(DiagID: diag::err_undeclared_label_use)
2257 << L);
2258}
2259
2260void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2261 S->applyNRVO();
2262
2263 if (S->decl_empty()) return;
2264 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2265 "Scope shouldn't contain decls!");
2266
2267 /// We visit the decls in non-deterministic order, but we want diagnostics
2268 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2269 /// and sort the diagnostics before emitting them, after we visited all decls.
2270 struct LocAndDiag {
2271 SourceLocation Loc;
2272 std::optional<SourceLocation> PreviousDeclLoc;
2273 PartialDiagnostic PD;
2274 };
2275 SmallVector<LocAndDiag, 16> DeclDiags;
2276 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2277 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: std::nullopt, .PD: std::move(PD)});
2278 };
2279 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2280 SourceLocation PreviousDeclLoc,
2281 PartialDiagnostic PD) {
2282 DeclDiags.push_back(Elt: LocAndDiag{.Loc: Loc, .PreviousDeclLoc: PreviousDeclLoc, .PD: std::move(PD)});
2283 };
2284
2285 for (auto *TmpD : S->decls()) {
2286 assert(TmpD && "This decl didn't get pushed??");
2287
2288 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2289 NamedDecl *D = cast<NamedDecl>(Val: TmpD);
2290
2291 // Diagnose unused variables in this scope.
2292 if (!S->hasUnrecoverableErrorOccurred()) {
2293 DiagnoseUnusedDecl(D, DiagReceiver: addDiag);
2294 if (const auto *RD = dyn_cast<RecordDecl>(Val: D))
2295 DiagnoseUnusedNestedTypedefs(D: RD, DiagReceiver: addDiag);
2296 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2297 DiagnoseUnusedButSetDecl(VD, DiagReceiver: addDiag);
2298 RefsMinusAssignments.erase(Val: VD);
2299 }
2300 }
2301
2302 if (!D->getDeclName()) continue;
2303
2304 // If this was a forward reference to a label, verify it was defined.
2305 if (LabelDecl *LD = dyn_cast<LabelDecl>(Val: D))
2306 CheckPoppedLabel(L: LD, S&: *this, DiagReceiver: addDiag);
2307
2308 // Partial translation units that are created in incremental processing must
2309 // not clean up the IdResolver because PTUs should take into account the
2310 // declarations that came from previous PTUs.
2311 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2312 getLangOpts().CPlusPlus)
2313 IdResolver.RemoveDecl(D);
2314
2315 // Warn on it if we are shadowing a declaration.
2316 auto ShadowI = ShadowingDecls.find(Val: D);
2317 if (ShadowI != ShadowingDecls.end()) {
2318 if (const auto *FD = dyn_cast<FieldDecl>(Val: ShadowI->second)) {
2319 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2320 PDiag(DiagID: diag::warn_ctor_parm_shadows_field)
2321 << D << FD << FD->getParent());
2322 }
2323 ShadowingDecls.erase(I: ShadowI);
2324 }
2325 }
2326
2327 llvm::sort(C&: DeclDiags,
2328 Comp: [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2329 // The particular order for diagnostics is not important, as long
2330 // as the order is deterministic. Using the raw location is going
2331 // to generally be in source order unless there are macro
2332 // expansions involved.
2333 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2334 });
2335 for (const LocAndDiag &D : DeclDiags) {
2336 Diag(Loc: D.Loc, PD: D.PD);
2337 if (D.PreviousDeclLoc)
2338 Diag(Loc: *D.PreviousDeclLoc, DiagID: diag::note_previous_declaration);
2339 }
2340}
2341
2342Scope *Sema::getNonFieldDeclScope(Scope *S) {
2343 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2344 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2345 (S->isClassScope() && !getLangOpts().CPlusPlus))
2346 S = S->getParent();
2347 return S;
2348}
2349
2350static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2351 ASTContext::GetBuiltinTypeError Error) {
2352 switch (Error) {
2353 case ASTContext::GE_None:
2354 return "";
2355 case ASTContext::GE_Missing_type:
2356 return BuiltinInfo.getHeaderName(ID);
2357 case ASTContext::GE_Missing_stdio:
2358 return "stdio.h";
2359 case ASTContext::GE_Missing_setjmp:
2360 return "setjmp.h";
2361 case ASTContext::GE_Missing_ucontext:
2362 return "ucontext.h";
2363 }
2364 llvm_unreachable("unhandled error kind");
2365}
2366
2367FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2368 unsigned ID, SourceLocation Loc) {
2369 DeclContext *Parent = Context.getTranslationUnitDecl();
2370
2371 if (getLangOpts().CPlusPlus) {
2372 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2373 C&: Context, DC: Parent, ExternLoc: Loc, LangLoc: Loc, Lang: LinkageSpecLanguageIDs::C, HasBraces: false);
2374 CLinkageDecl->setImplicit();
2375 Parent->addDecl(D: CLinkageDecl);
2376 Parent = CLinkageDecl;
2377 }
2378
2379 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified;
2380 if (Context.BuiltinInfo.isImmediate(ID)) {
2381 assert(getLangOpts().CPlusPlus20 &&
2382 "consteval builtins should only be available in C++20 mode");
2383 ConstexprKind = ConstexprSpecKind::Consteval;
2384 }
2385
2386 FunctionDecl *New = FunctionDecl::Create(
2387 C&: Context, DC: Parent, StartLoc: Loc, NLoc: Loc, N: II, T: Type, /*TInfo=*/nullptr, SC: SC_Extern,
2388 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2389 hasWrittenPrototype: Type->isFunctionProtoType(), ConstexprKind);
2390 New->setImplicit();
2391 New->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID));
2392
2393 // Create Decl objects for each parameter, adding them to the
2394 // FunctionDecl.
2395 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: Type)) {
2396 SmallVector<ParmVarDecl *, 16> Params;
2397 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2398 ParmVarDecl *parm = ParmVarDecl::Create(
2399 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
2400 T: FT->getParamType(i), /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
2401 parm->setScopeInfo(scopeDepth: 0, parameterIndex: i);
2402 Params.push_back(Elt: parm);
2403 }
2404 New->setParams(Params);
2405 }
2406
2407 AddKnownFunctionAttributes(FD: New);
2408 return New;
2409}
2410
2411NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2412 Scope *S, bool ForRedeclaration,
2413 SourceLocation Loc) {
2414 LookupNecessaryTypesForBuiltin(S, ID);
2415
2416 ASTContext::GetBuiltinTypeError Error;
2417 QualType R = Context.GetBuiltinType(ID, Error);
2418 if (Error) {
2419 if (!ForRedeclaration)
2420 return nullptr;
2421
2422 // If we have a builtin without an associated type we should not emit a
2423 // warning when we were not able to find a type for it.
2424 if (Error == ASTContext::GE_Missing_type ||
2425 Context.BuiltinInfo.allowTypeMismatch(ID))
2426 return nullptr;
2427
2428 // If we could not find a type for setjmp it is because the jmp_buf type was
2429 // not defined prior to the setjmp declaration.
2430 if (Error == ASTContext::GE_Missing_setjmp) {
2431 Diag(Loc, DiagID: diag::warn_implicit_decl_no_jmp_buf)
2432 << Context.BuiltinInfo.getName(ID);
2433 return nullptr;
2434 }
2435
2436 // Generally, we emit a warning that the declaration requires the
2437 // appropriate header.
2438 Diag(Loc, DiagID: diag::warn_implicit_decl_requires_sysheader)
2439 << getHeaderName(BuiltinInfo&: Context.BuiltinInfo, ID, Error)
2440 << Context.BuiltinInfo.getName(ID);
2441 return nullptr;
2442 }
2443
2444 if (!ForRedeclaration &&
2445 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2446 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2447 Diag(Loc, DiagID: LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2448 : diag::ext_implicit_lib_function_decl)
2449 << Context.BuiltinInfo.getName(ID) << R;
2450 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2451 Diag(Loc, DiagID: diag::note_include_header_or_declare)
2452 << Header << Context.BuiltinInfo.getName(ID);
2453 }
2454
2455 if (R.isNull())
2456 return nullptr;
2457
2458 FunctionDecl *New = CreateBuiltin(II, Type: R, ID, Loc);
2459 RegisterLocallyScopedExternCDecl(ND: New, S);
2460
2461 // TUScope is the translation-unit scope to insert this function into.
2462 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2463 // relate Scopes to DeclContexts, and probably eliminate CurContext
2464 // entirely, but we're not there yet.
2465 DeclContext *SavedContext = CurContext;
2466 CurContext = New->getDeclContext();
2467 PushOnScopeChains(D: New, S: TUScope);
2468 CurContext = SavedContext;
2469 return New;
2470}
2471
2472/// Typedef declarations don't have linkage, but they still denote the same
2473/// entity if their types are the same.
2474/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2475/// isSameEntity.
2476static void
2477filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl,
2478 LookupResult &Previous) {
2479 // This is only interesting when modules are enabled.
2480 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2481 return;
2482
2483 // Empty sets are uninteresting.
2484 if (Previous.empty())
2485 return;
2486
2487 LookupResult::Filter Filter = Previous.makeFilter();
2488 while (Filter.hasNext()) {
2489 NamedDecl *Old = Filter.next();
2490
2491 // Non-hidden declarations are never ignored.
2492 if (S.isVisible(D: Old))
2493 continue;
2494
2495 // Declarations of the same entity are not ignored, even if they have
2496 // different linkages.
2497 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2498 if (S.Context.hasSameType(T1: OldTD->getUnderlyingType(),
2499 T2: Decl->getUnderlyingType()))
2500 continue;
2501
2502 // If both declarations give a tag declaration a typedef name for linkage
2503 // purposes, then they declare the same entity.
2504 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2505 Decl->getAnonDeclWithTypedefName())
2506 continue;
2507 }
2508
2509 Filter.erase();
2510 }
2511
2512 Filter.done();
2513}
2514
2515bool Sema::isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New) {
2516 QualType OldType;
2517 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Val: Old))
2518 OldType = OldTypedef->getUnderlyingType();
2519 else
2520 OldType = Context.getTypeDeclType(Decl: Old);
2521 QualType NewType = New->getUnderlyingType();
2522
2523 if (NewType->isVariablyModifiedType()) {
2524 // Must not redefine a typedef with a variably-modified type.
2525 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2526 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_variably_modified_typedef)
2527 << Kind << NewType;
2528 if (Old->getLocation().isValid())
2529 notePreviousDefinition(Old, New: New->getLocation());
2530 New->setInvalidDecl();
2531 return true;
2532 }
2533
2534 if (OldType != NewType &&
2535 !OldType->isDependentType() &&
2536 !NewType->isDependentType() &&
2537 !Context.hasSameType(T1: OldType, T2: NewType)) {
2538 int Kind = isa<TypeAliasDecl>(Val: Old) ? 1 : 0;
2539 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_typedef)
2540 << Kind << NewType << OldType;
2541 if (Old->getLocation().isValid())
2542 notePreviousDefinition(Old, New: New->getLocation());
2543 New->setInvalidDecl();
2544 return true;
2545 }
2546 return false;
2547}
2548
2549void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2550 LookupResult &OldDecls) {
2551 // If the new decl is known invalid already, don't bother doing any
2552 // merging checks.
2553 if (New->isInvalidDecl()) return;
2554
2555 // Allow multiple definitions for ObjC built-in typedefs.
2556 // FIXME: Verify the underlying types are equivalent!
2557 if (getLangOpts().ObjC) {
2558 const IdentifierInfo *TypeID = New->getIdentifier();
2559 switch (TypeID->getLength()) {
2560 default: break;
2561 case 2:
2562 {
2563 if (!TypeID->isStr(Str: "id"))
2564 break;
2565 QualType T = New->getUnderlyingType();
2566 if (!T->isPointerType())
2567 break;
2568 if (!T->isVoidPointerType()) {
2569 QualType PT = T->castAs<PointerType>()->getPointeeType();
2570 if (!PT->isStructureType())
2571 break;
2572 }
2573 Context.setObjCIdRedefinitionType(T);
2574 // Install the built-in type for 'id', ignoring the current definition.
2575 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2576 modedTy: Context.getObjCIdType());
2577 return;
2578 }
2579 case 5:
2580 if (!TypeID->isStr(Str: "Class"))
2581 break;
2582 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2583 // Install the built-in type for 'Class', ignoring the current definition.
2584 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2585 modedTy: Context.getObjCClassType());
2586 return;
2587 case 3:
2588 if (!TypeID->isStr(Str: "SEL"))
2589 break;
2590 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2591 // Install the built-in type for 'SEL', ignoring the current definition.
2592 New->setModedTypeSourceInfo(unmodedTSI: New->getTypeSourceInfo(),
2593 modedTy: Context.getObjCSelType());
2594 return;
2595 }
2596 // Fall through - the typedef name was not a builtin type.
2597 }
2598
2599 // Verify the old decl was also a type.
2600 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2601 if (!Old) {
2602 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
2603 << New->getDeclName();
2604
2605 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2606 if (OldD->getLocation().isValid())
2607 notePreviousDefinition(Old: OldD, New: New->getLocation());
2608
2609 return New->setInvalidDecl();
2610 }
2611
2612 // If the old declaration is invalid, just give up here.
2613 if (Old->isInvalidDecl())
2614 return New->setInvalidDecl();
2615
2616 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Val: Old)) {
2617 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2618 auto *NewTag = New->getAnonDeclWithTypedefName();
2619 NamedDecl *Hidden = nullptr;
2620 if (OldTag && NewTag &&
2621 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2622 !hasVisibleDefinition(D: OldTag, Suggested: &Hidden)) {
2623 // There is a definition of this tag, but it is not visible. Use it
2624 // instead of our tag.
2625 if (OldTD->isModed())
2626 New->setModedTypeSourceInfo(unmodedTSI: OldTD->getTypeSourceInfo(),
2627 modedTy: OldTD->getUnderlyingType());
2628 else
2629 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2630
2631 // Make the old tag definition visible.
2632 makeMergedDefinitionVisible(ND: Hidden);
2633
2634 CleanupMergedEnum(S, New: NewTag);
2635 }
2636 }
2637
2638 // If the typedef types are not identical, reject them in all languages and
2639 // with any extensions enabled.
2640 if (isIncompatibleTypedef(Old, New))
2641 return;
2642
2643 // The types match. Link up the redeclaration chain and merge attributes if
2644 // the old declaration was a typedef.
2645 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Val: Old)) {
2646 New->setPreviousDecl(Typedef);
2647 mergeDeclAttributes(New, Old);
2648 }
2649
2650 if (getLangOpts().MicrosoftExt)
2651 return;
2652
2653 if (getLangOpts().CPlusPlus) {
2654 // C++ [dcl.typedef]p2:
2655 // In a given non-class scope, a typedef specifier can be used to
2656 // redefine the name of any type declared in that scope to refer
2657 // to the type to which it already refers.
2658 if (!isa<CXXRecordDecl>(Val: CurContext))
2659 return;
2660
2661 // C++0x [dcl.typedef]p4:
2662 // In a given class scope, a typedef specifier can be used to redefine
2663 // any class-name declared in that scope that is not also a typedef-name
2664 // to refer to the type to which it already refers.
2665 //
2666 // This wording came in via DR424, which was a correction to the
2667 // wording in DR56, which accidentally banned code like:
2668 //
2669 // struct S {
2670 // typedef struct A { } A;
2671 // };
2672 //
2673 // in the C++03 standard. We implement the C++0x semantics, which
2674 // allow the above but disallow
2675 //
2676 // struct S {
2677 // typedef int I;
2678 // typedef int I;
2679 // };
2680 //
2681 // since that was the intent of DR56.
2682 if (!isa<TypedefNameDecl>(Val: Old))
2683 return;
2684
2685 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition)
2686 << New->getDeclName();
2687 notePreviousDefinition(Old, New: New->getLocation());
2688 return New->setInvalidDecl();
2689 }
2690
2691 // Modules always permit redefinition of typedefs, as does C11.
2692 if (getLangOpts().Modules || getLangOpts().C11)
2693 return;
2694
2695 // If we have a redefinition of a typedef in C, emit a warning. This warning
2696 // is normally mapped to an error, but can be controlled with
2697 // -Wtypedef-redefinition. If either the original or the redefinition is
2698 // in a system header, don't emit this for compatibility with GCC.
2699 if (getDiagnostics().getSuppressSystemWarnings() &&
2700 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2701 (Old->isImplicit() ||
2702 Context.getSourceManager().isInSystemHeader(Loc: Old->getLocation()) ||
2703 Context.getSourceManager().isInSystemHeader(Loc: New->getLocation())))
2704 return;
2705
2706 Diag(Loc: New->getLocation(), DiagID: diag::ext_redefinition_of_typedef)
2707 << New->getDeclName();
2708 notePreviousDefinition(Old, New: New->getLocation());
2709}
2710
2711void Sema::CleanupMergedEnum(Scope *S, Decl *New) {
2712 // If this was an unscoped enumeration, yank all of its enumerators
2713 // out of the scope.
2714 if (auto *ED = dyn_cast<EnumDecl>(Val: New); ED && !ED->isScoped()) {
2715 Scope *EnumScope = getNonFieldDeclScope(S);
2716 for (auto *ECD : ED->enumerators()) {
2717 assert(EnumScope->isDeclScope(ECD));
2718 EnumScope->RemoveDecl(D: ECD);
2719 IdResolver.RemoveDecl(D: ECD);
2720 }
2721 }
2722}
2723
2724/// DeclhasAttr - returns true if decl Declaration already has the target
2725/// attribute.
2726static bool DeclHasAttr(const Decl *D, const Attr *A) {
2727 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(Val: A);
2728 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(Val: A);
2729 for (const auto *i : D->attrs())
2730 if (i->getKind() == A->getKind()) {
2731 if (Ann) {
2732 if (Ann->getAnnotation() == cast<AnnotateAttr>(Val: i)->getAnnotation())
2733 return true;
2734 continue;
2735 }
2736 // FIXME: Don't hardcode this check
2737 if (OA && isa<OwnershipAttr>(Val: i))
2738 return OA->getOwnKind() == cast<OwnershipAttr>(Val: i)->getOwnKind();
2739 return true;
2740 }
2741
2742 return false;
2743}
2744
2745static bool isAttributeTargetADefinition(Decl *D) {
2746 if (VarDecl *VD = dyn_cast<VarDecl>(Val: D))
2747 return VD->isThisDeclarationADefinition();
2748 if (TagDecl *TD = dyn_cast<TagDecl>(Val: D))
2749 return TD->isCompleteDefinition() || TD->isBeingDefined();
2750 return true;
2751}
2752
2753/// Merge alignment attributes from \p Old to \p New, taking into account the
2754/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2755///
2756/// \return \c true if any attributes were added to \p New.
2757static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2758 // Look for alignas attributes on Old, and pick out whichever attribute
2759 // specifies the strictest alignment requirement.
2760 AlignedAttr *OldAlignasAttr = nullptr;
2761 AlignedAttr *OldStrictestAlignAttr = nullptr;
2762 unsigned OldAlign = 0;
2763 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2764 // FIXME: We have no way of representing inherited dependent alignments
2765 // in a case like:
2766 // template<int A, int B> struct alignas(A) X;
2767 // template<int A, int B> struct alignas(B) X {};
2768 // For now, we just ignore any alignas attributes which are not on the
2769 // definition in such a case.
2770 if (I->isAlignmentDependent())
2771 return false;
2772
2773 if (I->isAlignas())
2774 OldAlignasAttr = I;
2775
2776 unsigned Align = I->getAlignment(Ctx&: S.Context);
2777 if (Align > OldAlign) {
2778 OldAlign = Align;
2779 OldStrictestAlignAttr = I;
2780 }
2781 }
2782
2783 // Look for alignas attributes on New.
2784 AlignedAttr *NewAlignasAttr = nullptr;
2785 unsigned NewAlign = 0;
2786 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2787 if (I->isAlignmentDependent())
2788 return false;
2789
2790 if (I->isAlignas())
2791 NewAlignasAttr = I;
2792
2793 unsigned Align = I->getAlignment(Ctx&: S.Context);
2794 if (Align > NewAlign)
2795 NewAlign = Align;
2796 }
2797
2798 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2799 // Both declarations have 'alignas' attributes. We require them to match.
2800 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2801 // fall short. (If two declarations both have alignas, they must both match
2802 // every definition, and so must match each other if there is a definition.)
2803
2804 // If either declaration only contains 'alignas(0)' specifiers, then it
2805 // specifies the natural alignment for the type.
2806 if (OldAlign == 0 || NewAlign == 0) {
2807 QualType Ty;
2808 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: New))
2809 Ty = VD->getType();
2810 else
2811 Ty = S.Context.getCanonicalTagType(TD: cast<TagDecl>(Val: New));
2812
2813 if (OldAlign == 0)
2814 OldAlign = S.Context.getTypeAlign(T: Ty);
2815 if (NewAlign == 0)
2816 NewAlign = S.Context.getTypeAlign(T: Ty);
2817 }
2818
2819 if (OldAlign != NewAlign) {
2820 S.Diag(Loc: NewAlignasAttr->getLocation(), DiagID: diag::err_alignas_mismatch)
2821 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: OldAlign).getQuantity()
2822 << (unsigned)S.Context.toCharUnitsFromBits(BitSize: NewAlign).getQuantity();
2823 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_previous_declaration);
2824 }
2825 }
2826
2827 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(D: New)) {
2828 // C++11 [dcl.align]p6:
2829 // if any declaration of an entity has an alignment-specifier,
2830 // every defining declaration of that entity shall specify an
2831 // equivalent alignment.
2832 // C11 6.7.5/7:
2833 // If the definition of an object does not have an alignment
2834 // specifier, any other declaration of that object shall also
2835 // have no alignment specifier.
2836 S.Diag(Loc: New->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
2837 << OldAlignasAttr;
2838 S.Diag(Loc: OldAlignasAttr->getLocation(), DiagID: diag::note_alignas_on_declaration)
2839 << OldAlignasAttr;
2840 }
2841
2842 bool AnyAdded = false;
2843
2844 // Ensure we have an attribute representing the strictest alignment.
2845 if (OldAlign > NewAlign) {
2846 AlignedAttr *Clone = OldStrictestAlignAttr->clone(C&: S.Context);
2847 Clone->setInherited(true);
2848 New->addAttr(A: Clone);
2849 AnyAdded = true;
2850 }
2851
2852 // Ensure we have an alignas attribute if the old declaration had one.
2853 if (OldAlignasAttr && !NewAlignasAttr &&
2854 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2855 AlignedAttr *Clone = OldAlignasAttr->clone(C&: S.Context);
2856 Clone->setInherited(true);
2857 New->addAttr(A: Clone);
2858 AnyAdded = true;
2859 }
2860
2861 return AnyAdded;
2862}
2863
2864#define WANT_DECL_MERGE_LOGIC
2865#include "clang/Sema/AttrParsedAttrImpl.inc"
2866#undef WANT_DECL_MERGE_LOGIC
2867
2868static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2869 const InheritableAttr *Attr,
2870 AvailabilityMergeKind AMK) {
2871 // Diagnose any mutual exclusions between the attribute that we want to add
2872 // and attributes that already exist on the declaration.
2873 if (!DiagnoseMutualExclusions(S, D, A: Attr))
2874 return false;
2875
2876 // This function copies an attribute Attr from a previous declaration to the
2877 // new declaration D if the new declaration doesn't itself have that attribute
2878 // yet or if that attribute allows duplicates.
2879 // If you're adding a new attribute that requires logic different from
2880 // "use explicit attribute on decl if present, else use attribute from
2881 // previous decl", for example if the attribute needs to be consistent
2882 // between redeclarations, you need to call a custom merge function here.
2883 InheritableAttr *NewAttr = nullptr;
2884 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: Attr))
2885 NewAttr = S.mergeAvailabilityAttr(
2886 D, CI: *AA, Platform: AA->getPlatform(), Implicit: AA->isImplicit(), Introduced: AA->getIntroduced(),
2887 Deprecated: AA->getDeprecated(), Obsoleted: AA->getObsoleted(), IsUnavailable: AA->getUnavailable(),
2888 Message: AA->getMessage(), IsStrict: AA->getStrict(), Replacement: AA->getReplacement(), AMK,
2889 Priority: AA->getPriority(), IIEnvironment: AA->getEnvironment());
2890 else if (const auto *VA = dyn_cast<VisibilityAttr>(Val: Attr))
2891 NewAttr = S.mergeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2892 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Val: Attr))
2893 NewAttr = S.mergeTypeVisibilityAttr(D, CI: *VA, Vis: VA->getVisibility());
2894 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Val: Attr))
2895 NewAttr = S.mergeDLLImportAttr(D, CI: *ImportA);
2896 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Val: Attr))
2897 NewAttr = S.mergeDLLExportAttr(D, CI: *ExportA);
2898 else if (const auto *EA = dyn_cast<ErrorAttr>(Val: Attr))
2899 NewAttr = S.mergeErrorAttr(D, CI: *EA, NewUserDiagnostic: EA->getUserDiagnostic());
2900 else if (const auto *FA = dyn_cast<FormatAttr>(Val: Attr))
2901 NewAttr = S.mergeFormatAttr(D, CI: *FA, Format: FA->getType(), FormatIdx: FA->getFormatIdx(),
2902 FirstArg: FA->getFirstArg());
2903 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Val: Attr))
2904 NewAttr = S.mergeFormatMatchesAttr(
2905 D, CI: *FMA, Format: FMA->getType(), FormatIdx: FMA->getFormatIdx(), FormatStr: FMA->getFormatString());
2906 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Val: Attr))
2907 NewAttr = S.mergeModularFormatAttr(
2908 D, CI: *MFA, ModularImplFn: MFA->getModularImplFn(), ImplName: MFA->getImplName(),
2909 Aspects: MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2910 else if (const auto *SA = dyn_cast<SectionAttr>(Val: Attr))
2911 NewAttr = S.mergeSectionAttr(D, CI: *SA, Name: SA->getName());
2912 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Val: Attr))
2913 NewAttr = S.mergeCodeSegAttr(D, CI: *CSA, Name: CSA->getName());
2914 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Val: Attr))
2915 NewAttr = S.mergeMSInheritanceAttr(D, CI: *IA, BestCase: IA->getBestCase(),
2916 Model: IA->getInheritanceModel());
2917 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Val: Attr))
2918 NewAttr = S.mergeAlwaysInlineAttr(D, CI: *AA,
2919 Ident: &S.Context.Idents.get(Name: AA->getSpelling()));
2920 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(Val: D) &&
2921 (isa<CUDAHostAttr>(Val: Attr) || isa<CUDADeviceAttr>(Val: Attr) ||
2922 isa<CUDAGlobalAttr>(Val: Attr))) {
2923 // CUDA target attributes are part of function signature for
2924 // overloading purposes and must not be merged.
2925 return false;
2926 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Val: Attr))
2927 NewAttr = S.mergeMinSizeAttr(D, CI: *MA);
2928 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Val: Attr))
2929 NewAttr = S.Swift().mergeNameAttr(D, SNA: *SNA, Name: SNA->getName());
2930 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Val: Attr))
2931 NewAttr = S.mergeOptimizeNoneAttr(D, CI: *OA);
2932 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Val: Attr))
2933 NewAttr = S.mergeInternalLinkageAttr(D, AL: *InternalLinkageA);
2934 else if (isa<AlignedAttr>(Val: Attr))
2935 // AlignedAttrs are handled separately, because we need to handle all
2936 // such attributes on a declaration at the same time.
2937 NewAttr = nullptr;
2938 else if ((isa<DeprecatedAttr>(Val: Attr) || isa<UnavailableAttr>(Val: Attr)) &&
2939 (AMK == AvailabilityMergeKind::Override ||
2940 AMK == AvailabilityMergeKind::ProtocolImplementation ||
2941 AMK == AvailabilityMergeKind::OptionalProtocolImplementation))
2942 NewAttr = nullptr;
2943 else if (const auto *UA = dyn_cast<UuidAttr>(Val: Attr))
2944 NewAttr = S.mergeUuidAttr(D, CI: *UA, UuidAsWritten: UA->getGuid(), GuidDecl: UA->getGuidDecl());
2945 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Val: Attr))
2946 NewAttr = S.Wasm().mergeImportModuleAttr(D, AL: *IMA);
2947 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Val: Attr))
2948 NewAttr = S.Wasm().mergeImportNameAttr(D, AL: *INA);
2949 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Val: Attr))
2950 NewAttr = S.mergeEnforceTCBAttr(D, AL: *TCBA);
2951 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Val: Attr))
2952 NewAttr = S.mergeEnforceTCBLeafAttr(D, AL: *TCBLA);
2953 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Val: Attr))
2954 NewAttr = S.mergeBTFDeclTagAttr(D, AL: *BTFA);
2955 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Val: Attr))
2956 NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL: *NT, X: NT->getX(), Y: NT->getY(),
2957 Z: NT->getZ());
2958 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Val: Attr))
2959 NewAttr = S.HLSL().mergeWaveSizeAttr(D, AL: *WS, Min: WS->getMin(), Max: WS->getMax(),
2960 Preferred: WS->getPreferred(),
2961 SpelledArgsCount: WS->getSpelledArgsCount());
2962 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Val: Attr))
2963 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, AL: *CI, Id: CI->getId());
2964 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Val: Attr))
2965 NewAttr = S.HLSL().mergeShaderAttr(D, AL: *SA, ShaderType: SA->getType());
2966 else if (isa<SuppressAttr>(Val: Attr))
2967 // Do nothing. Each redeclaration should be suppressed separately.
2968 NewAttr = nullptr;
2969 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Val: Attr))
2970 NewAttr = S.OpenACC().mergeRoutineDeclAttr(Old: *RD);
2971 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, A: Attr))
2972 NewAttr = cast<InheritableAttr>(Val: Attr->clone(C&: S.Context));
2973
2974 if (NewAttr) {
2975 NewAttr->setInherited(true);
2976 D->addAttr(A: NewAttr);
2977 if (isa<MSInheritanceAttr>(Val: NewAttr))
2978 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
2979 return true;
2980 }
2981
2982 return false;
2983}
2984
2985static const NamedDecl *getDefinition(const Decl *D) {
2986 if (const TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
2987 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
2988 return Def;
2989 return nullptr;
2990 }
2991 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
2992 const VarDecl *Def = VD->getDefinition();
2993 if (Def)
2994 return Def;
2995 return VD->getActingDefinition();
2996 }
2997 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
2998 const FunctionDecl *Def = nullptr;
2999 if (FD->isDefined(Definition&: Def, CheckForPendingFriendDefinition: true))
3000 return Def;
3001 }
3002 return nullptr;
3003}
3004
3005static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3006 for (const auto *Attribute : D->attrs())
3007 if (Attribute->getKind() == Kind)
3008 return true;
3009 return false;
3010}
3011
3012/// checkNewAttributesAfterDef - If we already have a definition, check that
3013/// there are no new attributes in this declaration.
3014static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3015 if (!New->hasAttrs())
3016 return;
3017
3018 const NamedDecl *Def = getDefinition(D: Old);
3019 if (!Def || Def == New)
3020 return;
3021
3022 AttrVec &NewAttributes = New->getAttrs();
3023 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3024 Attr *NewAttribute = NewAttributes[I];
3025
3026 if (isa<AliasAttr>(Val: NewAttribute) || isa<IFuncAttr>(Val: NewAttribute)) {
3027 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: New)) {
3028 SkipBodyInfo SkipBody;
3029 S.CheckForFunctionRedefinition(FD, EffectiveDefinition: cast<FunctionDecl>(Val: Def), SkipBody: &SkipBody);
3030
3031 // If we're skipping this definition, drop the "alias" attribute.
3032 if (SkipBody.ShouldSkip) {
3033 NewAttributes.erase(CI: NewAttributes.begin() + I);
3034 --E;
3035 continue;
3036 }
3037 } else {
3038 VarDecl *VD = cast<VarDecl>(Val: New);
3039 unsigned Diag = cast<VarDecl>(Val: Def)->isThisDeclarationADefinition() ==
3040 VarDecl::TentativeDefinition
3041 ? diag::err_alias_after_tentative
3042 : diag::err_redefinition;
3043 S.Diag(Loc: VD->getLocation(), DiagID: Diag) << VD->getDeclName();
3044 if (Diag == diag::err_redefinition)
3045 S.notePreviousDefinition(Old: Def, New: VD->getLocation());
3046 else
3047 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3048 VD->setInvalidDecl();
3049 }
3050 ++I;
3051 continue;
3052 }
3053
3054 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: Def)) {
3055 // Tentative definitions are only interesting for the alias check above.
3056 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3057 ++I;
3058 continue;
3059 }
3060 }
3061
3062 if (hasAttribute(D: Def, Kind: NewAttribute->getKind())) {
3063 ++I;
3064 continue; // regular attr merging will take care of validating this.
3065 }
3066
3067 if (isa<C11NoReturnAttr>(Val: NewAttribute)) {
3068 // C's _Noreturn is allowed to be added to a function after it is defined.
3069 ++I;
3070 continue;
3071 } else if (isa<UuidAttr>(Val: NewAttribute)) {
3072 // msvc will allow a subsequent definition to add an uuid to a class
3073 ++I;
3074 continue;
3075 } else if (isa<DeprecatedAttr, WarnUnusedResultAttr, UnusedAttr>(
3076 Val: NewAttribute) &&
3077 NewAttribute->isStandardAttributeSyntax()) {
3078 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3079 // deprecated attribute can later be re-declared with the attribute and
3080 // vice-versa.
3081 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3082 // maybe_unused attribute can later be redeclared with the attribute and
3083 // vice versa.
3084 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3085 // nodiscard attribute can later be redeclared with the attribute and
3086 // vice-versa.
3087 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3088 ++I;
3089 continue;
3090 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(Val: NewAttribute)) {
3091 if (AA->isAlignas()) {
3092 // C++11 [dcl.align]p6:
3093 // if any declaration of an entity has an alignment-specifier,
3094 // every defining declaration of that entity shall specify an
3095 // equivalent alignment.
3096 // C11 6.7.5/7:
3097 // If the definition of an object does not have an alignment
3098 // specifier, any other declaration of that object shall also
3099 // have no alignment specifier.
3100 S.Diag(Loc: Def->getLocation(), DiagID: diag::err_alignas_missing_on_definition)
3101 << AA;
3102 S.Diag(Loc: NewAttribute->getLocation(), DiagID: diag::note_alignas_on_declaration)
3103 << AA;
3104 NewAttributes.erase(CI: NewAttributes.begin() + I);
3105 --E;
3106 continue;
3107 }
3108 } else if (isa<LoaderUninitializedAttr>(Val: NewAttribute)) {
3109 // If there is a C definition followed by a redeclaration with this
3110 // attribute then there are two different definitions. In C++, prefer the
3111 // standard diagnostics.
3112 if (!S.getLangOpts().CPlusPlus) {
3113 S.Diag(Loc: NewAttribute->getLocation(),
3114 DiagID: diag::err_loader_uninitialized_redeclaration);
3115 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3116 NewAttributes.erase(CI: NewAttributes.begin() + I);
3117 --E;
3118 continue;
3119 }
3120 } else if (isa<SelectAnyAttr>(Val: NewAttribute) &&
3121 cast<VarDecl>(Val: New)->isInline() &&
3122 !cast<VarDecl>(Val: New)->isInlineSpecified()) {
3123 // Don't warn about applying selectany to implicitly inline variables.
3124 // Older compilers and language modes would require the use of selectany
3125 // to make such variables inline, and it would have no effect if we
3126 // honored it.
3127 ++I;
3128 continue;
3129 } else if (isa<OMPDeclareVariantAttr>(Val: NewAttribute)) {
3130 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3131 // declarations after definitions.
3132 ++I;
3133 continue;
3134 } else if (isa<SYCLKernelEntryPointAttr>(Val: NewAttribute)) {
3135 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3136 // error since the definition will have already been created without
3137 // the semantic effects of the attribute having been applied.
3138 S.Diag(Loc: NewAttribute->getLocation(),
3139 DiagID: diag::err_sycl_entry_point_after_definition)
3140 << NewAttribute;
3141 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3142 cast<SYCLKernelEntryPointAttr>(Val: NewAttribute)->setInvalidAttr();
3143 ++I;
3144 continue;
3145 } else if (isa<SYCLExternalAttr>(Val: NewAttribute)) {
3146 // SYCLExternalAttr may be added after a definition.
3147 ++I;
3148 continue;
3149 }
3150
3151 S.Diag(Loc: NewAttribute->getLocation(),
3152 DiagID: diag::warn_attribute_precede_definition);
3153 S.Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
3154 NewAttributes.erase(CI: NewAttributes.begin() + I);
3155 --E;
3156 }
3157}
3158
3159static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3160 const ConstInitAttr *CIAttr,
3161 bool AttrBeforeInit) {
3162 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3163
3164 // Figure out a good way to write this specifier on the old declaration.
3165 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3166 // enough of the attribute list spelling information to extract that without
3167 // heroics.
3168 std::string SuitableSpelling;
3169 if (S.getLangOpts().CPlusPlus20)
3170 SuitableSpelling = std::string(
3171 S.PP.getLastMacroWithSpelling(Loc: InsertLoc, Tokens: {tok::kw_constinit}));
3172 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3173 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3174 Loc: InsertLoc, Tokens: {tok::l_square, tok::l_square,
3175 S.PP.getIdentifierInfo(Name: "clang"), tok::coloncolon,
3176 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3177 tok::r_square, tok::r_square}));
3178 if (SuitableSpelling.empty())
3179 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3180 Loc: InsertLoc, Tokens: {tok::kw___attribute, tok::l_paren, tok::r_paren,
3181 S.PP.getIdentifierInfo(Name: "require_constant_initialization"),
3182 tok::r_paren, tok::r_paren}));
3183 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3184 SuitableSpelling = "constinit";
3185 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3186 SuitableSpelling = "[[clang::require_constant_initialization]]";
3187 if (SuitableSpelling.empty())
3188 SuitableSpelling = "__attribute__((require_constant_initialization))";
3189 SuitableSpelling += " ";
3190
3191 if (AttrBeforeInit) {
3192 // extern constinit int a;
3193 // int a = 0; // error (missing 'constinit'), accepted as extension
3194 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3195 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::ext_constinit_missing)
3196 << InitDecl << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3197 S.Diag(Loc: CIAttr->getLocation(), DiagID: diag::note_constinit_specified_here);
3198 } else {
3199 // int a = 0;
3200 // constinit extern int a; // error (missing 'constinit')
3201 S.Diag(Loc: CIAttr->getLocation(),
3202 DiagID: CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3203 : diag::warn_require_const_init_added_too_late)
3204 << FixItHint::CreateRemoval(RemoveRange: SourceRange(CIAttr->getLocation()));
3205 S.Diag(Loc: InitDecl->getLocation(), DiagID: diag::note_constinit_missing_here)
3206 << CIAttr->isConstinit()
3207 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: SuitableSpelling);
3208 }
3209}
3210
3211void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3212 AvailabilityMergeKind AMK) {
3213 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3214 UsedAttr *NewAttr = OldAttr->clone(C&: Context);
3215 NewAttr->setInherited(true);
3216 New->addAttr(A: NewAttr);
3217 }
3218 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3219 RetainAttr *NewAttr = OldAttr->clone(C&: Context);
3220 NewAttr->setInherited(true);
3221 New->addAttr(A: NewAttr);
3222 }
3223
3224 if (!Old->hasAttrs() && !New->hasAttrs())
3225 return;
3226
3227 // [dcl.constinit]p1:
3228 // If the [constinit] specifier is applied to any declaration of a
3229 // variable, it shall be applied to the initializing declaration.
3230 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3231 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3232 if (bool(OldConstInit) != bool(NewConstInit)) {
3233 const auto *OldVD = cast<VarDecl>(Val: Old);
3234 auto *NewVD = cast<VarDecl>(Val: New);
3235
3236 // Find the initializing declaration. Note that we might not have linked
3237 // the new declaration into the redeclaration chain yet.
3238 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3239 if (!InitDecl &&
3240 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3241 InitDecl = NewVD;
3242
3243 if (InitDecl == NewVD) {
3244 // This is the initializing declaration. If it would inherit 'constinit',
3245 // that's ill-formed. (Note that we do not apply this to the attribute
3246 // form).
3247 if (OldConstInit && OldConstInit->isConstinit())
3248 diagnoseMissingConstinit(S&: *this, InitDecl: NewVD, CIAttr: OldConstInit,
3249 /*AttrBeforeInit=*/true);
3250 } else if (NewConstInit) {
3251 // This is the first time we've been told that this declaration should
3252 // have a constant initializer. If we already saw the initializing
3253 // declaration, this is too late.
3254 if (InitDecl && InitDecl != NewVD) {
3255 diagnoseMissingConstinit(S&: *this, InitDecl, CIAttr: NewConstInit,
3256 /*AttrBeforeInit=*/false);
3257 NewVD->dropAttr<ConstInitAttr>();
3258 }
3259 }
3260 }
3261
3262 // Attributes declared post-definition are currently ignored.
3263 checkNewAttributesAfterDef(S&: *this, New, Old);
3264
3265 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3266 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3267 if (!OldA->isEquivalent(Other: NewA)) {
3268 // This redeclaration changes __asm__ label.
3269 Diag(Loc: New->getLocation(), DiagID: diag::err_different_asm_label);
3270 Diag(Loc: OldA->getLocation(), DiagID: diag::note_previous_declaration);
3271 }
3272 } else if (Old->isUsed()) {
3273 // This redeclaration adds an __asm__ label to a declaration that has
3274 // already been ODR-used.
3275 Diag(Loc: New->getLocation(), DiagID: diag::err_late_asm_label_name)
3276 << isa<FunctionDecl>(Val: Old) << New->getAttr<AsmLabelAttr>()->getRange();
3277 }
3278 }
3279
3280 // Re-declaration cannot add abi_tag's.
3281 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3282 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3283 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3284 if (!llvm::is_contained(Range: OldAbiTagAttr->tags(), Element: NewTag)) {
3285 Diag(Loc: NewAbiTagAttr->getLocation(),
3286 DiagID: diag::err_new_abi_tag_on_redeclaration)
3287 << NewTag;
3288 Diag(Loc: OldAbiTagAttr->getLocation(), DiagID: diag::note_previous_declaration);
3289 }
3290 }
3291 } else {
3292 Diag(Loc: NewAbiTagAttr->getLocation(), DiagID: diag::err_abi_tag_on_redeclaration);
3293 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3294 }
3295 }
3296
3297 // This redeclaration adds a section attribute.
3298 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3299 if (auto *VD = dyn_cast<VarDecl>(Val: New)) {
3300 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3301 Diag(Loc: New->getLocation(), DiagID: diag::warn_attribute_section_on_redeclaration);
3302 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3303 }
3304 }
3305 }
3306
3307 // Redeclaration adds code-seg attribute.
3308 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3309 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3310 !NewCSA->isImplicit() && isa<CXXMethodDecl>(Val: New)) {
3311 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_section)
3312 << 0 /*codeseg*/;
3313 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3314 }
3315
3316 if (!Old->hasAttrs())
3317 return;
3318
3319 bool foundAny = New->hasAttrs();
3320
3321 // Ensure that any moving of objects within the allocated map is done before
3322 // we process them.
3323 if (!foundAny) New->setAttrs(AttrVec());
3324
3325 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3326 // Ignore deprecated/unavailable/availability attributes if requested.
3327 AvailabilityMergeKind LocalAMK = AvailabilityMergeKind::None;
3328 if (isa<DeprecatedAttr>(Val: I) ||
3329 isa<UnavailableAttr>(Val: I) ||
3330 isa<AvailabilityAttr>(Val: I)) {
3331 switch (AMK) {
3332 case AvailabilityMergeKind::None:
3333 continue;
3334
3335 case AvailabilityMergeKind::Redeclaration:
3336 case AvailabilityMergeKind::Override:
3337 case AvailabilityMergeKind::ProtocolImplementation:
3338 case AvailabilityMergeKind::OptionalProtocolImplementation:
3339 LocalAMK = AMK;
3340 break;
3341 }
3342 }
3343
3344 // Already handled.
3345 if (isa<UsedAttr>(Val: I) || isa<RetainAttr>(Val: I))
3346 continue;
3347
3348 if (isa<InferredNoReturnAttr>(Val: I)) {
3349 if (auto *FD = dyn_cast<FunctionDecl>(Val: New);
3350 FD &&
3351 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3352 continue; // Don't propagate inferred noreturn attributes to explicit
3353 }
3354
3355 if (mergeDeclAttribute(S&: *this, D: New, Attr: I, AMK: LocalAMK))
3356 foundAny = true;
3357 }
3358
3359 if (mergeAlignedAttrs(S&: *this, New, Old))
3360 foundAny = true;
3361
3362 if (!foundAny) New->dropAttrs();
3363}
3364
3365void Sema::CheckAttributesOnDeducedType(Decl *D) {
3366 for (const Attr *A : D->attrs())
3367 checkAttrIsTypeDependent(D, A);
3368}
3369
3370// Returns the number of added attributes.
3371template <class T>
3372static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3373 Sema &S) {
3374 unsigned found = 0;
3375 for (const auto *I : From->specific_attrs<T>()) {
3376 if (!DeclHasAttr(To, I)) {
3377 T *newAttr = cast<T>(I->clone(S.Context));
3378 newAttr->setInherited(true);
3379 To->addAttr(A: newAttr);
3380 ++found;
3381 }
3382 }
3383 return found;
3384}
3385
3386template <class F>
3387static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3388 F &&propagator) {
3389 if (!From->hasAttrs()) {
3390 return;
3391 }
3392
3393 bool foundAny = To->hasAttrs();
3394
3395 // Ensure that any moving of objects within the allocated map is
3396 // done before we process them.
3397 if (!foundAny)
3398 To->setAttrs(AttrVec());
3399
3400 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3401
3402 if (!foundAny)
3403 To->dropAttrs();
3404}
3405
3406/// mergeParamDeclAttributes - Copy attributes from the old parameter
3407/// to the new one.
3408static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3409 const ParmVarDecl *oldDecl,
3410 Sema &S) {
3411 // C++11 [dcl.attr.depend]p2:
3412 // The first declaration of a function shall specify the
3413 // carries_dependency attribute for its declarator-id if any declaration
3414 // of the function specifies the carries_dependency attribute.
3415 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3416 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3417 S.Diag(Loc: CDA->getLocation(),
3418 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3419 // Find the first declaration of the parameter.
3420 // FIXME: Should we build redeclaration chains for function parameters?
3421 const FunctionDecl *FirstFD =
3422 cast<FunctionDecl>(Val: oldDecl->getDeclContext())->getFirstDecl();
3423 const ParmVarDecl *FirstVD =
3424 FirstFD->getParamDecl(i: oldDecl->getFunctionScopeIndex());
3425 S.Diag(Loc: FirstVD->getLocation(),
3426 DiagID: diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3427 }
3428
3429 propagateAttributes(
3430 To: newDecl, From: oldDecl, propagator: [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3431 unsigned found = 0;
3432 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3433 // Propagate the lifetimebound attribute from parameters to the
3434 // most recent declaration. Note that this doesn't include the implicit
3435 // 'this' parameter, as the attribute is applied to the function type in
3436 // that case.
3437 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3438 return found;
3439 });
3440}
3441
3442static bool EquivalentArrayTypes(QualType Old, QualType New,
3443 const ASTContext &Ctx) {
3444
3445 auto NoSizeInfo = [&Ctx](QualType Ty) {
3446 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3447 return true;
3448 if (const auto *VAT = Ctx.getAsVariableArrayType(T: Ty))
3449 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3450 return false;
3451 };
3452
3453 // `type[]` is equivalent to `type *` and `type[*]`.
3454 if (NoSizeInfo(Old) && NoSizeInfo(New))
3455 return true;
3456
3457 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3458 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3459 const auto *OldVAT = Ctx.getAsVariableArrayType(T: Old);
3460 const auto *NewVAT = Ctx.getAsVariableArrayType(T: New);
3461 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3462 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3463 return false;
3464 return true;
3465 }
3466
3467 // Only compare size, ignore Size modifiers and CVR.
3468 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3469 return Ctx.getAsConstantArrayType(T: Old)->getSize() ==
3470 Ctx.getAsConstantArrayType(T: New)->getSize();
3471 }
3472
3473 // Don't try to compare dependent sized array
3474 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3475 return true;
3476 }
3477
3478 return Old == New;
3479}
3480
3481static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3482 const ParmVarDecl *OldParam,
3483 Sema &S) {
3484 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3485 if (auto Newnullability = NewParam->getType()->getNullability()) {
3486 if (*Oldnullability != *Newnullability) {
3487 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_mismatched_nullability_attr)
3488 << DiagNullabilityKind(
3489 *Newnullability,
3490 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3491 != 0))
3492 << DiagNullabilityKind(
3493 *Oldnullability,
3494 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3495 != 0));
3496 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration);
3497 }
3498 } else {
3499 QualType NewT = NewParam->getType();
3500 NewT = S.Context.getAttributedType(nullability: *Oldnullability, modifiedType: NewT, equivalentType: NewT);
3501 NewParam->setType(NewT);
3502 }
3503 }
3504 const auto *OldParamDT = dyn_cast<DecayedType>(Val: OldParam->getType());
3505 const auto *NewParamDT = dyn_cast<DecayedType>(Val: NewParam->getType());
3506 if (OldParamDT && NewParamDT &&
3507 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3508 QualType OldParamOT = OldParamDT->getOriginalType();
3509 QualType NewParamOT = NewParamDT->getOriginalType();
3510 if (!EquivalentArrayTypes(Old: OldParamOT, New: NewParamOT, Ctx: S.getASTContext())) {
3511 S.Diag(Loc: NewParam->getLocation(), DiagID: diag::warn_inconsistent_array_form)
3512 << NewParam << NewParamOT;
3513 S.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
3514 << OldParamOT;
3515 }
3516 }
3517}
3518
3519namespace {
3520
3521/// Used in MergeFunctionDecl to keep track of function parameters in
3522/// C.
3523struct GNUCompatibleParamWarning {
3524 ParmVarDecl *OldParm;
3525 ParmVarDecl *NewParm;
3526 QualType PromotedType;
3527};
3528
3529} // end anonymous namespace
3530
3531// Determine whether the previous declaration was a definition, implicit
3532// declaration, or a declaration.
3533template <typename T>
3534static std::pair<diag::kind, SourceLocation>
3535getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3536 diag::kind PrevDiag;
3537 SourceLocation OldLocation = Old->getLocation();
3538 if (Old->isThisDeclarationADefinition())
3539 PrevDiag = diag::note_previous_definition;
3540 else if (Old->isImplicit()) {
3541 PrevDiag = diag::note_previous_implicit_declaration;
3542 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3543 if (FD->getBuiltinID())
3544 PrevDiag = diag::note_previous_builtin_declaration;
3545 }
3546 if (OldLocation.isInvalid())
3547 OldLocation = New->getLocation();
3548 } else
3549 PrevDiag = diag::note_previous_declaration;
3550 return std::make_pair(x&: PrevDiag, y&: OldLocation);
3551}
3552
3553/// canRedefineFunction - checks if a function can be redefined. Currently,
3554/// only extern inline functions can be redefined, and even then only in
3555/// GNU89 mode.
3556static bool canRedefineFunction(const FunctionDecl *FD,
3557 const LangOptions& LangOpts) {
3558 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3559 !LangOpts.CPlusPlus &&
3560 FD->isInlineSpecified() &&
3561 FD->getStorageClass() == SC_Extern);
3562}
3563
3564const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3565 const AttributedType *AT = T->getAs<AttributedType>();
3566 while (AT && !AT->isCallingConv())
3567 AT = AT->getModifiedType()->getAs<AttributedType>();
3568 return AT;
3569}
3570
3571template <typename T>
3572static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3573 const DeclContext *DC = Old->getDeclContext();
3574 if (DC->isRecord())
3575 return false;
3576
3577 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3578 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3579 return true;
3580 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3581 return true;
3582 return false;
3583}
3584
3585template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3586static bool isExternC(VarTemplateDecl *) { return false; }
3587static bool isExternC(FunctionTemplateDecl *) { return false; }
3588
3589/// Check whether a redeclaration of an entity introduced by a
3590/// using-declaration is valid, given that we know it's not an overload
3591/// (nor a hidden tag declaration).
3592template<typename ExpectedDecl>
3593static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3594 ExpectedDecl *New) {
3595 // C++11 [basic.scope.declarative]p4:
3596 // Given a set of declarations in a single declarative region, each of
3597 // which specifies the same unqualified name,
3598 // -- they shall all refer to the same entity, or all refer to functions
3599 // and function templates; or
3600 // -- exactly one declaration shall declare a class name or enumeration
3601 // name that is not a typedef name and the other declarations shall all
3602 // refer to the same variable or enumerator, or all refer to functions
3603 // and function templates; in this case the class name or enumeration
3604 // name is hidden (3.3.10).
3605
3606 // C++11 [namespace.udecl]p14:
3607 // If a function declaration in namespace scope or block scope has the
3608 // same name and the same parameter-type-list as a function introduced
3609 // by a using-declaration, and the declarations do not declare the same
3610 // function, the program is ill-formed.
3611
3612 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3613 if (Old &&
3614 !Old->getDeclContext()->getRedeclContext()->Equals(
3615 New->getDeclContext()->getRedeclContext()) &&
3616 !(isExternC(Old) && isExternC(New)))
3617 Old = nullptr;
3618
3619 if (!Old) {
3620 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3621 S.Diag(Loc: OldS->getTargetDecl()->getLocation(), DiagID: diag::note_using_decl_target);
3622 S.Diag(Loc: OldS->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
3623 return true;
3624 }
3625 return false;
3626}
3627
3628static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3629 const FunctionDecl *B) {
3630 assert(A->getNumParams() == B->getNumParams());
3631
3632 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3633 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3634 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3635 if (AttrA == AttrB)
3636 return true;
3637 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3638 AttrA->isDynamic() == AttrB->isDynamic();
3639 };
3640
3641 return std::equal(first1: A->param_begin(), last1: A->param_end(), first2: B->param_begin(), binary_pred: AttrEq);
3642}
3643
3644/// If necessary, adjust the semantic declaration context for a qualified
3645/// declaration to name the correct inline namespace within the qualifier.
3646static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3647 DeclaratorDecl *OldD) {
3648 // The only case where we need to update the DeclContext is when
3649 // redeclaration lookup for a qualified name finds a declaration
3650 // in an inline namespace within the context named by the qualifier:
3651 //
3652 // inline namespace N { int f(); }
3653 // int ::f(); // Sema DC needs adjusting from :: to N::.
3654 //
3655 // For unqualified declarations, the semantic context *can* change
3656 // along the redeclaration chain (for local extern declarations,
3657 // extern "C" declarations, and friend declarations in particular).
3658 if (!NewD->getQualifier())
3659 return;
3660
3661 // NewD is probably already in the right context.
3662 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3663 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3664 if (NamedDC->Equals(DC: SemaDC))
3665 return;
3666
3667 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3668 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3669 "unexpected context for redeclaration");
3670
3671 auto *LexDC = NewD->getLexicalDeclContext();
3672 auto FixSemaDC = [=](NamedDecl *D) {
3673 if (!D)
3674 return;
3675 D->setDeclContext(SemaDC);
3676 D->setLexicalDeclContext(LexDC);
3677 };
3678
3679 FixSemaDC(NewD);
3680 if (auto *FD = dyn_cast<FunctionDecl>(Val: NewD))
3681 FixSemaDC(FD->getDescribedFunctionTemplate());
3682 else if (auto *VD = dyn_cast<VarDecl>(Val: NewD))
3683 FixSemaDC(VD->getDescribedVarTemplate());
3684}
3685
3686bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3687 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3688 // Verify the old decl was also a function.
3689 FunctionDecl *Old = OldD->getAsFunction();
3690 if (!Old) {
3691 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: OldD)) {
3692 // We don't need to check the using friend pattern from other module unit
3693 // since we should have diagnosed such cases in its unit already.
3694 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3695 Diag(Loc: New->getLocation(), DiagID: diag::err_using_decl_friend);
3696 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
3697 DiagID: diag::note_using_decl_target);
3698 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
3699 << 0;
3700 return true;
3701 }
3702
3703 // Check whether the two declarations might declare the same function or
3704 // function template.
3705 if (FunctionTemplateDecl *NewTemplate =
3706 New->getDescribedFunctionTemplate()) {
3707 if (checkUsingShadowRedecl<FunctionTemplateDecl>(S&: *this, OldS: Shadow,
3708 New: NewTemplate))
3709 return true;
3710 OldD = Old = cast<FunctionTemplateDecl>(Val: Shadow->getTargetDecl())
3711 ->getAsFunction();
3712 } else {
3713 if (checkUsingShadowRedecl<FunctionDecl>(S&: *this, OldS: Shadow, New))
3714 return true;
3715 OldD = Old = cast<FunctionDecl>(Val: Shadow->getTargetDecl());
3716 }
3717 } else {
3718 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
3719 << New->getDeclName();
3720 notePreviousDefinition(Old: OldD, New: New->getLocation());
3721 return true;
3722 }
3723 }
3724
3725 // If the old declaration was found in an inline namespace and the new
3726 // declaration was qualified, update the DeclContext to match.
3727 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
3728
3729 // If the old declaration is invalid, just give up here.
3730 if (Old->isInvalidDecl())
3731 return true;
3732
3733 // Disallow redeclaration of some builtins.
3734 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3735 Diag(Loc: New->getLocation(), DiagID: diag::err_builtin_redeclare) << Old->getDeclName();
3736 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_builtin_declaration)
3737 << Old << Old->getType();
3738 return true;
3739 }
3740
3741 diag::kind PrevDiag;
3742 SourceLocation OldLocation;
3743 std::tie(args&: PrevDiag, args&: OldLocation) =
3744 getNoteDiagForInvalidRedeclaration(Old, New);
3745
3746 // Don't complain about this if we're in GNU89 mode and the old function
3747 // is an extern inline function.
3748 // Don't complain about specializations. They are not supposed to have
3749 // storage classes.
3750 if (!isa<CXXMethodDecl>(Val: New) && !isa<CXXMethodDecl>(Val: Old) &&
3751 New->getStorageClass() == SC_Static &&
3752 Old->hasExternalFormalLinkage() &&
3753 !New->getTemplateSpecializationInfo() &&
3754 !canRedefineFunction(FD: Old, LangOpts: getLangOpts())) {
3755 if (getLangOpts().MicrosoftExt) {
3756 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static) << New;
3757 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3758 } else {
3759 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static) << New;
3760 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3761 return true;
3762 }
3763 }
3764
3765 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3766 if (!Old->hasAttr<InternalLinkageAttr>()) {
3767 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
3768 << ILA;
3769 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3770 New->dropAttr<InternalLinkageAttr>();
3771 }
3772
3773 if (auto *EA = New->getAttr<ErrorAttr>()) {
3774 if (!Old->hasAttr<ErrorAttr>()) {
3775 Diag(Loc: EA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl) << EA;
3776 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3777 New->dropAttr<ErrorAttr>();
3778 }
3779 }
3780
3781 if (CheckRedeclarationInModule(New, Old))
3782 return true;
3783
3784 if (!getLangOpts().CPlusPlus) {
3785 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3786 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3787 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_overloadable_mismatch)
3788 << New << OldOvl;
3789
3790 // Try our best to find a decl that actually has the overloadable
3791 // attribute for the note. In most cases (e.g. programs with only one
3792 // broken declaration/definition), this won't matter.
3793 //
3794 // FIXME: We could do this if we juggled some extra state in
3795 // OverloadableAttr, rather than just removing it.
3796 const Decl *DiagOld = Old;
3797 if (OldOvl) {
3798 auto OldIter = llvm::find_if(Range: Old->redecls(), P: [](const Decl *D) {
3799 const auto *A = D->getAttr<OverloadableAttr>();
3800 return A && !A->isImplicit();
3801 });
3802 // If we've implicitly added *all* of the overloadable attrs to this
3803 // chain, emitting a "previous redecl" note is pointless.
3804 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3805 }
3806
3807 if (DiagOld)
3808 Diag(Loc: DiagOld->getLocation(),
3809 DiagID: diag::note_attribute_overloadable_prev_overload)
3810 << OldOvl;
3811
3812 if (OldOvl)
3813 New->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
3814 else
3815 New->dropAttr<OverloadableAttr>();
3816 }
3817 }
3818
3819 // It is not permitted to redeclare an SME function with different SME
3820 // attributes.
3821 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
3822 Diag(Loc: New->getLocation(), DiagID: diag::err_sme_attr_mismatch)
3823 << New->getType() << Old->getType();
3824 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3825 return true;
3826 }
3827
3828 // If a function is first declared with a calling convention, but is later
3829 // declared or defined without one, all following decls assume the calling
3830 // convention of the first.
3831 //
3832 // It's OK if a function is first declared without a calling convention,
3833 // but is later declared or defined with the default calling convention.
3834 //
3835 // To test if either decl has an explicit calling convention, we look for
3836 // AttributedType sugar nodes on the type as written. If they are missing or
3837 // were canonicalized away, we assume the calling convention was implicit.
3838 //
3839 // Note also that we DO NOT return at this point, because we still have
3840 // other tests to run.
3841 QualType OldQType = Context.getCanonicalType(T: Old->getType());
3842 QualType NewQType = Context.getCanonicalType(T: New->getType());
3843 const FunctionType *OldType = cast<FunctionType>(Val&: OldQType);
3844 const FunctionType *NewType = cast<FunctionType>(Val&: NewQType);
3845 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3846 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3847 bool RequiresAdjustment = false;
3848
3849 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3850 FunctionDecl *First = Old->getFirstDecl();
3851 const FunctionType *FT =
3852 First->getType().getCanonicalType()->castAs<FunctionType>();
3853 FunctionType::ExtInfo FI = FT->getExtInfo();
3854 bool NewCCExplicit = getCallingConvAttributedType(T: New->getType());
3855 if (!NewCCExplicit) {
3856 // Inherit the CC from the previous declaration if it was specified
3857 // there but not here.
3858 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3859 RequiresAdjustment = true;
3860 } else if (Old->getBuiltinID()) {
3861 // Builtin attribute isn't propagated to the new one yet at this point,
3862 // so we check if the old one is a builtin.
3863
3864 // Calling Conventions on a Builtin aren't really useful and setting a
3865 // default calling convention and cdecl'ing some builtin redeclarations is
3866 // common, so warn and ignore the calling convention on the redeclaration.
3867 Diag(Loc: New->getLocation(), DiagID: diag::warn_cconv_unsupported)
3868 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3869 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3870 NewTypeInfo = NewTypeInfo.withCallingConv(cc: OldTypeInfo.getCC());
3871 RequiresAdjustment = true;
3872 } else {
3873 // Calling conventions aren't compatible, so complain.
3874 bool FirstCCExplicit = getCallingConvAttributedType(T: First->getType());
3875 Diag(Loc: New->getLocation(), DiagID: diag::err_cconv_change)
3876 << FunctionType::getNameForCallConv(CC: NewTypeInfo.getCC())
3877 << !FirstCCExplicit
3878 << (!FirstCCExplicit ? "" :
3879 FunctionType::getNameForCallConv(CC: FI.getCC()));
3880
3881 // Put the note on the first decl, since it is the one that matters.
3882 Diag(Loc: First->getLocation(), DiagID: diag::note_previous_declaration);
3883 return true;
3884 }
3885 }
3886
3887 // FIXME: diagnose the other way around?
3888 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3889 NewTypeInfo = NewTypeInfo.withNoReturn(noReturn: true);
3890 RequiresAdjustment = true;
3891 }
3892
3893 // If the declaration is marked with cfi_unchecked_callee but the definition
3894 // isn't, the definition is also cfi_unchecked_callee.
3895 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3896 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3897 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3898 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3899
3900 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3901 EPI2.CFIUncheckedCallee = true;
3902 NewQType = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
3903 Args: FPT2->getParamTypes(), EPI: EPI2);
3904 NewType = cast<FunctionType>(Val&: NewQType);
3905 New->setType(NewQType);
3906 }
3907 }
3908 }
3909
3910 // Merge regparm attribute.
3911 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3912 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3913 if (NewTypeInfo.getHasRegParm()) {
3914 Diag(Loc: New->getLocation(), DiagID: diag::err_regparm_mismatch)
3915 << NewType->getRegParmType()
3916 << OldType->getRegParmType();
3917 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3918 return true;
3919 }
3920
3921 NewTypeInfo = NewTypeInfo.withRegParm(RegParm: OldTypeInfo.getRegParm());
3922 RequiresAdjustment = true;
3923 }
3924
3925 // Merge ns_returns_retained attribute.
3926 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3927 if (NewTypeInfo.getProducesResult()) {
3928 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch)
3929 << "'ns_returns_retained'";
3930 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3931 return true;
3932 }
3933
3934 NewTypeInfo = NewTypeInfo.withProducesResult(producesResult: true);
3935 RequiresAdjustment = true;
3936 }
3937
3938 if (OldTypeInfo.getNoCallerSavedRegs() !=
3939 NewTypeInfo.getNoCallerSavedRegs()) {
3940 if (NewTypeInfo.getNoCallerSavedRegs()) {
3941 AnyX86NoCallerSavedRegistersAttr *Attr =
3942 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3943 Diag(Loc: New->getLocation(), DiagID: diag::err_function_attribute_mismatch) << Attr;
3944 Diag(Loc: OldLocation, DiagID: diag::note_previous_declaration);
3945 return true;
3946 }
3947
3948 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(noCallerSavedRegs: true);
3949 RequiresAdjustment = true;
3950 }
3951
3952 if (RequiresAdjustment) {
3953 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3954 AdjustedType = Context.adjustFunctionType(Fn: AdjustedType, EInfo: NewTypeInfo);
3955 New->setType(QualType(AdjustedType, 0));
3956 NewQType = Context.getCanonicalType(T: New->getType());
3957 }
3958
3959 // If this redeclaration makes the function inline, we may need to add it to
3960 // UndefinedButUsed.
3961 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3962 !getLangOpts().GNUInline && Old->isUsed(CheckUsedAttr: false) && !Old->isDefined() &&
3963 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3964 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
3965 y: SourceLocation()));
3966
3967 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3968 // about it.
3969 if (New->hasAttr<GNUInlineAttr>() &&
3970 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3971 UndefinedButUsed.erase(Key: Old->getCanonicalDecl());
3972 }
3973
3974 // If pass_object_size params don't match up perfectly, this isn't a valid
3975 // redeclaration.
3976 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3977 !hasIdenticalPassObjectSizeAttrs(A: Old, B: New)) {
3978 Diag(Loc: New->getLocation(), DiagID: diag::err_different_pass_object_size_params)
3979 << New->getDeclName();
3980 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
3981 return true;
3982 }
3983
3984 QualType OldQTypeForComparison = OldQType;
3985 if (Context.hasAnyFunctionEffects()) {
3986 const auto OldFX = Old->getFunctionEffects();
3987 const auto NewFX = New->getFunctionEffects();
3988 if (OldFX != NewFX) {
3989 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3990 for (const auto &Diff : Diffs) {
3991 if (Diff.shouldDiagnoseRedeclaration(OldFunction: *Old, OldFX, NewFunction: *New, NewFX)) {
3992 Diag(Loc: New->getLocation(),
3993 DiagID: diag::warn_mismatched_func_effect_redeclaration)
3994 << Diff.effectName();
3995 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
3996 }
3997 }
3998 // Following a warning, we could skip merging effects from the previous
3999 // declaration, but that would trigger an additional "conflicting types"
4000 // error.
4001 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4002 FunctionEffectSet::Conflicts MergeErrs;
4003 FunctionEffectSet MergedFX =
4004 FunctionEffectSet::getUnion(LHS: OldFX, RHS: NewFX, Errs&: MergeErrs);
4005 if (!MergeErrs.empty())
4006 diagnoseFunctionEffectMergeConflicts(Errs: MergeErrs, NewLoc: New->getLocation(),
4007 OldLoc: Old->getLocation());
4008
4009 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4010 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4011 QualType ModQT = Context.getFunctionType(ResultTy: NewFPT->getReturnType(),
4012 Args: NewFPT->getParamTypes(), EPI);
4013
4014 New->setType(ModQT);
4015 NewQType = New->getType();
4016
4017 // Revise OldQTForComparison to include the merged effects,
4018 // so as not to fail due to differences later.
4019 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4020 EPI = OldFPT->getExtProtoInfo();
4021 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4022 OldQTypeForComparison = Context.getFunctionType(
4023 ResultTy: OldFPT->getReturnType(), Args: OldFPT->getParamTypes(), EPI);
4024 }
4025 if (OldFX.empty()) {
4026 // A redeclaration may add the attribute to a previously seen function
4027 // body which needs to be verified.
4028 maybeAddDeclWithEffects(D: Old, FX: MergedFX);
4029 }
4030 }
4031 }
4032 }
4033
4034 if (getLangOpts().CPlusPlus) {
4035 OldQType = Context.getCanonicalType(T: Old->getType());
4036 NewQType = Context.getCanonicalType(T: New->getType());
4037
4038 // Go back to the type source info to compare the declared return types,
4039 // per C++1y [dcl.type.auto]p13:
4040 // Redeclarations or specializations of a function or function template
4041 // with a declared return type that uses a placeholder type shall also
4042 // use that placeholder, not a deduced type.
4043 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4044 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4045 if (!Context.hasSameType(T1: OldDeclaredReturnType, T2: NewDeclaredReturnType) &&
4046 canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewDeclaredReturnType,
4047 OldT: OldDeclaredReturnType)) {
4048 QualType ResQT;
4049 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4050 OldDeclaredReturnType->isObjCObjectPointerType())
4051 // FIXME: This does the wrong thing for a deduced return type.
4052 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4053 if (ResQT.isNull()) {
4054 if (New->isCXXClassMember() && New->isOutOfLine())
4055 Diag(Loc: New->getLocation(), DiagID: diag::err_member_def_does_not_match_ret_type)
4056 << New << New->getReturnTypeSourceRange();
4057 else if (Old->isExternC() && New->isExternC() &&
4058 !Old->hasAttr<OverloadableAttr>() &&
4059 !New->hasAttr<OverloadableAttr>())
4060 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4061 else
4062 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_diff_return_type)
4063 << New->getReturnTypeSourceRange();
4064 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType()
4065 << Old->getReturnTypeSourceRange();
4066 return true;
4067 }
4068 else
4069 NewQType = ResQT;
4070 }
4071
4072 QualType OldReturnType = OldType->getReturnType();
4073 QualType NewReturnType = cast<FunctionType>(Val&: NewQType)->getReturnType();
4074 if (OldReturnType != NewReturnType) {
4075 // If this function has a deduced return type and has already been
4076 // defined, copy the deduced value from the old declaration.
4077 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4078 if (OldAT && OldAT->isDeduced()) {
4079 QualType DT = OldAT->getDeducedType();
4080 if (DT.isNull()) {
4081 New->setType(SubstAutoTypeDependent(TypeWithAuto: New->getType()));
4082 NewQType = Context.getCanonicalType(T: SubstAutoTypeDependent(TypeWithAuto: NewQType));
4083 } else {
4084 New->setType(SubstAutoType(TypeWithAuto: New->getType(), Replacement: DT));
4085 NewQType = Context.getCanonicalType(T: SubstAutoType(TypeWithAuto: NewQType, Replacement: DT));
4086 }
4087 }
4088 }
4089
4090 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
4091 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
4092 if (OldMethod && NewMethod) {
4093 // Preserve triviality.
4094 NewMethod->setTrivial(OldMethod->isTrivial());
4095
4096 // MSVC allows explicit template specialization at class scope:
4097 // 2 CXXMethodDecls referring to the same function will be injected.
4098 // We don't want a redeclaration error.
4099 bool IsClassScopeExplicitSpecialization =
4100 OldMethod->isFunctionTemplateSpecialization() &&
4101 NewMethod->isFunctionTemplateSpecialization();
4102 bool isFriend = NewMethod->getFriendObjectKind();
4103
4104 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4105 !IsClassScopeExplicitSpecialization) {
4106 // -- Member function declarations with the same name and the
4107 // same parameter types cannot be overloaded if any of them
4108 // is a static member function declaration.
4109 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4110 Diag(Loc: New->getLocation(), DiagID: diag::err_ovl_static_nonstatic_member);
4111 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4112 return true;
4113 }
4114
4115 // C++ [class.mem]p1:
4116 // [...] A member shall not be declared twice in the
4117 // member-specification, except that a nested class or member
4118 // class template can be declared and then later defined.
4119 if (!inTemplateInstantiation()) {
4120 unsigned NewDiag;
4121 if (isa<CXXConstructorDecl>(Val: OldMethod))
4122 NewDiag = diag::err_constructor_redeclared;
4123 else if (isa<CXXDestructorDecl>(Val: NewMethod))
4124 NewDiag = diag::err_destructor_redeclared;
4125 else if (isa<CXXConversionDecl>(Val: NewMethod))
4126 NewDiag = diag::err_conv_function_redeclared;
4127 else
4128 NewDiag = diag::err_member_redeclared;
4129
4130 Diag(Loc: New->getLocation(), DiagID: NewDiag);
4131 } else {
4132 Diag(Loc: New->getLocation(), DiagID: diag::err_member_redeclared_in_instantiation)
4133 << New << New->getType();
4134 }
4135 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4136 return true;
4137
4138 // Complain if this is an explicit declaration of a special
4139 // member that was initially declared implicitly.
4140 //
4141 // As an exception, it's okay to befriend such methods in order
4142 // to permit the implicit constructor/destructor/operator calls.
4143 } else if (OldMethod->isImplicit()) {
4144 if (isFriend) {
4145 NewMethod->setImplicit();
4146 } else {
4147 Diag(Loc: NewMethod->getLocation(),
4148 DiagID: diag::err_definition_of_implicitly_declared_member)
4149 << New << getSpecialMember(MD: OldMethod);
4150 return true;
4151 }
4152 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4153 Diag(Loc: NewMethod->getLocation(),
4154 DiagID: diag::err_definition_of_explicitly_defaulted_member)
4155 << getSpecialMember(MD: OldMethod);
4156 return true;
4157 }
4158 }
4159
4160 // C++1z [over.load]p2
4161 // Certain function declarations cannot be overloaded:
4162 // -- Function declarations that differ only in the return type,
4163 // the exception specification, or both cannot be overloaded.
4164
4165 // Check the exception specifications match. This may recompute the type of
4166 // both Old and New if it resolved exception specifications, so grab the
4167 // types again after this. Because this updates the type, we do this before
4168 // any of the other checks below, which may update the "de facto" NewQType
4169 // but do not necessarily update the type of New.
4170 if (CheckEquivalentExceptionSpec(Old, New))
4171 return true;
4172
4173 // C++11 [dcl.attr.noreturn]p1:
4174 // The first declaration of a function shall specify the noreturn
4175 // attribute if any declaration of that function specifies the noreturn
4176 // attribute.
4177 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4178 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4179 Diag(Loc: NRA->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4180 << NRA;
4181 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4182 }
4183
4184 // C++11 [dcl.attr.depend]p2:
4185 // The first declaration of a function shall specify the
4186 // carries_dependency attribute for its declarator-id if any declaration
4187 // of the function specifies the carries_dependency attribute.
4188 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4189 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4190 Diag(Loc: CDA->getLocation(),
4191 DiagID: diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4192 Diag(Loc: Old->getFirstDecl()->getLocation(),
4193 DiagID: diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4194 }
4195
4196 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4197 // When a function is declared with SYCL_EXTERNAL, that macro must be
4198 // used on the first declaration of that function in the translation unit.
4199 // Redeclarations of the function in the same translation unit may
4200 // optionally use SYCL_EXTERNAL, but this is not required.
4201 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4202 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4203 Diag(Loc: SEA->getLocation(), DiagID: diag::warn_sycl_external_missing_on_first_decl)
4204 << SEA;
4205 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4206 }
4207
4208 // (C++98 8.3.5p3):
4209 // All declarations for a function shall agree exactly in both the
4210 // return type and the parameter-type-list.
4211 // We also want to respect all the extended bits except noreturn.
4212
4213 // noreturn should now match unless the old type info didn't have it.
4214 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4215 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4216 const FunctionType *OldTypeForComparison
4217 = Context.adjustFunctionType(Fn: OldType, EInfo: OldTypeInfo.withNoReturn(noReturn: true));
4218 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4219 assert(OldQTypeForComparison.isCanonical());
4220 }
4221
4222 if (haveIncompatibleLanguageLinkages(Old, New)) {
4223 // As a special case, retain the language linkage from previous
4224 // declarations of a friend function as an extension.
4225 //
4226 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4227 // and is useful because there's otherwise no way to specify language
4228 // linkage within class scope.
4229 //
4230 // Check cautiously as the friend object kind isn't yet complete.
4231 if (New->getFriendObjectKind() != Decl::FOK_None) {
4232 Diag(Loc: New->getLocation(), DiagID: diag::ext_retained_language_linkage) << New;
4233 Diag(Loc: OldLocation, DiagID: PrevDiag);
4234 } else {
4235 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4236 Diag(Loc: OldLocation, DiagID: PrevDiag);
4237 return true;
4238 }
4239 }
4240
4241 // HLSL check parameters for matching ABI specifications.
4242 if (getLangOpts().HLSL) {
4243 if (HLSL().CheckCompatibleParameterABI(New, Old))
4244 return true;
4245
4246 // If no errors are generated when checking parameter ABIs we can check if
4247 // the two declarations have the same type ignoring the ABIs and if so,
4248 // the declarations can be merged. This case for merging is only valid in
4249 // HLSL because there are no valid cases of merging mismatched parameter
4250 // ABIs except the HLSL implicit in and explicit in.
4251 if (Context.hasSameFunctionTypeIgnoringParamABI(T: OldQTypeForComparison,
4252 U: NewQType))
4253 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4254 // Fall through for conflicting redeclarations and redefinitions.
4255 }
4256
4257 // If the function types are compatible, merge the declarations. Ignore the
4258 // exception specifier because it was already checked above in
4259 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4260 // about incompatible types under -fms-compatibility.
4261 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(T: OldQTypeForComparison,
4262 U: NewQType))
4263 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4264
4265 // If the types are imprecise (due to dependent constructs in friends or
4266 // local extern declarations), it's OK if they differ. We'll check again
4267 // during instantiation.
4268 if (!canFullyTypeCheckRedeclaration(NewD: New, OldD: Old, NewT: NewQType, OldT: OldQType))
4269 return false;
4270
4271 // Fall through for conflicting redeclarations and redefinitions.
4272 }
4273
4274 // C: Function types need to be compatible, not identical. This handles
4275 // duplicate function decls like "void f(int); void f(enum X);" properly.
4276 if (!getLangOpts().CPlusPlus) {
4277 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4278 // type is specified by a function definition that contains a (possibly
4279 // empty) identifier list, both shall agree in the number of parameters
4280 // and the type of each parameter shall be compatible with the type that
4281 // results from the application of default argument promotions to the
4282 // type of the corresponding identifier. ...
4283 // This cannot be handled by ASTContext::typesAreCompatible() because that
4284 // doesn't know whether the function type is for a definition or not when
4285 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4286 // we need to cover here is that the number of arguments agree as the
4287 // default argument promotion rules were already checked by
4288 // ASTContext::typesAreCompatible().
4289 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4290 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4291 if (Old->hasInheritedPrototype())
4292 Old = Old->getCanonicalDecl();
4293 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New;
4294 Diag(Loc: Old->getLocation(), DiagID: PrevDiag) << Old << Old->getType();
4295 return true;
4296 }
4297
4298 // If we are merging two functions where only one of them has a prototype,
4299 // we may have enough information to decide to issue a diagnostic that the
4300 // function without a prototype will change behavior in C23. This handles
4301 // cases like:
4302 // void i(); void i(int j);
4303 // void i(int j); void i();
4304 // void i(); void i(int j) {}
4305 // See ActOnFinishFunctionBody() for other cases of the behavior change
4306 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4307 // type without a prototype.
4308 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4309 !New->isImplicit() && !Old->isImplicit()) {
4310 const FunctionDecl *WithProto, *WithoutProto;
4311 if (New->hasWrittenPrototype()) {
4312 WithProto = New;
4313 WithoutProto = Old;
4314 } else {
4315 WithProto = Old;
4316 WithoutProto = New;
4317 }
4318
4319 if (WithProto->getNumParams() != 0) {
4320 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4321 // The one without the prototype will be changing behavior in C23, so
4322 // warn about that one so long as it's a user-visible declaration.
4323 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4324 if (WithoutProto == New)
4325 IsWithoutProtoADef = NewDeclIsDefn;
4326 else
4327 IsWithProtoADef = NewDeclIsDefn;
4328 Diag(Loc: WithoutProto->getLocation(),
4329 DiagID: diag::warn_non_prototype_changes_behavior)
4330 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4331 << (WithoutProto == Old) << IsWithProtoADef;
4332
4333 // The reason the one without the prototype will be changing behavior
4334 // is because of the one with the prototype, so note that so long as
4335 // it's a user-visible declaration. There is one exception to this:
4336 // when the new declaration is a definition without a prototype, the
4337 // old declaration with a prototype is not the cause of the issue,
4338 // and that does not need to be noted because the one with a
4339 // prototype will not change behavior in C23.
4340 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4341 !IsWithoutProtoADef)
4342 Diag(Loc: WithProto->getLocation(), DiagID: diag::note_conflicting_prototype);
4343 }
4344 }
4345 }
4346
4347 if (Context.typesAreCompatible(T1: OldQType, T2: NewQType)) {
4348 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4349 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4350 const FunctionProtoType *OldProto = nullptr;
4351 if (MergeTypeWithOld && isa<FunctionNoProtoType>(Val: NewFuncType) &&
4352 (OldProto = dyn_cast<FunctionProtoType>(Val: OldFuncType))) {
4353 // The old declaration provided a function prototype, but the
4354 // new declaration does not. Merge in the prototype.
4355 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4356 NewQType = Context.getFunctionType(ResultTy: NewFuncType->getReturnType(),
4357 Args: OldProto->getParamTypes(),
4358 EPI: OldProto->getExtProtoInfo());
4359 New->setType(NewQType);
4360 New->setHasInheritedPrototype();
4361
4362 // Synthesize parameters with the same types.
4363 SmallVector<ParmVarDecl *, 16> Params;
4364 for (const auto &ParamType : OldProto->param_types()) {
4365 ParmVarDecl *Param = ParmVarDecl::Create(
4366 C&: Context, DC: New, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr,
4367 T: ParamType, /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr);
4368 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
4369 Param->setImplicit();
4370 Params.push_back(Elt: Param);
4371 }
4372
4373 New->setParams(Params);
4374 }
4375
4376 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4377 }
4378 }
4379
4380 // Check if the function types are compatible when pointer size address
4381 // spaces are ignored.
4382 if (Context.hasSameFunctionTypeIgnoringPtrSizes(T: OldQType, U: NewQType))
4383 return false;
4384
4385 // GNU C permits a K&R definition to follow a prototype declaration
4386 // if the declared types of the parameters in the K&R definition
4387 // match the types in the prototype declaration, even when the
4388 // promoted types of the parameters from the K&R definition differ
4389 // from the types in the prototype. GCC then keeps the types from
4390 // the prototype.
4391 //
4392 // If a variadic prototype is followed by a non-variadic K&R definition,
4393 // the K&R definition becomes variadic. This is sort of an edge case, but
4394 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4395 // C99 6.9.1p8.
4396 if (!getLangOpts().CPlusPlus &&
4397 Old->hasPrototype() && !New->hasPrototype() &&
4398 New->getType()->getAs<FunctionProtoType>() &&
4399 Old->getNumParams() == New->getNumParams()) {
4400 SmallVector<QualType, 16> ArgTypes;
4401 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4402 const FunctionProtoType *OldProto
4403 = Old->getType()->getAs<FunctionProtoType>();
4404 const FunctionProtoType *NewProto
4405 = New->getType()->getAs<FunctionProtoType>();
4406
4407 // Determine whether this is the GNU C extension.
4408 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4409 NewProto->getReturnType());
4410 bool LooseCompatible = !MergedReturn.isNull();
4411 for (unsigned Idx = 0, End = Old->getNumParams();
4412 LooseCompatible && Idx != End; ++Idx) {
4413 ParmVarDecl *OldParm = Old->getParamDecl(i: Idx);
4414 ParmVarDecl *NewParm = New->getParamDecl(i: Idx);
4415 if (Context.typesAreCompatible(T1: OldParm->getType(),
4416 T2: NewProto->getParamType(i: Idx))) {
4417 ArgTypes.push_back(Elt: NewParm->getType());
4418 } else if (Context.typesAreCompatible(T1: OldParm->getType(),
4419 T2: NewParm->getType(),
4420 /*CompareUnqualified=*/true)) {
4421 GNUCompatibleParamWarning Warn = { .OldParm: OldParm, .NewParm: NewParm,
4422 .PromotedType: NewProto->getParamType(i: Idx) };
4423 Warnings.push_back(Elt: Warn);
4424 ArgTypes.push_back(Elt: NewParm->getType());
4425 } else
4426 LooseCompatible = false;
4427 }
4428
4429 if (LooseCompatible) {
4430 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4431 Diag(Loc: Warnings[Warn].NewParm->getLocation(),
4432 DiagID: diag::ext_param_promoted_not_compatible_with_prototype)
4433 << Warnings[Warn].PromotedType
4434 << Warnings[Warn].OldParm->getType();
4435 if (Warnings[Warn].OldParm->getLocation().isValid())
4436 Diag(Loc: Warnings[Warn].OldParm->getLocation(),
4437 DiagID: diag::note_previous_declaration);
4438 }
4439
4440 if (MergeTypeWithOld)
4441 New->setType(Context.getFunctionType(ResultTy: MergedReturn, Args: ArgTypes,
4442 EPI: OldProto->getExtProtoInfo()));
4443 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4444 }
4445
4446 // Fall through to diagnose conflicting types.
4447 }
4448
4449 // A function that has already been declared has been redeclared or
4450 // defined with a different type; show an appropriate diagnostic.
4451
4452 // If the previous declaration was an implicitly-generated builtin
4453 // declaration, then at the very least we should use a specialized note.
4454 unsigned BuiltinID;
4455 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4456 // If it's actually a library-defined builtin function like 'malloc'
4457 // or 'printf', just warn about the incompatible redeclaration.
4458 if (Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID)) {
4459 Diag(Loc: New->getLocation(), DiagID: diag::warn_redecl_library_builtin) << New;
4460 Diag(Loc: OldLocation, DiagID: diag::note_previous_builtin_declaration)
4461 << Old << Old->getType();
4462 return false;
4463 }
4464
4465 PrevDiag = diag::note_previous_builtin_declaration;
4466 }
4467
4468 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_types) << New->getDeclName();
4469 Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4470 return true;
4471}
4472
4473bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4474 Scope *S, bool MergeTypeWithOld) {
4475 // Merge the attributes
4476 mergeDeclAttributes(New, Old);
4477
4478 // Merge "pure" flag.
4479 if (Old->isPureVirtual())
4480 New->setIsPureVirtual();
4481
4482 // Merge "used" flag.
4483 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4484 New->setIsUsed();
4485
4486 // Merge attributes from the parameters. These can mismatch with K&R
4487 // declarations.
4488 if (New->getNumParams() == Old->getNumParams())
4489 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4490 ParmVarDecl *NewParam = New->getParamDecl(i);
4491 ParmVarDecl *OldParam = Old->getParamDecl(i);
4492 mergeParamDeclAttributes(newDecl: NewParam, oldDecl: OldParam, S&: *this);
4493 mergeParamDeclTypes(NewParam, OldParam, S&: *this);
4494 }
4495
4496 if (getLangOpts().CPlusPlus)
4497 return MergeCXXFunctionDecl(New, Old, S);
4498
4499 // Merge the function types so the we get the composite types for the return
4500 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4501 // was visible.
4502 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4503 if (!Merged.isNull() && MergeTypeWithOld)
4504 New->setType(Merged);
4505
4506 return false;
4507}
4508
4509void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4510 ObjCMethodDecl *oldMethod) {
4511 // Merge the attributes, including deprecated/unavailable
4512 AvailabilityMergeKind MergeKind =
4513 isa<ObjCProtocolDecl>(Val: oldMethod->getDeclContext())
4514 ? (oldMethod->isOptional()
4515 ? AvailabilityMergeKind::OptionalProtocolImplementation
4516 : AvailabilityMergeKind::ProtocolImplementation)
4517 : isa<ObjCImplDecl>(Val: newMethod->getDeclContext())
4518 ? AvailabilityMergeKind::Redeclaration
4519 : AvailabilityMergeKind::Override;
4520
4521 mergeDeclAttributes(New: newMethod, Old: oldMethod, AMK: MergeKind);
4522
4523 // Merge attributes from the parameters.
4524 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4525 oe = oldMethod->param_end();
4526 for (ObjCMethodDecl::param_iterator
4527 ni = newMethod->param_begin(), ne = newMethod->param_end();
4528 ni != ne && oi != oe; ++ni, ++oi)
4529 mergeParamDeclAttributes(newDecl: *ni, oldDecl: *oi, S&: *this);
4530
4531 ObjC().CheckObjCMethodOverride(NewMethod: newMethod, Overridden: oldMethod);
4532}
4533
4534static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4535 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4536
4537 S.Diag(Loc: New->getLocation(), DiagID: New->isThisDeclarationADefinition()
4538 ? diag::err_redefinition_different_type
4539 : diag::err_redeclaration_different_type)
4540 << New->getDeclName() << New->getType() << Old->getType();
4541
4542 diag::kind PrevDiag;
4543 SourceLocation OldLocation;
4544 std::tie(args&: PrevDiag, args&: OldLocation)
4545 = getNoteDiagForInvalidRedeclaration(Old, New);
4546 S.Diag(Loc: OldLocation, DiagID: PrevDiag) << Old << Old->getType();
4547 New->setInvalidDecl();
4548}
4549
4550void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4551 bool MergeTypeWithOld) {
4552 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4553 return;
4554
4555 QualType MergedT;
4556 if (getLangOpts().CPlusPlus) {
4557 if (New->getType()->isUndeducedType()) {
4558 // We don't know what the new type is until the initializer is attached.
4559 return;
4560 } else if (Context.hasSameType(T1: New->getType(), T2: Old->getType())) {
4561 // These could still be something that needs exception specs checked.
4562 return MergeVarDeclExceptionSpecs(New, Old);
4563 }
4564 // C++ [basic.link]p10:
4565 // [...] the types specified by all declarations referring to a given
4566 // object or function shall be identical, except that declarations for an
4567 // array object can specify array types that differ by the presence or
4568 // absence of a major array bound (8.3.4).
4569 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4570 const ArrayType *OldArray = Context.getAsArrayType(T: Old->getType());
4571 const ArrayType *NewArray = Context.getAsArrayType(T: New->getType());
4572
4573 // We are merging a variable declaration New into Old. If it has an array
4574 // bound, and that bound differs from Old's bound, we should diagnose the
4575 // mismatch.
4576 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4577 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4578 PrevVD = PrevVD->getPreviousDecl()) {
4579 QualType PrevVDTy = PrevVD->getType();
4580 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4581 continue;
4582
4583 if (!Context.hasSameType(T1: New->getType(), T2: PrevVDTy))
4584 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old: PrevVD);
4585 }
4586 }
4587
4588 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4589 if (Context.hasSameType(T1: OldArray->getElementType(),
4590 T2: NewArray->getElementType()))
4591 MergedT = New->getType();
4592 }
4593 // FIXME: Check visibility. New is hidden but has a complete type. If New
4594 // has no array bound, it should not inherit one from Old, if Old is not
4595 // visible.
4596 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4597 if (Context.hasSameType(T1: OldArray->getElementType(),
4598 T2: NewArray->getElementType()))
4599 MergedT = Old->getType();
4600 }
4601 }
4602 else if (New->getType()->isObjCObjectPointerType() &&
4603 Old->getType()->isObjCObjectPointerType()) {
4604 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4605 Old->getType());
4606 }
4607 } else {
4608 // C 6.2.7p2:
4609 // All declarations that refer to the same object or function shall have
4610 // compatible type.
4611 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4612 }
4613 if (MergedT.isNull()) {
4614 // It's OK if we couldn't merge types if either type is dependent, for a
4615 // block-scope variable. In other cases (static data members of class
4616 // templates, variable templates, ...), we require the types to be
4617 // equivalent.
4618 // FIXME: The C++ standard doesn't say anything about this.
4619 if ((New->getType()->isDependentType() ||
4620 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4621 // If the old type was dependent, we can't merge with it, so the new type
4622 // becomes dependent for now. We'll reproduce the original type when we
4623 // instantiate the TypeSourceInfo for the variable.
4624 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4625 New->setType(Context.DependentTy);
4626 return;
4627 }
4628 return diagnoseVarDeclTypeMismatch(S&: *this, New, Old);
4629 }
4630
4631 // Don't actually update the type on the new declaration if the old
4632 // declaration was an extern declaration in a different scope.
4633 if (MergeTypeWithOld)
4634 New->setType(MergedT);
4635}
4636
4637static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4638 LookupResult &Previous) {
4639 // C11 6.2.7p4:
4640 // For an identifier with internal or external linkage declared
4641 // in a scope in which a prior declaration of that identifier is
4642 // visible, if the prior declaration specifies internal or
4643 // external linkage, the type of the identifier at the later
4644 // declaration becomes the composite type.
4645 //
4646 // If the variable isn't visible, we do not merge with its type.
4647 if (Previous.isShadowed())
4648 return false;
4649
4650 if (S.getLangOpts().CPlusPlus) {
4651 // C++11 [dcl.array]p3:
4652 // If there is a preceding declaration of the entity in the same
4653 // scope in which the bound was specified, an omitted array bound
4654 // is taken to be the same as in that earlier declaration.
4655 return NewVD->isPreviousDeclInSameBlockScope() ||
4656 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4657 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4658 } else {
4659 // If the old declaration was function-local, don't merge with its
4660 // type unless we're in the same function.
4661 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4662 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4663 }
4664}
4665
4666void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4667 // If the new decl is already invalid, don't do any other checking.
4668 if (New->isInvalidDecl())
4669 return;
4670
4671 if (!shouldLinkPossiblyHiddenDecl(Old&: Previous, New))
4672 return;
4673
4674 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4675
4676 // Verify the old decl was also a variable or variable template.
4677 VarDecl *Old = nullptr;
4678 VarTemplateDecl *OldTemplate = nullptr;
4679 if (Previous.isSingleResult()) {
4680 if (NewTemplate) {
4681 OldTemplate = dyn_cast<VarTemplateDecl>(Val: Previous.getFoundDecl());
4682 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4683
4684 if (auto *Shadow =
4685 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4686 if (checkUsingShadowRedecl<VarTemplateDecl>(S&: *this, OldS: Shadow, New: NewTemplate))
4687 return New->setInvalidDecl();
4688 } else {
4689 Old = dyn_cast<VarDecl>(Val: Previous.getFoundDecl());
4690
4691 if (auto *Shadow =
4692 dyn_cast<UsingShadowDecl>(Val: Previous.getRepresentativeDecl()))
4693 if (checkUsingShadowRedecl<VarDecl>(S&: *this, OldS: Shadow, New))
4694 return New->setInvalidDecl();
4695 }
4696 }
4697 if (!Old) {
4698 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition_different_kind)
4699 << New->getDeclName();
4700 notePreviousDefinition(Old: Previous.getRepresentativeDecl(),
4701 New: New->getLocation());
4702 return New->setInvalidDecl();
4703 }
4704
4705 // If the old declaration was found in an inline namespace and the new
4706 // declaration was qualified, update the DeclContext to match.
4707 adjustDeclContextForDeclaratorDecl(NewD: New, OldD: Old);
4708
4709 // Ensure the template parameters are compatible.
4710 if (NewTemplate &&
4711 !TemplateParameterListsAreEqual(New: NewTemplate->getTemplateParameters(),
4712 Old: OldTemplate->getTemplateParameters(),
4713 /*Complain=*/true, Kind: TPL_TemplateMatch))
4714 return New->setInvalidDecl();
4715
4716 // C++ [class.mem]p1:
4717 // A member shall not be declared twice in the member-specification [...]
4718 //
4719 // Here, we need only consider static data members.
4720 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4721 Diag(Loc: New->getLocation(), DiagID: diag::err_duplicate_member)
4722 << New->getIdentifier();
4723 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4724 New->setInvalidDecl();
4725 }
4726
4727 mergeDeclAttributes(New, Old);
4728 // Warn if an already-defined variable is made a weak_import in a subsequent
4729 // declaration
4730 if (New->hasAttr<WeakImportAttr>())
4731 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4732 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4733 Diag(Loc: New->getLocation(), DiagID: diag::warn_weak_import) << New->getDeclName();
4734 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
4735 // Remove weak_import attribute on new declaration.
4736 New->dropAttr<WeakImportAttr>();
4737 break;
4738 }
4739 }
4740
4741 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4742 if (!Old->hasAttr<InternalLinkageAttr>()) {
4743 Diag(Loc: New->getLocation(), DiagID: diag::err_attribute_missing_on_first_decl)
4744 << ILA;
4745 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4746 New->dropAttr<InternalLinkageAttr>();
4747 }
4748
4749 // Merge the types.
4750 VarDecl *MostRecent = Old->getMostRecentDecl();
4751 if (MostRecent != Old) {
4752 MergeVarDeclTypes(New, Old: MostRecent,
4753 MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: MostRecent, Previous));
4754 if (New->isInvalidDecl())
4755 return;
4756 }
4757
4758 MergeVarDeclTypes(New, Old, MergeTypeWithOld: mergeTypeWithPrevious(S&: *this, NewVD: New, OldVD: Old, Previous));
4759 if (New->isInvalidDecl())
4760 return;
4761
4762 diag::kind PrevDiag;
4763 SourceLocation OldLocation;
4764 std::tie(args&: PrevDiag, args&: OldLocation) =
4765 getNoteDiagForInvalidRedeclaration(Old, New);
4766
4767 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4768 if (New->getStorageClass() == SC_Static &&
4769 !New->isStaticDataMember() &&
4770 Old->hasExternalFormalLinkage()) {
4771 if (getLangOpts().MicrosoftExt) {
4772 Diag(Loc: New->getLocation(), DiagID: diag::ext_static_non_static)
4773 << New->getDeclName();
4774 Diag(Loc: OldLocation, DiagID: PrevDiag);
4775 } else {
4776 Diag(Loc: New->getLocation(), DiagID: diag::err_static_non_static)
4777 << New->getDeclName();
4778 Diag(Loc: OldLocation, DiagID: PrevDiag);
4779 return New->setInvalidDecl();
4780 }
4781 }
4782 // C99 6.2.2p4:
4783 // For an identifier declared with the storage-class specifier
4784 // extern in a scope in which a prior declaration of that
4785 // identifier is visible,23) if the prior declaration specifies
4786 // internal or external linkage, the linkage of the identifier at
4787 // the later declaration is the same as the linkage specified at
4788 // the prior declaration. If no prior declaration is visible, or
4789 // if the prior declaration specifies no linkage, then the
4790 // identifier has external linkage.
4791 if (New->hasExternalStorage() && Old->hasLinkage())
4792 /* Okay */;
4793 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4794 !New->isStaticDataMember() &&
4795 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4796 Diag(Loc: New->getLocation(), DiagID: diag::err_non_static_static) << New->getDeclName();
4797 Diag(Loc: OldLocation, DiagID: PrevDiag);
4798 return New->setInvalidDecl();
4799 }
4800
4801 // Check if extern is followed by non-extern and vice-versa.
4802 if (New->hasExternalStorage() &&
4803 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4804 Diag(Loc: New->getLocation(), DiagID: diag::err_extern_non_extern) << New->getDeclName();
4805 Diag(Loc: OldLocation, DiagID: PrevDiag);
4806 return New->setInvalidDecl();
4807 }
4808 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4809 !New->hasExternalStorage()) {
4810 Diag(Loc: New->getLocation(), DiagID: diag::err_non_extern_extern) << New->getDeclName();
4811 Diag(Loc: OldLocation, DiagID: PrevDiag);
4812 return New->setInvalidDecl();
4813 }
4814
4815 if (CheckRedeclarationInModule(New, Old))
4816 return;
4817
4818 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4819
4820 // FIXME: The test for external storage here seems wrong? We still
4821 // need to check for mismatches.
4822 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4823 // Don't complain about out-of-line definitions of static members.
4824 !(Old->getLexicalDeclContext()->isRecord() &&
4825 !New->getLexicalDeclContext()->isRecord())) {
4826 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New->getDeclName();
4827 Diag(Loc: OldLocation, DiagID: PrevDiag);
4828 return New->setInvalidDecl();
4829 }
4830
4831 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4832 if (VarDecl *Def = Old->getDefinition()) {
4833 // C++1z [dcl.fcn.spec]p4:
4834 // If the definition of a variable appears in a translation unit before
4835 // its first declaration as inline, the program is ill-formed.
4836 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
4837 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
4838 }
4839 }
4840
4841 // If this redeclaration makes the variable inline, we may need to add it to
4842 // UndefinedButUsed.
4843 if (!Old->isInline() && New->isInline() && Old->isUsed(CheckUsedAttr: false) &&
4844 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4845 !Old->isInAnotherModuleUnit())
4846 UndefinedButUsed.insert(KV: std::make_pair(x: Old->getCanonicalDecl(),
4847 y: SourceLocation()));
4848
4849 if (New->getTLSKind() != Old->getTLSKind()) {
4850 if (!Old->getTLSKind()) {
4851 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_non_thread) << New->getDeclName();
4852 Diag(Loc: OldLocation, DiagID: PrevDiag);
4853 } else if (!New->getTLSKind()) {
4854 Diag(Loc: New->getLocation(), DiagID: diag::err_non_thread_thread) << New->getDeclName();
4855 Diag(Loc: OldLocation, DiagID: PrevDiag);
4856 } else {
4857 // Do not allow redeclaration to change the variable between requiring
4858 // static and dynamic initialization.
4859 // FIXME: GCC allows this, but uses the TLS keyword on the first
4860 // declaration to determine the kind. Do we need to be compatible here?
4861 Diag(Loc: New->getLocation(), DiagID: diag::err_thread_thread_different_kind)
4862 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4863 Diag(Loc: OldLocation, DiagID: PrevDiag);
4864 }
4865 }
4866
4867 // C++ doesn't have tentative definitions, so go right ahead and check here.
4868 if (getLangOpts().CPlusPlus) {
4869 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4870 Old->getCanonicalDecl()->isConstexpr()) {
4871 // This definition won't be a definition any more once it's been merged.
4872 Diag(Loc: New->getLocation(),
4873 DiagID: diag::warn_deprecated_redundant_constexpr_static_def);
4874 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4875 VarDecl *Def = Old->getDefinition();
4876 if (Def && checkVarDeclRedefinition(OldDefn: Def, NewDefn: New))
4877 return;
4878 }
4879 } else {
4880 // C++ may not have a tentative definition rule, but it has a different
4881 // rule about what constitutes a definition in the first place. See
4882 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4883 // contains the extern specifier and doesn't have an initializer, it's fine
4884 // in C++.
4885 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4886 Diag(Loc: New->getLocation(), DiagID: diag::warn_cxx_compat_tentative_definition)
4887 << New;
4888 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
4889 }
4890 }
4891
4892 if (haveIncompatibleLanguageLinkages(Old, New)) {
4893 Diag(Loc: New->getLocation(), DiagID: diag::err_different_language_linkage) << New;
4894 Diag(Loc: OldLocation, DiagID: PrevDiag);
4895 New->setInvalidDecl();
4896 return;
4897 }
4898
4899 // Merge "used" flag.
4900 if (Old->getMostRecentDecl()->isUsed(CheckUsedAttr: false))
4901 New->setIsUsed();
4902
4903 // Keep a chain of previous declarations.
4904 New->setPreviousDecl(Old);
4905 if (NewTemplate)
4906 NewTemplate->setPreviousDecl(OldTemplate);
4907
4908 // Inherit access appropriately.
4909 New->setAccess(Old->getAccess());
4910 if (NewTemplate)
4911 NewTemplate->setAccess(New->getAccess());
4912
4913 if (Old->isInline())
4914 New->setImplicitlyInline();
4915}
4916
4917void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4918 SourceManager &SrcMgr = getSourceManager();
4919 auto FNewDecLoc = SrcMgr.getDecomposedLoc(Loc: New);
4920 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Loc: Old->getLocation());
4921 auto *FNew = SrcMgr.getFileEntryForID(FID: FNewDecLoc.first);
4922 auto FOld = SrcMgr.getFileEntryRefForID(FID: FOldDecLoc.first);
4923 auto &HSI = PP.getHeaderSearchInfo();
4924 StringRef HdrFilename =
4925 SrcMgr.getFilename(SpellingLoc: SrcMgr.getSpellingLoc(Loc: Old->getLocation()));
4926
4927 auto noteFromModuleOrInclude = [&](Module *Mod,
4928 SourceLocation IncLoc) -> bool {
4929 // Redefinition errors with modules are common with non modular mapped
4930 // headers, example: a non-modular header H in module A that also gets
4931 // included directly in a TU. Pointing twice to the same header/definition
4932 // is confusing, try to get better diagnostics when modules is on.
4933 if (IncLoc.isValid()) {
4934 if (Mod) {
4935 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_modules_same_file)
4936 << HdrFilename.str() << Mod->getFullModuleName();
4937 if (!Mod->DefinitionLoc.isInvalid())
4938 Diag(Loc: Mod->DefinitionLoc, DiagID: diag::note_defined_here)
4939 << Mod->getFullModuleName();
4940 } else {
4941 Diag(Loc: IncLoc, DiagID: diag::note_redefinition_include_same_file)
4942 << HdrFilename.str();
4943 }
4944 return true;
4945 }
4946
4947 return false;
4948 };
4949
4950 // Is it the same file and same offset? Provide more information on why
4951 // this leads to a redefinition error.
4952 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4953 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FID: FOldDecLoc.first);
4954 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FID: FNewDecLoc.first);
4955 bool EmittedDiag =
4956 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4957 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4958
4959 // If the header has no guards, emit a note suggesting one.
4960 if (FOld && !HSI.isFileMultipleIncludeGuarded(File: *FOld))
4961 Diag(Loc: Old->getLocation(), DiagID: diag::note_use_ifdef_guards);
4962
4963 if (EmittedDiag)
4964 return;
4965 }
4966
4967 // Redefinition coming from different files or couldn't do better above.
4968 if (Old->getLocation().isValid())
4969 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
4970}
4971
4972bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4973 if (!hasVisibleDefinition(D: Old) &&
4974 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4975 isa<VarTemplateSpecializationDecl>(Val: New) ||
4976 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4977 New->getDeclContext()->isDependentContext() ||
4978 New->hasAttr<SelectAnyAttr>())) {
4979 // The previous definition is hidden, and multiple definitions are
4980 // permitted (in separate TUs). Demote this to a declaration.
4981 New->demoteThisDefinitionToDeclaration();
4982
4983 // Make the canonical definition visible.
4984 if (auto *OldTD = Old->getDescribedVarTemplate())
4985 makeMergedDefinitionVisible(ND: OldTD);
4986 makeMergedDefinitionVisible(ND: Old);
4987 return false;
4988 } else {
4989 Diag(Loc: New->getLocation(), DiagID: diag::err_redefinition) << New;
4990 notePreviousDefinition(Old, New: New->getLocation());
4991 New->setInvalidDecl();
4992 return true;
4993 }
4994}
4995
4996Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4997 DeclSpec &DS,
4998 const ParsedAttributesView &DeclAttrs,
4999 RecordDecl *&AnonRecord) {
5000 return ParsedFreeStandingDeclSpec(
5001 S, AS, DS, DeclAttrs, TemplateParams: MultiTemplateParamsArg(), IsExplicitInstantiation: false, AnonRecord);
5002}
5003
5004// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5005// disambiguate entities defined in different scopes.
5006// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5007// compatibility.
5008// We will pick our mangling number depending on which version of MSVC is being
5009// targeted.
5010static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5011 return LO.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015)
5012 ? S->getMSCurManglingNumber()
5013 : S->getMSLastManglingNumber();
5014}
5015
5016void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5017 if (!Context.getLangOpts().CPlusPlus)
5018 return;
5019
5020 if (isa<CXXRecordDecl>(Val: Tag->getParent())) {
5021 // If this tag is the direct child of a class, number it if
5022 // it is anonymous.
5023 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5024 return;
5025 MangleNumberingContext &MCtx =
5026 Context.getManglingNumberContext(DC: Tag->getParent());
5027 Context.setManglingNumber(
5028 ND: Tag, Number: MCtx.getManglingNumber(
5029 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5030 return;
5031 }
5032
5033 // If this tag isn't a direct child of a class, number it if it is local.
5034 MangleNumberingContext *MCtx;
5035 Decl *ManglingContextDecl;
5036 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5037 getCurrentMangleNumberContext(DC: Tag->getDeclContext());
5038 if (MCtx) {
5039 Context.setManglingNumber(
5040 ND: Tag, Number: MCtx->getManglingNumber(
5041 TD: Tag, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S: TagScope)));
5042 }
5043}
5044
5045namespace {
5046struct NonCLikeKind {
5047 enum {
5048 None,
5049 BaseClass,
5050 DefaultMemberInit,
5051 Lambda,
5052 Friend,
5053 OtherMember,
5054 Invalid,
5055 } Kind = None;
5056 SourceRange Range;
5057
5058 explicit operator bool() { return Kind != None; }
5059};
5060}
5061
5062/// Determine whether a class is C-like, according to the rules of C++
5063/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5064static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5065 if (RD->isInvalidDecl())
5066 return {.Kind: NonCLikeKind::Invalid, .Range: {}};
5067
5068 // C++ [dcl.typedef]p9: [P1766R1]
5069 // An unnamed class with a typedef name for linkage purposes shall not
5070 //
5071 // -- have any base classes
5072 if (RD->getNumBases())
5073 return {.Kind: NonCLikeKind::BaseClass,
5074 .Range: SourceRange(RD->bases_begin()->getBeginLoc(),
5075 RD->bases_end()[-1].getEndLoc())};
5076 bool Invalid = false;
5077 for (Decl *D : RD->decls()) {
5078 // Don't complain about things we already diagnosed.
5079 if (D->isInvalidDecl()) {
5080 Invalid = true;
5081 continue;
5082 }
5083
5084 // -- have any [...] default member initializers
5085 if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
5086 if (FD->hasInClassInitializer()) {
5087 auto *Init = FD->getInClassInitializer();
5088 return {.Kind: NonCLikeKind::DefaultMemberInit,
5089 .Range: Init ? Init->getSourceRange() : D->getSourceRange()};
5090 }
5091 continue;
5092 }
5093
5094 // FIXME: We don't allow friend declarations. This violates the wording of
5095 // P1766, but not the intent.
5096 if (isa<FriendDecl>(Val: D))
5097 return {.Kind: NonCLikeKind::Friend, .Range: D->getSourceRange()};
5098
5099 // -- declare any members other than non-static data members, member
5100 // enumerations, or member classes,
5101 if (isa<StaticAssertDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) ||
5102 isa<EnumDecl>(Val: D))
5103 continue;
5104 auto *MemberRD = dyn_cast<CXXRecordDecl>(Val: D);
5105 if (!MemberRD) {
5106 if (D->isImplicit())
5107 continue;
5108 return {.Kind: NonCLikeKind::OtherMember, .Range: D->getSourceRange()};
5109 }
5110
5111 // -- contain a lambda-expression,
5112 if (MemberRD->isLambda())
5113 return {.Kind: NonCLikeKind::Lambda, .Range: MemberRD->getSourceRange()};
5114
5115 // and all member classes shall also satisfy these requirements
5116 // (recursively).
5117 if (MemberRD->isThisDeclarationADefinition()) {
5118 if (auto Kind = getNonCLikeKindForAnonymousStruct(RD: MemberRD))
5119 return Kind;
5120 }
5121 }
5122
5123 return {.Kind: Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, .Range: {}};
5124}
5125
5126void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5127 TypedefNameDecl *NewTD) {
5128 if (TagFromDeclSpec->isInvalidDecl())
5129 return;
5130
5131 // Do nothing if the tag already has a name for linkage purposes.
5132 if (TagFromDeclSpec->hasNameForLinkage())
5133 return;
5134
5135 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5136 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5137
5138 // The type must match the tag exactly; no qualifiers allowed.
5139 if (!Context.hasSameType(T1: NewTD->getUnderlyingType(),
5140 T2: Context.getCanonicalTagType(TD: TagFromDeclSpec))) {
5141 if (getLangOpts().CPlusPlus)
5142 Context.addTypedefNameForUnnamedTagDecl(TD: TagFromDeclSpec, TND: NewTD);
5143 return;
5144 }
5145
5146 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5147 // An unnamed class with a typedef name for linkage purposes shall [be
5148 // C-like].
5149 //
5150 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5151 // shouldn't happen, but there are constructs that the language rule doesn't
5152 // disallow for which we can't reasonably avoid computing linkage early.
5153 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TagFromDeclSpec);
5154 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5155 : NonCLikeKind();
5156 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5157 if (NonCLike || ChangesLinkage) {
5158 if (NonCLike.Kind == NonCLikeKind::Invalid)
5159 return;
5160
5161 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5162 if (ChangesLinkage) {
5163 // If the linkage changes, we can't accept this as an extension.
5164 if (NonCLike.Kind == NonCLikeKind::None)
5165 DiagID = diag::err_typedef_changes_linkage;
5166 else
5167 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5168 }
5169
5170 SourceLocation FixitLoc =
5171 getLocForEndOfToken(Loc: TagFromDeclSpec->getInnerLocStart());
5172 llvm::SmallString<40> TextToInsert;
5173 TextToInsert += ' ';
5174 TextToInsert += NewTD->getIdentifier()->getName();
5175
5176 Diag(Loc: FixitLoc, DiagID)
5177 << isa<TypeAliasDecl>(Val: NewTD)
5178 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: TextToInsert);
5179 if (NonCLike.Kind != NonCLikeKind::None) {
5180 Diag(Loc: NonCLike.Range.getBegin(), DiagID: diag::note_non_c_like_anon_struct)
5181 << NonCLike.Kind - 1 << NonCLike.Range;
5182 }
5183 Diag(Loc: NewTD->getLocation(), DiagID: diag::note_typedef_for_linkage_here)
5184 << NewTD << isa<TypeAliasDecl>(Val: NewTD);
5185
5186 if (ChangesLinkage)
5187 return;
5188 }
5189
5190 // Otherwise, set this as the anon-decl typedef for the tag.
5191 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5192
5193 // Now that we have a name for the tag, process API notes again.
5194 ProcessAPINotes(D: TagFromDeclSpec);
5195}
5196
5197static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5198 DeclSpec::TST T = DS.getTypeSpecType();
5199 switch (T) {
5200 case DeclSpec::TST_class:
5201 return 0;
5202 case DeclSpec::TST_struct:
5203 return 1;
5204 case DeclSpec::TST_interface:
5205 return 2;
5206 case DeclSpec::TST_union:
5207 return 3;
5208 case DeclSpec::TST_enum:
5209 if (const auto *ED = dyn_cast<EnumDecl>(Val: DS.getRepAsDecl())) {
5210 if (ED->isScopedUsingClassTag())
5211 return 5;
5212 if (ED->isScoped())
5213 return 6;
5214 }
5215 return 4;
5216 default:
5217 llvm_unreachable("unexpected type specifier");
5218 }
5219}
5220
5221Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5222 DeclSpec &DS,
5223 const ParsedAttributesView &DeclAttrs,
5224 MultiTemplateParamsArg TemplateParams,
5225 bool IsExplicitInstantiation,
5226 RecordDecl *&AnonRecord,
5227 SourceLocation EllipsisLoc) {
5228 Decl *TagD = nullptr;
5229 TagDecl *Tag = nullptr;
5230 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5231 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5232 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5233 DS.getTypeSpecType() == DeclSpec::TST_union ||
5234 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5235 TagD = DS.getRepAsDecl();
5236
5237 if (!TagD) // We probably had an error
5238 return nullptr;
5239
5240 // Note that the above type specs guarantee that the
5241 // type rep is a Decl, whereas in many of the others
5242 // it's a Type.
5243 if (isa<TagDecl>(Val: TagD))
5244 Tag = cast<TagDecl>(Val: TagD);
5245 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: TagD))
5246 Tag = CTD->getTemplatedDecl();
5247 }
5248
5249 if (Tag) {
5250 handleTagNumbering(Tag, TagScope: S);
5251 Tag->setFreeStanding();
5252 if (Tag->isInvalidDecl())
5253 return Tag;
5254 }
5255
5256 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5257 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5258 // or incomplete types shall not be restrict-qualified."
5259 if (TypeQuals & DeclSpec::TQ_restrict)
5260 Diag(Loc: DS.getRestrictSpecLoc(),
5261 DiagID: diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5262 << DS.getSourceRange();
5263 }
5264
5265 if (DS.isInlineSpecified())
5266 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
5267 << getLangOpts().CPlusPlus17;
5268
5269 if (DS.hasConstexprSpecifier()) {
5270 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5271 // and definitions of functions and variables.
5272 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5273 // the declaration of a function or function template
5274 if (Tag)
5275 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_tag)
5276 << GetDiagnosticTypeSpecifierID(DS)
5277 << static_cast<int>(DS.getConstexprSpecifier());
5278 else if (getLangOpts().C23)
5279 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_c23_constexpr_not_variable);
5280 else
5281 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_wrong_decl_kind)
5282 << static_cast<int>(DS.getConstexprSpecifier());
5283 // Don't emit warnings after this error.
5284 return TagD;
5285 }
5286
5287 DiagnoseFunctionSpecifiers(DS);
5288
5289 if (DS.isFriendSpecified()) {
5290 // If we're dealing with a decl but not a TagDecl, assume that
5291 // whatever routines created it handled the friendship aspect.
5292 if (TagD && !Tag)
5293 return nullptr;
5294 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5295 }
5296
5297 assert(EllipsisLoc.isInvalid() &&
5298 "Friend ellipsis but not friend-specified?");
5299
5300 // Track whether this decl-specifier declares anything.
5301 bool DeclaresAnything = true;
5302
5303 // Handle anonymous struct definitions.
5304 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Val: Tag)) {
5305 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5306 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5307 if (getLangOpts().CPlusPlus ||
5308 Record->getDeclContext()->isRecord()) {
5309 // If CurContext is a DeclContext that can contain statements,
5310 // RecursiveASTVisitor won't visit the decls that
5311 // BuildAnonymousStructOrUnion() will put into CurContext.
5312 // Also store them here so that they can be part of the
5313 // DeclStmt that gets created in this case.
5314 // FIXME: Also return the IndirectFieldDecls created by
5315 // BuildAnonymousStructOr union, for the same reason?
5316 if (CurContext->isFunctionOrMethod())
5317 AnonRecord = Record;
5318 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5319 Policy: Context.getPrintingPolicy());
5320 }
5321
5322 DeclaresAnything = false;
5323 }
5324 }
5325
5326 // C11 6.7.2.1p2:
5327 // A struct-declaration that does not declare an anonymous structure or
5328 // anonymous union shall contain a struct-declarator-list.
5329 //
5330 // This rule also existed in C89 and C99; the grammar for struct-declaration
5331 // did not permit a struct-declaration without a struct-declarator-list.
5332 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5333 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5334 // Check for Microsoft C extension: anonymous struct/union member.
5335 // Handle 2 kinds of anonymous struct/union:
5336 // struct STRUCT;
5337 // union UNION;
5338 // and
5339 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5340 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5341 if ((Tag && Tag->getDeclName()) ||
5342 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5343 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Val: Tag)
5344 : DS.getRepAsType().get()->getAsRecordDecl();
5345 if (Record && getLangOpts().MSAnonymousStructs) {
5346 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_ms_anonymous_record)
5347 << Record->isUnion() << DS.getSourceRange();
5348 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5349 }
5350
5351 DeclaresAnything = false;
5352 }
5353 }
5354
5355 // Skip all the checks below if we have a type error.
5356 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5357 (TagD && TagD->isInvalidDecl()))
5358 return TagD;
5359
5360 if (getLangOpts().CPlusPlus &&
5361 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5362 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Val: Tag))
5363 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5364 !Enum->isInvalidDecl())
5365 DeclaresAnything = false;
5366
5367 if (!DS.isMissingDeclaratorOk()) {
5368 // Customize diagnostic for a typedef missing a name.
5369 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5370 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_typedef_without_a_name)
5371 << DS.getSourceRange();
5372 else
5373 DeclaresAnything = false;
5374 }
5375
5376 if (DS.isModulePrivateSpecified() &&
5377 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5378 Diag(Loc: DS.getModulePrivateSpecLoc(), DiagID: diag::err_module_private_local_class)
5379 << Tag->getTagKind()
5380 << FixItHint::CreateRemoval(RemoveRange: DS.getModulePrivateSpecLoc());
5381
5382 ActOnDocumentableDecl(D: TagD);
5383
5384 // C 6.7/2:
5385 // A declaration [...] shall declare at least a declarator [...], a tag,
5386 // or the members of an enumeration.
5387 // C++ [dcl.dcl]p3:
5388 // [If there are no declarators], and except for the declaration of an
5389 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5390 // names into the program, or shall redeclare a name introduced by a
5391 // previous declaration.
5392 if (!DeclaresAnything) {
5393 // In C, we allow this as a (popular) extension / bug. Don't bother
5394 // producing further diagnostics for redundant qualifiers after this.
5395 Diag(Loc: DS.getBeginLoc(), DiagID: (IsExplicitInstantiation || !TemplateParams.empty())
5396 ? diag::err_no_declarators
5397 : diag::ext_no_declarators)
5398 << DS.getSourceRange();
5399 return TagD;
5400 }
5401
5402 // C++ [dcl.stc]p1:
5403 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5404 // init-declarator-list of the declaration shall not be empty.
5405 // C++ [dcl.fct.spec]p1:
5406 // If a cv-qualifier appears in a decl-specifier-seq, the
5407 // init-declarator-list of the declaration shall not be empty.
5408 //
5409 // Spurious qualifiers here appear to be valid in C.
5410 unsigned DiagID = diag::warn_standalone_specifier;
5411 if (getLangOpts().CPlusPlus)
5412 DiagID = diag::ext_standalone_specifier;
5413
5414 // Note that a linkage-specification sets a storage class, but
5415 // 'extern "C" struct foo;' is actually valid and not theoretically
5416 // useless.
5417 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5418 if (SCS == DeclSpec::SCS_mutable)
5419 // Since mutable is not a viable storage class specifier in C, there is
5420 // no reason to treat it as an extension. Instead, diagnose as an error.
5421 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_nonmember);
5422 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5423 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID)
5424 << DeclSpec::getSpecifierName(S: SCS);
5425 }
5426
5427 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5428 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID)
5429 << DeclSpec::getSpecifierName(S: TSCS);
5430 if (DS.getTypeQualifiers()) {
5431 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5432 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "const";
5433 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5434 Diag(Loc: DS.getConstSpecLoc(), DiagID) << "volatile";
5435 // Restrict is covered above.
5436 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5437 Diag(Loc: DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5438 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5439 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5440 }
5441
5442 // Warn about ignored type attributes, for example:
5443 // __attribute__((aligned)) struct A;
5444 // Attributes should be placed after tag to apply to type declaration.
5445 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5446 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5447 if (TypeSpecType == DeclSpec::TST_class ||
5448 TypeSpecType == DeclSpec::TST_struct ||
5449 TypeSpecType == DeclSpec::TST_interface ||
5450 TypeSpecType == DeclSpec::TST_union ||
5451 TypeSpecType == DeclSpec::TST_enum) {
5452
5453 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5454 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5455 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5456 DiagnosticId = diag::warn_attribute_ignored;
5457 else if (AL.isRegularKeywordAttribute())
5458 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5459 else
5460 DiagnosticId = diag::warn_declspec_attribute_ignored;
5461 Diag(Loc: AL.getLoc(), DiagID: DiagnosticId)
5462 << AL << GetDiagnosticTypeSpecifierID(DS);
5463 };
5464
5465 llvm::for_each(Range&: DS.getAttributes(), F: EmitAttributeDiagnostic);
5466 llvm::for_each(Range: DeclAttrs, F: EmitAttributeDiagnostic);
5467 }
5468 }
5469
5470 return TagD;
5471}
5472
5473/// We are trying to inject an anonymous member into the given scope;
5474/// check if there's an existing declaration that can't be overloaded.
5475///
5476/// \return true if this is a forbidden redeclaration
5477static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5478 DeclContext *Owner,
5479 DeclarationName Name,
5480 SourceLocation NameLoc, bool IsUnion,
5481 StorageClass SC) {
5482 LookupResult R(SemaRef, Name, NameLoc,
5483 Owner->isRecord() ? Sema::LookupMemberName
5484 : Sema::LookupOrdinaryName,
5485 RedeclarationKind::ForVisibleRedeclaration);
5486 if (!SemaRef.LookupName(R, S)) return false;
5487
5488 // Pick a representative declaration.
5489 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5490 assert(PrevDecl && "Expected a non-null Decl");
5491
5492 if (!SemaRef.isDeclInScope(D: PrevDecl, Ctx: Owner, S))
5493 return false;
5494
5495 if (SC == StorageClass::SC_None &&
5496 PrevDecl->isPlaceholderVar(LangOpts: SemaRef.getLangOpts()) &&
5497 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5498 if (!Owner->isRecord())
5499 SemaRef.DiagPlaceholderVariableDefinition(Loc: NameLoc);
5500 return false;
5501 }
5502
5503 SemaRef.Diag(Loc: NameLoc, DiagID: diag::err_anonymous_record_member_redecl)
5504 << IsUnion << Name;
5505 SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
5506
5507 return true;
5508}
5509
5510void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5511 if (auto *RD = dyn_cast_if_present<RecordDecl>(Val: D))
5512 DiagPlaceholderFieldDeclDefinitions(Record: RD);
5513}
5514
5515void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5516 if (!getLangOpts().CPlusPlus)
5517 return;
5518
5519 // This function can be parsed before we have validated the
5520 // structure as an anonymous struct
5521 if (Record->isAnonymousStructOrUnion())
5522 return;
5523
5524 const NamedDecl *First = 0;
5525 for (const Decl *D : Record->decls()) {
5526 const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D);
5527 if (!ND || !ND->isPlaceholderVar(LangOpts: getLangOpts()))
5528 continue;
5529 if (!First)
5530 First = ND;
5531 else
5532 DiagPlaceholderVariableDefinition(Loc: ND->getLocation());
5533 }
5534}
5535
5536/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5537/// anonymous struct or union AnonRecord into the owning context Owner
5538/// and scope S. This routine will be invoked just after we realize
5539/// that an unnamed union or struct is actually an anonymous union or
5540/// struct, e.g.,
5541///
5542/// @code
5543/// union {
5544/// int i;
5545/// float f;
5546/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5547/// // f into the surrounding scope.x
5548/// @endcode
5549///
5550/// This routine is recursive, injecting the names of nested anonymous
5551/// structs/unions into the owning context and scope as well.
5552static bool
5553InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5554 RecordDecl *AnonRecord, AccessSpecifier AS,
5555 StorageClass SC,
5556 SmallVectorImpl<NamedDecl *> &Chaining) {
5557 bool Invalid = false;
5558
5559 // Look every FieldDecl and IndirectFieldDecl with a name.
5560 for (auto *D : AnonRecord->decls()) {
5561 if ((isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D)) &&
5562 cast<NamedDecl>(Val: D)->getDeclName()) {
5563 ValueDecl *VD = cast<ValueDecl>(Val: D);
5564 // C++ [class.union]p2:
5565 // The names of the members of an anonymous union shall be
5566 // distinct from the names of any other entity in the
5567 // scope in which the anonymous union is declared.
5568
5569 bool FieldInvalid = CheckAnonMemberRedeclaration(
5570 SemaRef, S, Owner, Name: VD->getDeclName(), NameLoc: VD->getLocation(),
5571 IsUnion: AnonRecord->isUnion(), SC);
5572 if (FieldInvalid)
5573 Invalid = true;
5574
5575 // Inject the IndirectFieldDecl even if invalid, because later
5576 // diagnostics may depend on it being present, see findDefaultInitializer.
5577
5578 // C++ [class.union]p2:
5579 // For the purpose of name lookup, after the anonymous union
5580 // definition, the members of the anonymous union are
5581 // considered to have been defined in the scope in which the
5582 // anonymous union is declared.
5583 unsigned OldChainingSize = Chaining.size();
5584 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(Val: VD))
5585 Chaining.append(in_start: IF->chain_begin(), in_end: IF->chain_end());
5586 else
5587 Chaining.push_back(Elt: VD);
5588
5589 assert(Chaining.size() >= 2);
5590 NamedDecl **NamedChain =
5591 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5592 for (unsigned i = 0; i < Chaining.size(); i++)
5593 NamedChain[i] = Chaining[i];
5594
5595 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5596 C&: SemaRef.Context, DC: Owner, L: VD->getLocation(), Id: VD->getIdentifier(),
5597 T: VD->getType(), CH: {NamedChain, Chaining.size()});
5598
5599 for (const auto *Attr : VD->attrs())
5600 IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context));
5601
5602 IndirectField->setAccess(AS);
5603 IndirectField->setImplicit();
5604 IndirectField->setInvalidDecl(FieldInvalid);
5605 SemaRef.PushOnScopeChains(D: IndirectField, S);
5606
5607 // That includes picking up the appropriate access specifier.
5608 if (AS != AS_none)
5609 IndirectField->setAccess(AS);
5610
5611 Chaining.resize(N: OldChainingSize);
5612 }
5613 }
5614
5615 return Invalid;
5616}
5617
5618/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5619/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5620/// illegal input values are mapped to SC_None.
5621static StorageClass
5622StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5623 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5624 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5625 "Parser allowed 'typedef' as storage class VarDecl.");
5626 switch (StorageClassSpec) {
5627 case DeclSpec::SCS_unspecified: return SC_None;
5628 case DeclSpec::SCS_extern:
5629 if (DS.isExternInLinkageSpec())
5630 return SC_None;
5631 return SC_Extern;
5632 case DeclSpec::SCS_static: return SC_Static;
5633 case DeclSpec::SCS_auto: return SC_Auto;
5634 case DeclSpec::SCS_register: return SC_Register;
5635 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5636 // Illegal SCSs map to None: error reporting is up to the caller.
5637 case DeclSpec::SCS_mutable: // Fall through.
5638 case DeclSpec::SCS_typedef: return SC_None;
5639 }
5640 llvm_unreachable("unknown storage class specifier");
5641}
5642
5643static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5644 assert(Record->hasInClassInitializer());
5645
5646 for (const auto *I : Record->decls()) {
5647 const auto *FD = dyn_cast<FieldDecl>(Val: I);
5648 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
5649 FD = IFD->getAnonField();
5650 if (FD && FD->hasInClassInitializer())
5651 return FD->getLocation();
5652 }
5653
5654 llvm_unreachable("couldn't find in-class initializer");
5655}
5656
5657static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5658 SourceLocation DefaultInitLoc) {
5659 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5660 return;
5661
5662 S.Diag(Loc: DefaultInitLoc, DiagID: diag::err_multiple_mem_union_initialization);
5663 S.Diag(Loc: findDefaultInitializer(Record: Parent), DiagID: diag::note_previous_initializer) << 0;
5664}
5665
5666static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5667 CXXRecordDecl *AnonUnion) {
5668 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5669 return;
5670
5671 checkDuplicateDefaultInit(S, Parent, DefaultInitLoc: findDefaultInitializer(Record: AnonUnion));
5672}
5673
5674Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5675 AccessSpecifier AS,
5676 RecordDecl *Record,
5677 const PrintingPolicy &Policy) {
5678 DeclContext *Owner = Record->getDeclContext();
5679
5680 // Diagnose whether this anonymous struct/union is an extension.
5681 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5682 Diag(Loc: Record->getLocation(), DiagID: diag::ext_anonymous_union);
5683 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5684 Diag(Loc: Record->getLocation(), DiagID: diag::ext_gnu_anonymous_struct);
5685 else if (!Record->isUnion() && !getLangOpts().C11)
5686 Diag(Loc: Record->getLocation(), DiagID: diag::ext_c11_anonymous_struct);
5687
5688 // C and C++ require different kinds of checks for anonymous
5689 // structs/unions.
5690 bool Invalid = false;
5691 if (getLangOpts().CPlusPlus) {
5692 const char *PrevSpec = nullptr;
5693 if (Record->isUnion()) {
5694 // C++ [class.union]p6:
5695 // C++17 [class.union.anon]p2:
5696 // Anonymous unions declared in a named namespace or in the
5697 // global namespace shall be declared static.
5698 unsigned DiagID;
5699 DeclContext *OwnerScope = Owner->getRedeclContext();
5700 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5701 (OwnerScope->isTranslationUnit() ||
5702 (OwnerScope->isNamespace() &&
5703 !cast<NamespaceDecl>(Val: OwnerScope)->isAnonymousNamespace()))) {
5704 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_union_not_static)
5705 << FixItHint::CreateInsertion(InsertionLoc: Record->getLocation(), Code: "static ");
5706
5707 // Recover by adding 'static'.
5708 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_static, Loc: SourceLocation(),
5709 PrevSpec, DiagID, Policy);
5710 }
5711 // C++ [class.union]p6:
5712 // A storage class is not allowed in a declaration of an
5713 // anonymous union in a class scope.
5714 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5715 isa<RecordDecl>(Val: Owner)) {
5716 Diag(Loc: DS.getStorageClassSpecLoc(),
5717 DiagID: diag::err_anonymous_union_with_storage_spec)
5718 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
5719
5720 // Recover by removing the storage specifier.
5721 DS.SetStorageClassSpec(S&: *this, SC: DeclSpec::SCS_unspecified,
5722 Loc: SourceLocation(),
5723 PrevSpec, DiagID, Policy: Context.getPrintingPolicy());
5724 }
5725 }
5726
5727 // Ignore const/volatile/restrict qualifiers.
5728 if (DS.getTypeQualifiers()) {
5729 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5730 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_anonymous_struct_union_qualified)
5731 << Record->isUnion() << "const"
5732 << FixItHint::CreateRemoval(RemoveRange: DS.getConstSpecLoc());
5733 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5734 Diag(Loc: DS.getVolatileSpecLoc(),
5735 DiagID: diag::ext_anonymous_struct_union_qualified)
5736 << Record->isUnion() << "volatile"
5737 << FixItHint::CreateRemoval(RemoveRange: DS.getVolatileSpecLoc());
5738 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5739 Diag(Loc: DS.getRestrictSpecLoc(),
5740 DiagID: diag::ext_anonymous_struct_union_qualified)
5741 << Record->isUnion() << "restrict"
5742 << FixItHint::CreateRemoval(RemoveRange: DS.getRestrictSpecLoc());
5743 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5744 Diag(Loc: DS.getAtomicSpecLoc(),
5745 DiagID: diag::ext_anonymous_struct_union_qualified)
5746 << Record->isUnion() << "_Atomic"
5747 << FixItHint::CreateRemoval(RemoveRange: DS.getAtomicSpecLoc());
5748 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5749 Diag(Loc: DS.getUnalignedSpecLoc(),
5750 DiagID: diag::ext_anonymous_struct_union_qualified)
5751 << Record->isUnion() << "__unaligned"
5752 << FixItHint::CreateRemoval(RemoveRange: DS.getUnalignedSpecLoc());
5753
5754 DS.ClearTypeQualifiers();
5755 }
5756
5757 // C++ [class.union]p2:
5758 // The member-specification of an anonymous union shall only
5759 // define non-static data members. [Note: nested types and
5760 // functions cannot be declared within an anonymous union. ]
5761 for (auto *Mem : Record->decls()) {
5762 // Ignore invalid declarations; we already diagnosed them.
5763 if (Mem->isInvalidDecl())
5764 continue;
5765
5766 if (auto *FD = dyn_cast<FieldDecl>(Val: Mem)) {
5767 // C++ [class.union]p3:
5768 // An anonymous union shall not have private or protected
5769 // members (clause 11).
5770 assert(FD->getAccess() != AS_none);
5771 if (FD->getAccess() != AS_public) {
5772 Diag(Loc: FD->getLocation(), DiagID: diag::err_anonymous_record_nonpublic_member)
5773 << Record->isUnion() << (FD->getAccess() == AS_protected);
5774 Invalid = true;
5775 }
5776
5777 // C++ [class.union]p1
5778 // An object of a class with a non-trivial constructor, a non-trivial
5779 // copy constructor, a non-trivial destructor, or a non-trivial copy
5780 // assignment operator cannot be a member of a union, nor can an
5781 // array of such objects.
5782 if (CheckNontrivialField(FD))
5783 Invalid = true;
5784 } else if (Mem->isImplicit()) {
5785 // Any implicit members are fine.
5786 } else if (isa<TagDecl>(Val: Mem) && Mem->getDeclContext() != Record) {
5787 // This is a type that showed up in an
5788 // elaborated-type-specifier inside the anonymous struct or
5789 // union, but which actually declares a type outside of the
5790 // anonymous struct or union. It's okay.
5791 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Val: Mem)) {
5792 if (!MemRecord->isAnonymousStructOrUnion() &&
5793 MemRecord->getDeclName()) {
5794 // Visual C++ allows type definition in anonymous struct or union.
5795 if (getLangOpts().MicrosoftExt)
5796 Diag(Loc: MemRecord->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5797 << Record->isUnion();
5798 else {
5799 // This is a nested type declaration.
5800 Diag(Loc: MemRecord->getLocation(), DiagID: diag::err_anonymous_record_with_type)
5801 << Record->isUnion();
5802 Invalid = true;
5803 }
5804 } else {
5805 // This is an anonymous type definition within another anonymous type.
5806 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5807 // not part of standard C++.
5808 Diag(Loc: MemRecord->getLocation(),
5809 DiagID: diag::ext_anonymous_record_with_anonymous_type)
5810 << Record->isUnion();
5811 }
5812 } else if (isa<AccessSpecDecl>(Val: Mem)) {
5813 // Any access specifier is fine.
5814 } else if (isa<StaticAssertDecl>(Val: Mem)) {
5815 // In C++1z, static_assert declarations are also fine.
5816 } else {
5817 // We have something that isn't a non-static data
5818 // member. Complain about it.
5819 unsigned DK = diag::err_anonymous_record_bad_member;
5820 if (isa<TypeDecl>(Val: Mem))
5821 DK = diag::err_anonymous_record_with_type;
5822 else if (isa<FunctionDecl>(Val: Mem))
5823 DK = diag::err_anonymous_record_with_function;
5824 else if (isa<VarDecl>(Val: Mem))
5825 DK = diag::err_anonymous_record_with_static;
5826
5827 // Visual C++ allows type definition in anonymous struct or union.
5828 if (getLangOpts().MicrosoftExt &&
5829 DK == diag::err_anonymous_record_with_type)
5830 Diag(Loc: Mem->getLocation(), DiagID: diag::ext_anonymous_record_with_type)
5831 << Record->isUnion();
5832 else {
5833 Diag(Loc: Mem->getLocation(), DiagID: DK) << Record->isUnion();
5834 Invalid = true;
5835 }
5836 }
5837 }
5838
5839 // C++11 [class.union]p8 (DR1460):
5840 // At most one variant member of a union may have a
5841 // brace-or-equal-initializer.
5842 if (cast<CXXRecordDecl>(Val: Record)->hasInClassInitializer() &&
5843 Owner->isRecord())
5844 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Owner),
5845 AnonUnion: cast<CXXRecordDecl>(Val: Record));
5846 }
5847
5848 if (!Record->isUnion() && !Owner->isRecord()) {
5849 Diag(Loc: Record->getLocation(), DiagID: diag::err_anonymous_struct_not_member)
5850 << getLangOpts().CPlusPlus;
5851 Invalid = true;
5852 }
5853
5854 // C++ [dcl.dcl]p3:
5855 // [If there are no declarators], and except for the declaration of an
5856 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5857 // names into the program
5858 // C++ [class.mem]p2:
5859 // each such member-declaration shall either declare at least one member
5860 // name of the class or declare at least one unnamed bit-field
5861 //
5862 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5863 if (getLangOpts().CPlusPlus && Record->field_empty())
5864 Diag(Loc: DS.getBeginLoc(), DiagID: diag::ext_no_declarators) << DS.getSourceRange();
5865
5866 // Mock up a declarator.
5867 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5868 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5869 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5870 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5871
5872 // Create a declaration for this anonymous struct/union.
5873 NamedDecl *Anon = nullptr;
5874 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Val: Owner)) {
5875 Anon = FieldDecl::Create(
5876 C: Context, DC: OwningClass, StartLoc: DS.getBeginLoc(), IdLoc: Record->getLocation(),
5877 /*IdentifierInfo=*/Id: nullptr, T: Context.getCanonicalTagType(TD: Record), TInfo,
5878 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5879 /*InitStyle=*/ICIS_NoInit);
5880 Anon->setAccess(AS);
5881 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5882
5883 if (getLangOpts().CPlusPlus)
5884 FieldCollector->Add(D: cast<FieldDecl>(Val: Anon));
5885 } else {
5886 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5887 if (SCSpec == DeclSpec::SCS_mutable) {
5888 // mutable can only appear on non-static class members, so it's always
5889 // an error here
5890 Diag(Loc: Record->getLocation(), DiagID: diag::err_mutable_nonmember);
5891 Invalid = true;
5892 SC = SC_None;
5893 }
5894
5895 Anon = VarDecl::Create(C&: Context, DC: Owner, StartLoc: DS.getBeginLoc(),
5896 IdLoc: Record->getLocation(), /*IdentifierInfo=*/Id: nullptr,
5897 T: Context.getCanonicalTagType(TD: Record), TInfo, S: SC);
5898 if (Invalid)
5899 Anon->setInvalidDecl();
5900
5901 ProcessDeclAttributes(S, D: Anon, PD: Dc);
5902
5903 // Default-initialize the implicit variable. This initialization will be
5904 // trivial in almost all cases, except if a union member has an in-class
5905 // initializer:
5906 // union { int n = 0; };
5907 ActOnUninitializedDecl(dcl: Anon);
5908 }
5909 Anon->setImplicit();
5910
5911 // Mark this as an anonymous struct/union type.
5912 Record->setAnonymousStructOrUnion(true);
5913
5914 // Add the anonymous struct/union object to the current
5915 // context. We'll be referencing this object when we refer to one of
5916 // its members.
5917 Owner->addDecl(D: Anon);
5918
5919 // Inject the members of the anonymous struct/union into the owning
5920 // context and into the identifier resolver chain for name lookup
5921 // purposes.
5922 SmallVector<NamedDecl*, 2> Chain;
5923 Chain.push_back(Elt: Anon);
5924
5925 if (InjectAnonymousStructOrUnionMembers(SemaRef&: *this, S, Owner, AnonRecord: Record, AS, SC,
5926 Chaining&: Chain))
5927 Invalid = true;
5928
5929 if (VarDecl *NewVD = dyn_cast<VarDecl>(Val: Anon)) {
5930 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5931 MangleNumberingContext *MCtx;
5932 Decl *ManglingContextDecl;
5933 std::tie(args&: MCtx, args&: ManglingContextDecl) =
5934 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
5935 if (MCtx) {
5936 Context.setManglingNumber(
5937 ND: NewVD, Number: MCtx->getManglingNumber(
5938 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
5939 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
5940 }
5941 }
5942 }
5943
5944 if (Invalid)
5945 Anon->setInvalidDecl();
5946
5947 return Anon;
5948}
5949
5950Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5951 RecordDecl *Record) {
5952 assert(Record && "expected a record!");
5953
5954 // Mock up a declarator.
5955 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5956 TypeSourceInfo *TInfo = GetTypeForDeclarator(D&: Dc);
5957 assert(TInfo && "couldn't build declarator info for anonymous struct");
5958
5959 auto *ParentDecl = cast<RecordDecl>(Val: CurContext);
5960 CanQualType RecTy = Context.getCanonicalTagType(TD: Record);
5961
5962 // Create a declaration for this anonymous struct.
5963 NamedDecl *Anon =
5964 FieldDecl::Create(C: Context, DC: ParentDecl, StartLoc: DS.getBeginLoc(), IdLoc: DS.getBeginLoc(),
5965 /*IdentifierInfo=*/Id: nullptr, T: RecTy, TInfo,
5966 /*BitWidth=*/BW: nullptr, /*Mutable=*/false,
5967 /*InitStyle=*/ICIS_NoInit);
5968 Anon->setImplicit();
5969
5970 // Add the anonymous struct object to the current context.
5971 CurContext->addDecl(D: Anon);
5972
5973 // Inject the members of the anonymous struct into the current
5974 // context and into the identifier resolver chain for name lookup
5975 // purposes.
5976 SmallVector<NamedDecl*, 2> Chain;
5977 Chain.push_back(Elt: Anon);
5978
5979 RecordDecl *RecordDef = Record->getDefinition();
5980 if (RequireCompleteSizedType(Loc: Anon->getLocation(), T: RecTy,
5981 DiagID: diag::err_field_incomplete_or_sizeless) ||
5982 InjectAnonymousStructOrUnionMembers(
5983 SemaRef&: *this, S, Owner: CurContext, AnonRecord: RecordDef, AS: AS_none,
5984 SC: StorageClassSpecToVarDeclStorageClass(DS), Chaining&: Chain)) {
5985 Anon->setInvalidDecl();
5986 ParentDecl->setInvalidDecl();
5987 }
5988
5989 return Anon;
5990}
5991
5992DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5993 return GetNameFromUnqualifiedId(Name: D.getName());
5994}
5995
5996DeclarationNameInfo
5997Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5998 DeclarationNameInfo NameInfo;
5999 NameInfo.setLoc(Name.StartLocation);
6000
6001 switch (Name.getKind()) {
6002
6003 case UnqualifiedIdKind::IK_ImplicitSelfParam:
6004 case UnqualifiedIdKind::IK_Identifier:
6005 NameInfo.setName(Name.Identifier);
6006 return NameInfo;
6007
6008 case UnqualifiedIdKind::IK_DeductionGuideName: {
6009 // C++ [temp.deduct.guide]p3:
6010 // The simple-template-id shall name a class template specialization.
6011 // The template-name shall be the same identifier as the template-name
6012 // of the simple-template-id.
6013 // These together intend to imply that the template-name shall name a
6014 // class template.
6015 // FIXME: template<typename T> struct X {};
6016 // template<typename T> using Y = X<T>;
6017 // Y(int) -> Y<int>;
6018 // satisfies these rules but does not name a class template.
6019 TemplateName TN = Name.TemplateName.get().get();
6020 auto *Template = TN.getAsTemplateDecl();
6021 if (!Template || !isa<ClassTemplateDecl>(Val: Template)) {
6022 Diag(Loc: Name.StartLocation,
6023 DiagID: diag::err_deduction_guide_name_not_class_template)
6024 << (int)getTemplateNameKindForDiagnostics(Name: TN) << TN;
6025 if (Template)
6026 NoteTemplateLocation(Decl: *Template);
6027 return DeclarationNameInfo();
6028 }
6029
6030 NameInfo.setName(
6031 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template));
6032 return NameInfo;
6033 }
6034
6035 case UnqualifiedIdKind::IK_OperatorFunctionId:
6036 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6037 Op: Name.OperatorFunctionId.Operator));
6038 NameInfo.setCXXOperatorNameRange(SourceRange(
6039 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
6040 return NameInfo;
6041
6042 case UnqualifiedIdKind::IK_LiteralOperatorId:
6043 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6044 II: Name.Identifier));
6045 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
6046 return NameInfo;
6047
6048 case UnqualifiedIdKind::IK_ConversionFunctionId: {
6049 TypeSourceInfo *TInfo;
6050 QualType Ty = GetTypeFromParser(Ty: Name.ConversionFunctionId, TInfo: &TInfo);
6051 if (Ty.isNull())
6052 return DeclarationNameInfo();
6053 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6054 Ty: Context.getCanonicalType(T: Ty)));
6055 NameInfo.setNamedTypeInfo(TInfo);
6056 return NameInfo;
6057 }
6058
6059 case UnqualifiedIdKind::IK_ConstructorName: {
6060 TypeSourceInfo *TInfo;
6061 QualType Ty = GetTypeFromParser(Ty: Name.ConstructorName, TInfo: &TInfo);
6062 if (Ty.isNull())
6063 return DeclarationNameInfo();
6064 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6065 Ty: Context.getCanonicalType(T: Ty)));
6066 NameInfo.setNamedTypeInfo(TInfo);
6067 return NameInfo;
6068 }
6069
6070 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6071 // In well-formed code, we can only have a constructor
6072 // template-id that refers to the current context, so go there
6073 // to find the actual type being constructed.
6074 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(Val: CurContext);
6075 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6076 return DeclarationNameInfo();
6077
6078 // Determine the type of the class being constructed.
6079 CanQualType CurClassType = Context.getCanonicalTagType(TD: CurClass);
6080
6081 // FIXME: Check two things: that the template-id names the same type as
6082 // CurClassType, and that the template-id does not occur when the name
6083 // was qualified.
6084
6085 NameInfo.setName(
6086 Context.DeclarationNames.getCXXConstructorName(Ty: CurClassType));
6087 // FIXME: should we retrieve TypeSourceInfo?
6088 NameInfo.setNamedTypeInfo(nullptr);
6089 return NameInfo;
6090 }
6091
6092 case UnqualifiedIdKind::IK_DestructorName: {
6093 TypeSourceInfo *TInfo;
6094 QualType Ty = GetTypeFromParser(Ty: Name.DestructorName, TInfo: &TInfo);
6095 if (Ty.isNull())
6096 return DeclarationNameInfo();
6097 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6098 Ty: Context.getCanonicalType(T: Ty)));
6099 NameInfo.setNamedTypeInfo(TInfo);
6100 return NameInfo;
6101 }
6102
6103 case UnqualifiedIdKind::IK_TemplateId: {
6104 TemplateName TName = Name.TemplateId->Template.get();
6105 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6106 return Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
6107 }
6108
6109 } // switch (Name.getKind())
6110
6111 llvm_unreachable("Unknown name kind");
6112}
6113
6114static QualType getCoreType(QualType Ty) {
6115 do {
6116 if (Ty->isPointerOrReferenceType())
6117 Ty = Ty->getPointeeType();
6118 else if (Ty->isArrayType())
6119 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6120 else
6121 return Ty.withoutLocalFastQualifiers();
6122 } while (true);
6123}
6124
6125/// hasSimilarParameters - Determine whether the C++ functions Declaration
6126/// and Definition have "nearly" matching parameters. This heuristic is
6127/// used to improve diagnostics in the case where an out-of-line function
6128/// definition doesn't match any declaration within the class or namespace.
6129/// Also sets Params to the list of indices to the parameters that differ
6130/// between the declaration and the definition. If hasSimilarParameters
6131/// returns true and Params is empty, then all of the parameters match.
6132static bool hasSimilarParameters(ASTContext &Context,
6133 FunctionDecl *Declaration,
6134 FunctionDecl *Definition,
6135 SmallVectorImpl<unsigned> &Params) {
6136 Params.clear();
6137 if (Declaration->param_size() != Definition->param_size())
6138 return false;
6139 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6140 QualType DeclParamTy = Declaration->getParamDecl(i: Idx)->getType();
6141 QualType DefParamTy = Definition->getParamDecl(i: Idx)->getType();
6142
6143 // The parameter types are identical
6144 if (Context.hasSameUnqualifiedType(T1: DefParamTy, T2: DeclParamTy))
6145 continue;
6146
6147 QualType DeclParamBaseTy = getCoreType(Ty: DeclParamTy);
6148 QualType DefParamBaseTy = getCoreType(Ty: DefParamTy);
6149 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6150 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6151
6152 if (Context.hasSameUnqualifiedType(T1: DeclParamBaseTy, T2: DefParamBaseTy) ||
6153 (DeclTyName && DeclTyName == DefTyName))
6154 Params.push_back(Elt: Idx);
6155 else // The two parameters aren't even close
6156 return false;
6157 }
6158
6159 return true;
6160}
6161
6162/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6163/// declarator needs to be rebuilt in the current instantiation.
6164/// Any bits of declarator which appear before the name are valid for
6165/// consideration here. That's specifically the type in the decl spec
6166/// and the base type in any member-pointer chunks.
6167static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6168 DeclarationName Name) {
6169 // The types we specifically need to rebuild are:
6170 // - typenames, typeofs, and decltypes
6171 // - types which will become injected class names
6172 // Of course, we also need to rebuild any type referencing such a
6173 // type. It's safest to just say "dependent", but we call out a
6174 // few cases here.
6175
6176 DeclSpec &DS = D.getMutableDeclSpec();
6177 switch (DS.getTypeSpecType()) {
6178 case DeclSpec::TST_typename:
6179 case DeclSpec::TST_typeofType:
6180 case DeclSpec::TST_typeof_unqualType:
6181#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6182#include "clang/Basic/TransformTypeTraits.def"
6183 case DeclSpec::TST_atomic: {
6184 // Grab the type from the parser.
6185 TypeSourceInfo *TSI = nullptr;
6186 QualType T = S.GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TSI);
6187 if (T.isNull() || !T->isInstantiationDependentType()) break;
6188
6189 // Make sure there's a type source info. This isn't really much
6190 // of a waste; most dependent types should have type source info
6191 // attached already.
6192 if (!TSI)
6193 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: DS.getTypeSpecTypeLoc());
6194
6195 // Rebuild the type in the current instantiation.
6196 TSI = S.RebuildTypeInCurrentInstantiation(T: TSI, Loc: D.getIdentifierLoc(), Name);
6197 if (!TSI) return true;
6198
6199 // Store the new type back in the decl spec.
6200 ParsedType LocType = S.CreateParsedType(T: TSI->getType(), TInfo: TSI);
6201 DS.UpdateTypeRep(Rep: LocType);
6202 break;
6203 }
6204
6205 case DeclSpec::TST_decltype:
6206 case DeclSpec::TST_typeof_unqualExpr:
6207 case DeclSpec::TST_typeofExpr: {
6208 Expr *E = DS.getRepAsExpr();
6209 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6210 if (Result.isInvalid()) return true;
6211 DS.UpdateExprRep(Rep: Result.get());
6212 break;
6213 }
6214
6215 default:
6216 // Nothing to do for these decl specs.
6217 break;
6218 }
6219
6220 // It doesn't matter what order we do this in.
6221 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6222 DeclaratorChunk &Chunk = D.getTypeObject(i: I);
6223
6224 // The only type information in the declarator which can come
6225 // before the declaration name is the base type of a member
6226 // pointer.
6227 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6228 continue;
6229
6230 // Rebuild the scope specifier in-place.
6231 CXXScopeSpec &SS = Chunk.Mem.Scope();
6232 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6233 return true;
6234 }
6235
6236 return false;
6237}
6238
6239/// Returns true if the declaration is declared in a system header or from a
6240/// system macro.
6241static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6242 return SM.isInSystemHeader(Loc: D->getLocation()) ||
6243 SM.isInSystemMacro(loc: D->getLocation());
6244}
6245
6246void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6247 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6248 // of system decl.
6249 if (D->getPreviousDecl() || D->isImplicit())
6250 return;
6251 ReservedIdentifierStatus Status = D->isReserved(LangOpts: getLangOpts());
6252 if (Status != ReservedIdentifierStatus::NotReserved &&
6253 !isFromSystemHeader(SM&: Context.getSourceManager(), D)) {
6254 Diag(Loc: D->getLocation(), DiagID: diag::warn_reserved_extern_symbol)
6255 << D << static_cast<int>(Status);
6256 }
6257}
6258
6259Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6260 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6261
6262 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6263 // declaration only if the `bind_to_declaration` extension is set.
6264 SmallVector<FunctionDecl *, 4> Bases;
6265 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6266 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6267 TP: llvm::omp::TraitProperty::
6268 implementation_extension_bind_to_declaration))
6269 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6270 S, D, TemplateParameterLists: MultiTemplateParamsArg(), Bases);
6271
6272 Decl *Dcl = HandleDeclarator(S, D, TemplateParameterLists: MultiTemplateParamsArg());
6273
6274 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6275 Dcl && Dcl->getDeclContext()->isFileContext())
6276 Dcl->setTopLevelDeclInObjCContainer();
6277
6278 if (!Bases.empty())
6279 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
6280 Bases);
6281
6282 return Dcl;
6283}
6284
6285bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6286 DeclarationNameInfo NameInfo) {
6287 DeclarationName Name = NameInfo.getName();
6288
6289 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: DC);
6290 while (Record && Record->isAnonymousStructOrUnion())
6291 Record = dyn_cast<CXXRecordDecl>(Val: Record->getParent());
6292 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6293 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_member_name_of_class) << Name;
6294 return true;
6295 }
6296
6297 return false;
6298}
6299
6300bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6301 DeclarationName Name,
6302 SourceLocation Loc,
6303 TemplateIdAnnotation *TemplateId,
6304 bool IsMemberSpecialization) {
6305 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6306 "without nested-name-specifier");
6307 DeclContext *Cur = CurContext;
6308 while (isa<LinkageSpecDecl>(Val: Cur) || isa<CapturedDecl>(Val: Cur))
6309 Cur = Cur->getParent();
6310
6311 // If the user provided a superfluous scope specifier that refers back to the
6312 // class in which the entity is already declared, diagnose and ignore it.
6313 //
6314 // class X {
6315 // void X::f();
6316 // };
6317 //
6318 // Note, it was once ill-formed to give redundant qualification in all
6319 // contexts, but that rule was removed by DR482.
6320 if (Cur->Equals(DC)) {
6321 if (Cur->isRecord()) {
6322 Diag(Loc, DiagID: LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6323 : diag::err_member_extra_qualification)
6324 << Name << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
6325 SS.clear();
6326 } else {
6327 Diag(Loc, DiagID: diag::warn_namespace_member_extra_qualification) << Name;
6328 }
6329 return false;
6330 }
6331
6332 // Check whether the qualifying scope encloses the scope of the original
6333 // declaration. For a template-id, we perform the checks in
6334 // CheckTemplateSpecializationScope.
6335 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6336 if (Cur->isRecord())
6337 Diag(Loc, DiagID: diag::err_member_qualification)
6338 << Name << SS.getRange();
6339 else if (isa<TranslationUnitDecl>(Val: DC))
6340 Diag(Loc, DiagID: diag::err_invalid_declarator_global_scope)
6341 << Name << SS.getRange();
6342 else if (isa<FunctionDecl>(Val: Cur))
6343 Diag(Loc, DiagID: diag::err_invalid_declarator_in_function)
6344 << Name << SS.getRange();
6345 else if (isa<BlockDecl>(Val: Cur))
6346 Diag(Loc, DiagID: diag::err_invalid_declarator_in_block)
6347 << Name << SS.getRange();
6348 else if (isa<ExportDecl>(Val: Cur)) {
6349 if (!isa<NamespaceDecl>(Val: DC))
6350 Diag(Loc, DiagID: diag::err_export_non_namespace_scope_name)
6351 << Name << SS.getRange();
6352 else
6353 // The cases that DC is not NamespaceDecl should be handled in
6354 // CheckRedeclarationExported.
6355 return false;
6356 } else
6357 Diag(Loc, DiagID: diag::err_invalid_declarator_scope)
6358 << Name << cast<NamedDecl>(Val: Cur) << cast<NamedDecl>(Val: DC) << SS.getRange();
6359
6360 return true;
6361 }
6362
6363 if (Cur->isRecord()) {
6364 // Cannot qualify members within a class.
6365 Diag(Loc, DiagID: diag::err_member_qualification)
6366 << Name << SS.getRange();
6367 SS.clear();
6368
6369 // C++ constructors and destructors with incorrect scopes can break
6370 // our AST invariants by having the wrong underlying types. If
6371 // that's the case, then drop this declaration entirely.
6372 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6373 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6374 !Context.hasSameType(
6375 T1: Name.getCXXNameType(),
6376 T2: Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: Cur))))
6377 return true;
6378
6379 return false;
6380 }
6381
6382 // C++23 [temp.names]p5:
6383 // The keyword template shall not appear immediately after a declarative
6384 // nested-name-specifier.
6385 //
6386 // First check the template-id (if any), and then check each component of the
6387 // nested-name-specifier in reverse order.
6388 //
6389 // FIXME: nested-name-specifiers in friend declarations are declarative,
6390 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6391 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6392 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6393 << FixItHint::CreateRemoval(RemoveRange: TemplateId->TemplateKWLoc);
6394
6395 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6396 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6397 TL = std::exchange(obj&: NextTL, new_val: TypeLoc())) {
6398 SourceLocation TemplateKeywordLoc;
6399 switch (TL.getTypeLocClass()) {
6400 case TypeLoc::TemplateSpecialization: {
6401 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6402 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6403 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6404 Diag(Loc, DiagID: diag::ext_alias_template_in_declarative_nns)
6405 << TST.getLocalSourceRange();
6406 break;
6407 }
6408 case TypeLoc::Decltype:
6409 case TypeLoc::PackIndexing: {
6410 const Type *T = TL.getTypePtr();
6411 // C++23 [expr.prim.id.qual]p2:
6412 // [...] A declarative nested-name-specifier shall not have a
6413 // computed-type-specifier.
6414 //
6415 // CWG2858 changed this from 'decltype-specifier' to
6416 // 'computed-type-specifier'.
6417 Diag(Loc, DiagID: diag::err_computed_type_in_declarative_nns)
6418 << T->isDecltypeType() << TL.getSourceRange();
6419 break;
6420 }
6421 case TypeLoc::DependentName:
6422 NextTL =
6423 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6424 break;
6425 default:
6426 break;
6427 }
6428 if (TemplateKeywordLoc.isValid())
6429 Diag(Loc, DiagID: diag::ext_template_after_declarative_nns)
6430 << FixItHint::CreateRemoval(RemoveRange: TemplateKeywordLoc);
6431 }
6432
6433 return false;
6434}
6435
6436NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6437 MultiTemplateParamsArg TemplateParamLists) {
6438 // TODO: consider using NameInfo for diagnostic.
6439 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6440 DeclarationName Name = NameInfo.getName();
6441
6442 // All of these full declarators require an identifier. If it doesn't have
6443 // one, the ParsedFreeStandingDeclSpec action should be used.
6444 if (D.isDecompositionDeclarator()) {
6445 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6446 } else if (!Name) {
6447 if (!D.isInvalidType()) // Reject this if we think it is valid.
6448 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_declarator_need_ident)
6449 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6450 return nullptr;
6451 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_DeclarationType))
6452 return nullptr;
6453
6454 DeclContext *DC = CurContext;
6455 if (D.getCXXScopeSpec().isInvalid())
6456 D.setInvalidType();
6457 else if (D.getCXXScopeSpec().isSet()) {
6458 if (DiagnoseUnexpandedParameterPack(SS: D.getCXXScopeSpec(),
6459 UPPC: UPPC_DeclarationQualifier))
6460 return nullptr;
6461
6462 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6463 DC = computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext);
6464 if (!DC || isa<EnumDecl>(Val: DC)) {
6465 // If we could not compute the declaration context, it's because the
6466 // declaration context is dependent but does not refer to a class,
6467 // class template, or class template partial specialization. Complain
6468 // and return early, to avoid the coming semantic disaster.
6469 Diag(Loc: D.getIdentifierLoc(),
6470 DiagID: diag::err_template_qualified_declarator_no_match)
6471 << D.getCXXScopeSpec().getScopeRep()
6472 << D.getCXXScopeSpec().getRange();
6473 return nullptr;
6474 }
6475 bool IsDependentContext = DC->isDependentContext();
6476
6477 if (!IsDependentContext &&
6478 RequireCompleteDeclContext(SS&: D.getCXXScopeSpec(), DC))
6479 return nullptr;
6480
6481 // If a class is incomplete, do not parse entities inside it.
6482 if (isa<CXXRecordDecl>(Val: DC) && !cast<CXXRecordDecl>(Val: DC)->hasDefinition()) {
6483 Diag(Loc: D.getIdentifierLoc(),
6484 DiagID: diag::err_member_def_undefined_record)
6485 << Name << DC << D.getCXXScopeSpec().getRange();
6486 return nullptr;
6487 }
6488 if (!D.getDeclSpec().isFriendSpecified()) {
6489 TemplateIdAnnotation *TemplateId =
6490 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6491 ? D.getName().TemplateId
6492 : nullptr;
6493 if (diagnoseQualifiedDeclaration(SS&: D.getCXXScopeSpec(), DC, Name,
6494 Loc: D.getIdentifierLoc(), TemplateId,
6495 /*IsMemberSpecialization=*/false)) {
6496 if (DC->isRecord())
6497 return nullptr;
6498
6499 D.setInvalidType();
6500 }
6501 }
6502
6503 // Check whether we need to rebuild the type of the given
6504 // declaration in the current instantiation.
6505 if (EnteringContext && IsDependentContext &&
6506 TemplateParamLists.size() != 0) {
6507 ContextRAII SavedContext(*this, DC);
6508 if (RebuildDeclaratorInCurrentInstantiation(S&: *this, D, Name))
6509 D.setInvalidType();
6510 }
6511 }
6512
6513 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6514 QualType R = TInfo->getType();
6515
6516 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
6517 UPPC: UPPC_DeclarationType))
6518 D.setInvalidType();
6519
6520 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6521 forRedeclarationInCurContext());
6522
6523 // See if this is a redefinition of a variable in the same scope.
6524 if (!D.getCXXScopeSpec().isSet()) {
6525 bool IsLinkageLookup = false;
6526 bool CreateBuiltins = false;
6527
6528 // If the declaration we're planning to build will be a function
6529 // or object with linkage, then look for another declaration with
6530 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6531 //
6532 // If the declaration we're planning to build will be declared with
6533 // external linkage in the translation unit, create any builtin with
6534 // the same name.
6535 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6536 /* Do nothing*/;
6537 else if (CurContext->isFunctionOrMethod() &&
6538 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6539 R->isFunctionType())) {
6540 IsLinkageLookup = true;
6541 CreateBuiltins =
6542 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6543 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6544 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6545 CreateBuiltins = true;
6546
6547 if (IsLinkageLookup) {
6548 Previous.clear(Kind: LookupRedeclarationWithLinkage);
6549 Previous.setRedeclarationKind(
6550 RedeclarationKind::ForExternalRedeclaration);
6551 }
6552
6553 LookupName(R&: Previous, S, AllowBuiltinCreation: CreateBuiltins);
6554 } else { // Something like "int foo::x;"
6555 LookupQualifiedName(R&: Previous, LookupCtx: DC);
6556
6557 // C++ [dcl.meaning]p1:
6558 // When the declarator-id is qualified, the declaration shall refer to a
6559 // previously declared member of the class or namespace to which the
6560 // qualifier refers (or, in the case of a namespace, of an element of the
6561 // inline namespace set of that namespace (7.3.1)) or to a specialization
6562 // thereof; [...]
6563 //
6564 // Note that we already checked the context above, and that we do not have
6565 // enough information to make sure that Previous contains the declaration
6566 // we want to match. For example, given:
6567 //
6568 // class X {
6569 // void f();
6570 // void f(float);
6571 // };
6572 //
6573 // void X::f(int) { } // ill-formed
6574 //
6575 // In this case, Previous will point to the overload set
6576 // containing the two f's declared in X, but neither of them
6577 // matches.
6578
6579 RemoveUsingDecls(R&: Previous);
6580 }
6581
6582 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6583 TPD && TPD->isTemplateParameter()) {
6584 // Older versions of clang allowed the names of function/variable templates
6585 // to shadow the names of their template parameters. For the compatibility
6586 // purposes we detect such cases and issue a default-to-error warning that
6587 // can be disabled with -Wno-strict-primary-template-shadow.
6588 if (!D.isInvalidType()) {
6589 bool AllowForCompatibility = false;
6590 if (Scope *DeclParent = S->getDeclParent();
6591 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6592 AllowForCompatibility = DeclParent->Contains(rhs: *TemplateParamParent) &&
6593 TemplateParamParent->isDeclScope(D: TPD);
6594 }
6595 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl: TPD,
6596 SupportedForCompatibility: AllowForCompatibility);
6597 }
6598
6599 // Just pretend that we didn't see the previous declaration.
6600 Previous.clear();
6601 }
6602
6603 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6604 // Forget that the previous declaration is the injected-class-name.
6605 Previous.clear();
6606
6607 // In C++, the previous declaration we find might be a tag type
6608 // (class or enum). In this case, the new declaration will hide the
6609 // tag type. Note that this applies to functions, function templates, and
6610 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6611 if (Previous.isSingleTagDecl() &&
6612 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6613 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6614 Previous.clear();
6615
6616 // Check that there are no default arguments other than in the parameters
6617 // of a function declaration (C++ only).
6618 if (getLangOpts().CPlusPlus)
6619 CheckExtraCXXDefaultArguments(D);
6620
6621 /// Get the innermost enclosing declaration scope.
6622 S = S->getDeclParent();
6623
6624 NamedDecl *New;
6625
6626 bool AddToScope = true;
6627 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6628 if (TemplateParamLists.size()) {
6629 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_typedef);
6630 return nullptr;
6631 }
6632
6633 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6634 } else if (R->isFunctionType()) {
6635 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6636 TemplateParamLists,
6637 AddToScope);
6638 } else {
6639 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6640 AddToScope);
6641 }
6642
6643 if (!New)
6644 return nullptr;
6645
6646 warnOnCTypeHiddenInCPlusPlus(D: New);
6647
6648 // If this has an identifier and is not a function template specialization,
6649 // add it to the scope stack.
6650 if (New->getDeclName() && AddToScope)
6651 PushOnScopeChains(D: New, S);
6652
6653 if (OpenMP().isInOpenMPDeclareTargetContext())
6654 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
6655
6656 return New;
6657}
6658
6659/// Helper method to turn variable array types into constant array
6660/// types in certain situations which would otherwise be errors (for
6661/// GCC compatibility).
6662static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6663 ASTContext &Context,
6664 bool &SizeIsNegative,
6665 llvm::APSInt &Oversized) {
6666 // This method tries to turn a variable array into a constant
6667 // array even when the size isn't an ICE. This is necessary
6668 // for compatibility with code that depends on gcc's buggy
6669 // constant expression folding, like struct {char x[(int)(char*)2];}
6670 SizeIsNegative = false;
6671 Oversized = 0;
6672
6673 if (T->isDependentType())
6674 return QualType();
6675
6676 QualifierCollector Qs;
6677 const Type *Ty = Qs.strip(type: T);
6678
6679 if (const PointerType* PTy = dyn_cast<PointerType>(Val: Ty)) {
6680 QualType Pointee = PTy->getPointeeType();
6681 QualType FixedType =
6682 TryToFixInvalidVariablyModifiedType(T: Pointee, Context, SizeIsNegative,
6683 Oversized);
6684 if (FixedType.isNull()) return FixedType;
6685 FixedType = Context.getPointerType(T: FixedType);
6686 return Qs.apply(Context, QT: FixedType);
6687 }
6688 if (const ParenType* PTy = dyn_cast<ParenType>(Val: Ty)) {
6689 QualType Inner = PTy->getInnerType();
6690 QualType FixedType =
6691 TryToFixInvalidVariablyModifiedType(T: Inner, Context, SizeIsNegative,
6692 Oversized);
6693 if (FixedType.isNull()) return FixedType;
6694 FixedType = Context.getParenType(NamedType: FixedType);
6695 return Qs.apply(Context, QT: FixedType);
6696 }
6697
6698 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(Val&: T);
6699 if (!VLATy)
6700 return QualType();
6701
6702 QualType ElemTy = VLATy->getElementType();
6703 if (ElemTy->isVariablyModifiedType()) {
6704 ElemTy = TryToFixInvalidVariablyModifiedType(T: ElemTy, Context,
6705 SizeIsNegative, Oversized);
6706 if (ElemTy.isNull())
6707 return QualType();
6708 }
6709
6710 Expr::EvalResult Result;
6711 if (!VLATy->getSizeExpr() ||
6712 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Ctx: Context))
6713 return QualType();
6714
6715 llvm::APSInt Res = Result.Val.getInt();
6716
6717 // Check whether the array size is negative.
6718 if (Res.isSigned() && Res.isNegative()) {
6719 SizeIsNegative = true;
6720 return QualType();
6721 }
6722
6723 // Check whether the array is too large to be addressed.
6724 unsigned ActiveSizeBits =
6725 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6726 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6727 ? ConstantArrayType::getNumAddressingBits(Context, ElementType: ElemTy, NumElements: Res)
6728 : Res.getActiveBits();
6729 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6730 Oversized = Res;
6731 return QualType();
6732 }
6733
6734 QualType FoldedArrayType = Context.getConstantArrayType(
6735 EltTy: ElemTy, ArySize: Res, SizeExpr: VLATy->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6736 return Qs.apply(Context, QT: FoldedArrayType);
6737}
6738
6739static void
6740FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6741 SrcTL = SrcTL.getUnqualifiedLoc();
6742 DstTL = DstTL.getUnqualifiedLoc();
6743 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6744 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6745 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getPointeeLoc(),
6746 DstTL: DstPTL.getPointeeLoc());
6747 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6748 return;
6749 }
6750 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6751 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6752 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcPTL.getInnerLoc(),
6753 DstTL: DstPTL.getInnerLoc());
6754 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6755 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6756 return;
6757 }
6758 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6759 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6760 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6761 TypeLoc DstElemTL = DstATL.getElementLoc();
6762 if (VariableArrayTypeLoc SrcElemATL =
6763 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6764 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6765 FixInvalidVariablyModifiedTypeLoc(SrcTL: SrcElemATL, DstTL: DstElemATL);
6766 } else {
6767 DstElemTL.initializeFullCopy(Other: SrcElemTL);
6768 }
6769 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6770 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6771 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6772}
6773
6774/// Helper method to turn variable array types into constant array
6775/// types in certain situations which would otherwise be errors (for
6776/// GCC compatibility).
6777static TypeSourceInfo*
6778TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6779 ASTContext &Context,
6780 bool &SizeIsNegative,
6781 llvm::APSInt &Oversized) {
6782 QualType FixedTy
6783 = TryToFixInvalidVariablyModifiedType(T: TInfo->getType(), Context,
6784 SizeIsNegative, Oversized);
6785 if (FixedTy.isNull())
6786 return nullptr;
6787 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(T: FixedTy);
6788 FixInvalidVariablyModifiedTypeLoc(SrcTL: TInfo->getTypeLoc(),
6789 DstTL: FixedTInfo->getTypeLoc());
6790 return FixedTInfo;
6791}
6792
6793bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6794 QualType &T, SourceLocation Loc,
6795 unsigned FailedFoldDiagID) {
6796 bool SizeIsNegative;
6797 llvm::APSInt Oversized;
6798 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6799 TInfo, Context, SizeIsNegative, Oversized);
6800 if (FixedTInfo) {
6801 Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
6802 TInfo = FixedTInfo;
6803 T = FixedTInfo->getType();
6804 return true;
6805 }
6806
6807 if (SizeIsNegative)
6808 Diag(Loc, DiagID: diag::err_typecheck_negative_array_size);
6809 else if (Oversized.getBoolValue())
6810 Diag(Loc, DiagID: diag::err_array_too_large) << toString(
6811 I: Oversized, Radix: 10, Signed: Oversized.isSigned(), /*formatAsCLiteral=*/false,
6812 /*UpperCase=*/false, /*InsertSeparators=*/true);
6813 else if (FailedFoldDiagID)
6814 Diag(Loc, DiagID: FailedFoldDiagID);
6815 return false;
6816}
6817
6818void
6819Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6820 if (!getLangOpts().CPlusPlus &&
6821 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6822 // Don't need to track declarations in the TU in C.
6823 return;
6824
6825 // Note that we have a locally-scoped external with this name.
6826 Context.getExternCContextDecl()->makeDeclVisibleInContext(D: ND);
6827}
6828
6829NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6830 // FIXME: We can have multiple results via __attribute__((overloadable)).
6831 auto Result = Context.getExternCContextDecl()->lookup(Name);
6832 return Result.empty() ? nullptr : *Result.begin();
6833}
6834
6835void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6836 // FIXME: We should probably indicate the identifier in question to avoid
6837 // confusion for constructs like "virtual int a(), b;"
6838 if (DS.isVirtualSpecified())
6839 Diag(Loc: DS.getVirtualSpecLoc(),
6840 DiagID: diag::err_virtual_non_function);
6841
6842 if (DS.hasExplicitSpecifier())
6843 Diag(Loc: DS.getExplicitSpecLoc(),
6844 DiagID: diag::err_explicit_non_function);
6845
6846 if (DS.isNoreturnSpecified())
6847 Diag(Loc: DS.getNoreturnSpecLoc(),
6848 DiagID: diag::err_noreturn_non_function);
6849}
6850
6851NamedDecl*
6852Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6853 TypeSourceInfo *TInfo, LookupResult &Previous) {
6854 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6855 if (D.getCXXScopeSpec().isSet()) {
6856 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_typedef_declarator)
6857 << D.getCXXScopeSpec().getRange();
6858 D.setInvalidType();
6859 // Pretend we didn't see the scope specifier.
6860 DC = CurContext;
6861 Previous.clear();
6862 }
6863
6864 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
6865
6866 if (D.getDeclSpec().isInlineSpecified())
6867 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
6868 DiagID: (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6869 ? diag::warn_ms_inline_non_function
6870 : diag::err_inline_non_function)
6871 << getLangOpts().CPlusPlus17;
6872 if (D.getDeclSpec().hasConstexprSpecifier())
6873 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
6874 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6875
6876 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6877 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6878 Diag(Loc: D.getName().StartLocation,
6879 DiagID: diag::err_deduction_guide_invalid_specifier)
6880 << "typedef";
6881 else
6882 Diag(Loc: D.getName().StartLocation, DiagID: diag::err_typedef_not_identifier)
6883 << D.getName().getSourceRange();
6884 return nullptr;
6885 }
6886
6887 TypedefDecl *NewTD = ParseTypedefDecl(S, D, T: TInfo->getType(), TInfo);
6888 if (!NewTD) return nullptr;
6889
6890 // Handle attributes prior to checking for duplicates in MergeVarDecl
6891 ProcessDeclAttributes(S, D: NewTD, PD: D);
6892
6893 CheckTypedefForVariablyModifiedType(S, D: NewTD);
6894
6895 bool Redeclaration = D.isRedeclaration();
6896 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, D: NewTD, Previous, Redeclaration);
6897 D.setRedeclaration(Redeclaration);
6898 return ND;
6899}
6900
6901void
6902Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6903 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6904 // then it shall have block scope.
6905 // Note that variably modified types must be fixed before merging the decl so
6906 // that redeclarations will match.
6907 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6908 QualType T = TInfo->getType();
6909 if (T->isVariablyModifiedType()) {
6910 setFunctionHasBranchProtectedScope();
6911
6912 if (S->getFnParent() == nullptr) {
6913 bool SizeIsNegative;
6914 llvm::APSInt Oversized;
6915 TypeSourceInfo *FixedTInfo =
6916 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6917 SizeIsNegative,
6918 Oversized);
6919 if (FixedTInfo) {
6920 Diag(Loc: NewTD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
6921 NewTD->setTypeSourceInfo(FixedTInfo);
6922 } else {
6923 if (SizeIsNegative)
6924 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_typecheck_negative_array_size);
6925 else if (T->isVariableArrayType())
6926 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope);
6927 else if (Oversized.getBoolValue())
6928 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_array_too_large)
6929 << toString(I: Oversized, Radix: 10);
6930 else
6931 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
6932 NewTD->setInvalidDecl();
6933 }
6934 }
6935 }
6936}
6937
6938NamedDecl*
6939Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6940 LookupResult &Previous, bool &Redeclaration) {
6941
6942 // Find the shadowed declaration before filtering for scope.
6943 NamedDecl *ShadowedDecl = getShadowedDeclaration(D: NewTD, R: Previous);
6944
6945 // Merge the decl with the existing one if appropriate. If the decl is
6946 // in an outer scope, it isn't the same thing.
6947 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage*/false,
6948 /*AllowInlineNamespace*/false);
6949 filterNonConflictingPreviousTypedefDecls(S&: *this, Decl: NewTD, Previous);
6950 if (!Previous.empty()) {
6951 Redeclaration = true;
6952 MergeTypedefNameDecl(S, New: NewTD, OldDecls&: Previous);
6953 } else {
6954 inferGslPointerAttribute(TD: NewTD);
6955 }
6956
6957 if (ShadowedDecl && !Redeclaration)
6958 CheckShadow(D: NewTD, ShadowedDecl, R: Previous);
6959
6960 // If this is the C FILE type, notify the AST context.
6961 if (IdentifierInfo *II = NewTD->getIdentifier())
6962 if (!NewTD->isInvalidDecl() &&
6963 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6964 switch (II->getNotableIdentifierID()) {
6965 case tok::NotableIdentifierKind::FILE:
6966 Context.setFILEDecl(NewTD);
6967 break;
6968 case tok::NotableIdentifierKind::jmp_buf:
6969 Context.setjmp_bufDecl(NewTD);
6970 break;
6971 case tok::NotableIdentifierKind::sigjmp_buf:
6972 Context.setsigjmp_bufDecl(NewTD);
6973 break;
6974 case tok::NotableIdentifierKind::ucontext_t:
6975 Context.setucontext_tDecl(NewTD);
6976 break;
6977 case tok::NotableIdentifierKind::float_t:
6978 case tok::NotableIdentifierKind::double_t:
6979 NewTD->addAttr(A: AvailableOnlyInDefaultEvalMethodAttr::Create(Ctx&: Context));
6980 break;
6981 default:
6982 break;
6983 }
6984 }
6985
6986 return NewTD;
6987}
6988
6989/// Determines whether the given declaration is an out-of-scope
6990/// previous declaration.
6991///
6992/// This routine should be invoked when name lookup has found a
6993/// previous declaration (PrevDecl) that is not in the scope where a
6994/// new declaration by the same name is being introduced. If the new
6995/// declaration occurs in a local scope, previous declarations with
6996/// linkage may still be considered previous declarations (C99
6997/// 6.2.2p4-5, C++ [basic.link]p6).
6998///
6999/// \param PrevDecl the previous declaration found by name
7000/// lookup
7001///
7002/// \param DC the context in which the new declaration is being
7003/// declared.
7004///
7005/// \returns true if PrevDecl is an out-of-scope previous declaration
7006/// for a new delcaration with the same name.
7007static bool
7008isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
7009 ASTContext &Context) {
7010 if (!PrevDecl)
7011 return false;
7012
7013 if (!PrevDecl->hasLinkage())
7014 return false;
7015
7016 if (Context.getLangOpts().CPlusPlus) {
7017 // C++ [basic.link]p6:
7018 // If there is a visible declaration of an entity with linkage
7019 // having the same name and type, ignoring entities declared
7020 // outside the innermost enclosing namespace scope, the block
7021 // scope declaration declares that same entity and receives the
7022 // linkage of the previous declaration.
7023 DeclContext *OuterContext = DC->getRedeclContext();
7024 if (!OuterContext->isFunctionOrMethod())
7025 // This rule only applies to block-scope declarations.
7026 return false;
7027
7028 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7029 if (PrevOuterContext->isRecord())
7030 // We found a member function: ignore it.
7031 return false;
7032
7033 // Find the innermost enclosing namespace for the new and
7034 // previous declarations.
7035 OuterContext = OuterContext->getEnclosingNamespaceContext();
7036 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7037
7038 // The previous declaration is in a different namespace, so it
7039 // isn't the same function.
7040 if (!OuterContext->Equals(DC: PrevOuterContext))
7041 return false;
7042 }
7043
7044 return true;
7045}
7046
7047static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
7048 CXXScopeSpec &SS = D.getCXXScopeSpec();
7049 if (!SS.isSet()) return;
7050 DD->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
7051}
7052
7053void Sema::deduceOpenCLAddressSpace(VarDecl *Var) {
7054 QualType Type = Var->getType();
7055 if (Type.hasAddressSpace())
7056 return;
7057 if (Type->isDependentType())
7058 return;
7059 if (Type->isSamplerT() || Type->isVoidType())
7060 return;
7061 LangAS ImplAS = LangAS::opencl_private;
7062 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7063 // __opencl_c_program_scope_global_variables feature, the address space
7064 // for a variable at program scope or a static or extern variable inside
7065 // a function are inferred to be __global.
7066 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()) &&
7067 Var->hasGlobalStorage())
7068 ImplAS = LangAS::opencl_global;
7069 // If the original type from a decayed type is an array type and that array
7070 // type has no address space yet, deduce it now.
7071 if (auto DT = dyn_cast<DecayedType>(Val&: Type)) {
7072 auto OrigTy = DT->getOriginalType();
7073 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7074 // Add the address space to the original array type and then propagate
7075 // that to the element type through `getAsArrayType`.
7076 OrigTy = Context.getAddrSpaceQualType(T: OrigTy, AddressSpace: ImplAS);
7077 OrigTy = QualType(Context.getAsArrayType(T: OrigTy), 0);
7078 // Re-generate the decayed type.
7079 Type = Context.getDecayedType(T: OrigTy);
7080 }
7081 }
7082 Type = Context.getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
7083 // Apply any qualifiers (including address space) from the array type to
7084 // the element type. This implements C99 6.7.3p8: "If the specification of
7085 // an array type includes any type qualifiers, the element type is so
7086 // qualified, not the array type."
7087 if (Type->isArrayType())
7088 Type = QualType(Context.getAsArrayType(T: Type), 0);
7089 Var->setType(Type);
7090}
7091
7092static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7093 // 'weak' only applies to declarations with external linkage.
7094 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7095 if (!ND.isExternallyVisible()) {
7096 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weak_static);
7097 ND.dropAttr<WeakAttr>();
7098 }
7099 }
7100}
7101
7102static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7103 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7104 if (ND.isExternallyVisible()) {
7105 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_attribute_weakref_not_static);
7106 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7107 }
7108 }
7109}
7110
7111static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7112 if (auto *VD = dyn_cast<VarDecl>(Val: &ND)) {
7113 if (VD->hasInit()) {
7114 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7115 assert(VD->isThisDeclarationADefinition() &&
7116 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7117 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << VD << 0;
7118 VD->dropAttr<AliasAttr>();
7119 }
7120 }
7121 }
7122}
7123
7124static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7125 // 'selectany' only applies to externally visible variable declarations.
7126 // It does not apply to functions.
7127 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7128 if (isa<FunctionDecl>(Val: ND) || !ND.isExternallyVisible()) {
7129 S.Diag(Loc: Attr->getLocation(),
7130 DiagID: diag::err_attribute_selectany_non_extern_data);
7131 ND.dropAttr<SelectAnyAttr>();
7132 }
7133 }
7134}
7135
7136static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND) {
7137 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7138 if (!ND.isExternallyVisible())
7139 S.Diag(Loc: Attr->getLocation(),
7140 DiagID: diag::warn_attribute_hybrid_patchable_non_extern);
7141 }
7142}
7143
7144static void checkInheritableAttr(Sema &S, NamedDecl &ND) {
7145 if (const InheritableAttr *Attr = getDLLAttr(D: &ND)) {
7146 auto *VD = dyn_cast<VarDecl>(Val: &ND);
7147 bool IsAnonymousNS = false;
7148 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7149 if (VD) {
7150 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: VD->getDeclContext());
7151 while (NS && !IsAnonymousNS) {
7152 IsAnonymousNS = NS->isAnonymousNamespace();
7153 NS = dyn_cast<NamespaceDecl>(Val: NS->getParent());
7154 }
7155 }
7156 // dll attributes require external linkage. Static locals may have external
7157 // linkage but still cannot be explicitly imported or exported.
7158 // In Microsoft mode, a variable defined in anonymous namespace must have
7159 // external linkage in order to be exported.
7160 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7161 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7162 (!AnonNSInMicrosoftMode &&
7163 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7164 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_attribute_dll_not_extern)
7165 << &ND << Attr;
7166 ND.setInvalidDecl();
7167 }
7168 }
7169}
7170
7171static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND) {
7172 // Check the attributes on the function type and function params, if any.
7173 if (const auto *FD = dyn_cast<FunctionDecl>(Val: &ND)) {
7174 FD = FD->getMostRecentDecl();
7175 // Don't declare this variable in the second operand of the for-statement;
7176 // GCC miscompiles that by ending its lifetime before evaluating the
7177 // third operand. See gcc.gnu.org/PR86769.
7178 AttributedTypeLoc ATL;
7179 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7180 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7181 TL = ATL.getModifiedLoc()) {
7182 // The [[lifetimebound]] attribute can be applied to the implicit object
7183 // parameter of a non-static member function (other than a ctor or dtor)
7184 // by applying it to the function type.
7185 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7186 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
7187 int NoImplicitObjectError = -1;
7188 if (!MD)
7189 NoImplicitObjectError = 0;
7190 else if (MD->isStatic())
7191 NoImplicitObjectError = 1;
7192 else if (MD->isExplicitObjectMemberFunction())
7193 NoImplicitObjectError = 2;
7194 if (NoImplicitObjectError != -1) {
7195 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_no_object_param)
7196 << NoImplicitObjectError << A->getRange();
7197 } else if (isa<CXXConstructorDecl>(Val: MD) || isa<CXXDestructorDecl>(Val: MD)) {
7198 S.Diag(Loc: A->getLocation(), DiagID: diag::err_lifetimebound_ctor_dtor)
7199 << isa<CXXDestructorDecl>(Val: MD) << A->getRange();
7200 } else if (MD->getReturnType()->isVoidType()) {
7201 S.Diag(
7202 Loc: MD->getLocation(),
7203 DiagID: diag::
7204 err_lifetimebound_implicit_object_parameter_void_return_type);
7205 }
7206 }
7207 }
7208
7209 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7210 const ParmVarDecl *P = FD->getParamDecl(i: I);
7211
7212 // The [[lifetimebound]] attribute can be applied to a function parameter
7213 // only if the function returns a value.
7214 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7215 if (!isa<CXXConstructorDecl>(Val: FD) && FD->getReturnType()->isVoidType()) {
7216 S.Diag(Loc: A->getLocation(),
7217 DiagID: diag::err_lifetimebound_parameter_void_return_type);
7218 }
7219 }
7220 }
7221 }
7222}
7223
7224static void checkModularFormatAttr(Sema &S, NamedDecl &ND) {
7225 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7226 S.Diag(Loc: ND.getLocation(), DiagID: diag::err_modular_format_attribute_no_format);
7227}
7228
7229static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7230 // Ensure that an auto decl is deduced otherwise the checks below might cache
7231 // the wrong linkage.
7232 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7233
7234 checkWeakAttr(S, ND);
7235 checkWeakRefAttr(S, ND);
7236 checkAliasAttr(S, ND);
7237 checkSelectAnyAttr(S, ND);
7238 checkHybridPatchableAttr(S, ND);
7239 checkInheritableAttr(S, ND);
7240 checkLifetimeBoundAttr(S, ND);
7241 checkModularFormatAttr(S, ND);
7242}
7243
7244static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7245 NamedDecl *NewDecl,
7246 bool IsSpecialization,
7247 bool IsDefinition) {
7248 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7249 return;
7250
7251 bool IsTemplate = false;
7252 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(Val: OldDecl)) {
7253 OldDecl = OldTD->getTemplatedDecl();
7254 IsTemplate = true;
7255 if (!IsSpecialization)
7256 IsDefinition = false;
7257 }
7258 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(Val: NewDecl)) {
7259 NewDecl = NewTD->getTemplatedDecl();
7260 IsTemplate = true;
7261 }
7262
7263 if (!OldDecl || !NewDecl)
7264 return;
7265
7266 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7267 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7268 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7269 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7270
7271 // dllimport and dllexport are inheritable attributes so we have to exclude
7272 // inherited attribute instances.
7273 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7274 (NewExportAttr && !NewExportAttr->isInherited());
7275
7276 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7277 // the only exception being explicit specializations.
7278 // Implicitly generated declarations are also excluded for now because there
7279 // is no other way to switch these to use dllimport or dllexport.
7280 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7281
7282 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7283 // Allow with a warning for free functions and global variables.
7284 bool JustWarn = false;
7285 if (!OldDecl->isCXXClassMember()) {
7286 auto *VD = dyn_cast<VarDecl>(Val: OldDecl);
7287 if (VD && !VD->getDescribedVarTemplate())
7288 JustWarn = true;
7289 auto *FD = dyn_cast<FunctionDecl>(Val: OldDecl);
7290 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7291 JustWarn = true;
7292 }
7293
7294 // We cannot change a declaration that's been used because IR has already
7295 // been emitted. Dllimported functions will still work though (modulo
7296 // address equality) as they can use the thunk.
7297 if (OldDecl->isUsed())
7298 if (!isa<FunctionDecl>(Val: OldDecl) || !NewImportAttr)
7299 JustWarn = false;
7300
7301 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7302 : diag::err_attribute_dll_redeclaration;
7303 S.Diag(Loc: NewDecl->getLocation(), DiagID)
7304 << NewDecl
7305 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7306 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7307 if (!JustWarn) {
7308 NewDecl->setInvalidDecl();
7309 return;
7310 }
7311 }
7312
7313 // A redeclaration is not allowed to drop a dllimport attribute, the only
7314 // exceptions being inline function definitions (except for function
7315 // templates), local extern declarations, qualified friend declarations or
7316 // special MSVC extension: in the last case, the declaration is treated as if
7317 // it were marked dllexport.
7318 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7319 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7320 if (const auto *VD = dyn_cast<VarDecl>(Val: NewDecl)) {
7321 // Ignore static data because out-of-line definitions are diagnosed
7322 // separately.
7323 IsStaticDataMember = VD->isStaticDataMember();
7324 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7325 VarDecl::DeclarationOnly;
7326 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: NewDecl)) {
7327 IsInline = FD->isInlined();
7328 IsQualifiedFriend = FD->getQualifier() &&
7329 FD->getFriendObjectKind() == Decl::FOK_Declared;
7330 }
7331
7332 if (OldImportAttr && !HasNewAttr &&
7333 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7334 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7335 if (IsMicrosoftABI && IsDefinition) {
7336 if (IsSpecialization) {
7337 S.Diag(
7338 Loc: NewDecl->getLocation(),
7339 DiagID: diag::err_attribute_dllimport_function_specialization_definition);
7340 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_attribute);
7341 NewDecl->dropAttr<DLLImportAttr>();
7342 } else {
7343 S.Diag(Loc: NewDecl->getLocation(),
7344 DiagID: diag::warn_redeclaration_without_import_attribute)
7345 << NewDecl;
7346 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7347 NewDecl->dropAttr<DLLImportAttr>();
7348 NewDecl->addAttr(A: DLLExportAttr::CreateImplicit(
7349 Ctx&: S.Context, Range: NewImportAttr->getRange()));
7350 }
7351 } else if (IsMicrosoftABI && IsSpecialization) {
7352 assert(!IsDefinition);
7353 // MSVC allows this. Keep the inherited attribute.
7354 } else {
7355 S.Diag(Loc: NewDecl->getLocation(),
7356 DiagID: diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7357 << NewDecl << OldImportAttr;
7358 S.Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_previous_declaration);
7359 S.Diag(Loc: OldImportAttr->getLocation(), DiagID: diag::note_previous_attribute);
7360 OldDecl->dropAttr<DLLImportAttr>();
7361 NewDecl->dropAttr<DLLImportAttr>();
7362 }
7363 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7364 // In MinGW, seeing a function declared inline drops the dllimport
7365 // attribute.
7366 OldDecl->dropAttr<DLLImportAttr>();
7367 NewDecl->dropAttr<DLLImportAttr>();
7368 S.Diag(Loc: NewDecl->getLocation(),
7369 DiagID: diag::warn_dllimport_dropped_from_inline_function)
7370 << NewDecl << OldImportAttr;
7371 }
7372
7373 // A specialization of a class template member function is processed here
7374 // since it's a redeclaration. If the parent class is dllexport, the
7375 // specialization inherits that attribute. This doesn't happen automatically
7376 // since the parent class isn't instantiated until later.
7377 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewDecl)) {
7378 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7379 !NewImportAttr && !NewExportAttr) {
7380 if (const DLLExportAttr *ParentExportAttr =
7381 MD->getParent()->getAttr<DLLExportAttr>()) {
7382 DLLExportAttr *NewAttr = ParentExportAttr->clone(C&: S.Context);
7383 NewAttr->setInherited(true);
7384 NewDecl->addAttr(A: NewAttr);
7385 }
7386 }
7387 }
7388}
7389
7390/// Given that we are within the definition of the given function,
7391/// will that definition behave like C99's 'inline', where the
7392/// definition is discarded except for optimization purposes?
7393static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7394 // Try to avoid calling GetGVALinkageForFunction.
7395
7396 // All cases of this require the 'inline' keyword.
7397 if (!FD->isInlined()) return false;
7398
7399 // This is only possible in C++ with the gnu_inline attribute.
7400 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7401 return false;
7402
7403 // Okay, go ahead and call the relatively-more-expensive function.
7404 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7405}
7406
7407/// Determine whether a variable is extern "C" prior to attaching
7408/// an initializer. We can't just call isExternC() here, because that
7409/// will also compute and cache whether the declaration is externally
7410/// visible, which might change when we attach the initializer.
7411///
7412/// This can only be used if the declaration is known to not be a
7413/// redeclaration of an internal linkage declaration.
7414///
7415/// For instance:
7416///
7417/// auto x = []{};
7418///
7419/// Attaching the initializer here makes this declaration not externally
7420/// visible, because its type has internal linkage.
7421///
7422/// FIXME: This is a hack.
7423template<typename T>
7424static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7425 if (S.getLangOpts().CPlusPlus) {
7426 // In C++, the overloadable attribute negates the effects of extern "C".
7427 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7428 return false;
7429
7430 // So do CUDA's host/device attributes.
7431 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7432 D->template hasAttr<CUDAHostAttr>()))
7433 return false;
7434 }
7435 return D->isExternC();
7436}
7437
7438static bool shouldConsiderLinkage(const VarDecl *VD) {
7439 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7440 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(Val: DC) ||
7441 isa<OMPDeclareMapperDecl>(Val: DC))
7442 return VD->hasExternalStorage();
7443 if (DC->isFileContext())
7444 return true;
7445 if (DC->isRecord())
7446 return false;
7447 if (DC->getDeclKind() == Decl::HLSLBuffer)
7448 return false;
7449
7450 if (isa<RequiresExprBodyDecl>(Val: DC))
7451 return false;
7452 llvm_unreachable("Unexpected context");
7453}
7454
7455static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7456 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7457 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7458 isa<OMPDeclareReductionDecl>(Val: DC) || isa<OMPDeclareMapperDecl>(Val: DC))
7459 return true;
7460 if (DC->isRecord())
7461 return false;
7462 llvm_unreachable("Unexpected context");
7463}
7464
7465static bool hasParsedAttr(Scope *S, const Declarator &PD,
7466 ParsedAttr::Kind Kind) {
7467 // Check decl attributes on the DeclSpec.
7468 if (PD.getDeclSpec().getAttributes().hasAttribute(K: Kind))
7469 return true;
7470
7471 // Walk the declarator structure, checking decl attributes that were in a type
7472 // position to the decl itself.
7473 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7474 if (PD.getTypeObject(i: I).getAttrs().hasAttribute(K: Kind))
7475 return true;
7476 }
7477
7478 // Finally, check attributes on the decl itself.
7479 return PD.getAttributes().hasAttribute(K: Kind) ||
7480 PD.getDeclarationAttributes().hasAttribute(K: Kind);
7481}
7482
7483bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7484 if (!DC->isFunctionOrMethod())
7485 return false;
7486
7487 // If this is a local extern function or variable declared within a function
7488 // template, don't add it into the enclosing namespace scope until it is
7489 // instantiated; it might have a dependent type right now.
7490 if (DC->isDependentContext())
7491 return true;
7492
7493 // C++11 [basic.link]p7:
7494 // When a block scope declaration of an entity with linkage is not found to
7495 // refer to some other declaration, then that entity is a member of the
7496 // innermost enclosing namespace.
7497 //
7498 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7499 // semantically-enclosing namespace, not a lexically-enclosing one.
7500 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(Val: DC))
7501 DC = DC->getParent();
7502 return true;
7503}
7504
7505/// Returns true if given declaration has external C language linkage.
7506static bool isDeclExternC(const Decl *D) {
7507 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
7508 return FD->isExternC();
7509 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
7510 return VD->isExternC();
7511
7512 llvm_unreachable("Unknown type of decl!");
7513}
7514
7515/// Returns true if there hasn't been any invalid type diagnosed.
7516static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7517 DeclContext *DC = NewVD->getDeclContext();
7518 QualType R = NewVD->getType();
7519
7520 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7521 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7522 // argument.
7523 if (R->isImageType() || R->isPipeType()) {
7524 Se.Diag(Loc: NewVD->getLocation(),
7525 DiagID: diag::err_opencl_type_can_only_be_used_as_function_parameter)
7526 << R;
7527 NewVD->setInvalidDecl();
7528 return false;
7529 }
7530
7531 // OpenCL v1.2 s6.9.r:
7532 // The event type cannot be used to declare a program scope variable.
7533 // OpenCL v2.0 s6.9.q:
7534 // The clk_event_t and reserve_id_t types cannot be declared in program
7535 // scope.
7536 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7537 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7538 Se.Diag(Loc: NewVD->getLocation(),
7539 DiagID: diag::err_invalid_type_for_program_scope_var)
7540 << R;
7541 NewVD->setInvalidDecl();
7542 return false;
7543 }
7544 }
7545
7546 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7547 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
7548 LO: Se.getLangOpts())) {
7549 QualType NR = R.getCanonicalType();
7550 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7551 NR->isReferenceType()) {
7552 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7553 NR->isFunctionReferenceType()) {
7554 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_pointer)
7555 << NR->isReferenceType();
7556 NewVD->setInvalidDecl();
7557 return false;
7558 }
7559 NR = NR->getPointeeType();
7560 }
7561 }
7562
7563 if (!Se.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
7564 LO: Se.getLangOpts())) {
7565 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7566 // half array type (unless the cl_khr_fp16 extension is enabled).
7567 if (Se.Context.getBaseElementType(QT: R)->isHalfType()) {
7568 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_half_declaration) << R;
7569 NewVD->setInvalidDecl();
7570 return false;
7571 }
7572 }
7573
7574 // OpenCL v1.2 s6.9.r:
7575 // The event type cannot be used with the __local, __constant and __global
7576 // address space qualifiers.
7577 if (R->isEventT()) {
7578 if (R.getAddressSpace() != LangAS::opencl_private) {
7579 Se.Diag(Loc: NewVD->getBeginLoc(), DiagID: diag::err_event_t_addr_space_qual);
7580 NewVD->setInvalidDecl();
7581 return false;
7582 }
7583 }
7584
7585 if (R->isSamplerT()) {
7586 // OpenCL v1.2 s6.9.b p4:
7587 // The sampler type cannot be used with the __local and __global address
7588 // space qualifiers.
7589 if (R.getAddressSpace() == LangAS::opencl_local ||
7590 R.getAddressSpace() == LangAS::opencl_global) {
7591 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wrong_sampler_addressspace);
7592 NewVD->setInvalidDecl();
7593 }
7594
7595 // OpenCL v1.2 s6.12.14.1:
7596 // A global sampler must be declared with either the constant address
7597 // space qualifier or with the const qualifier.
7598 if (DC->isTranslationUnit() &&
7599 !(R.getAddressSpace() == LangAS::opencl_constant ||
7600 R.isConstQualified())) {
7601 Se.Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_nonconst_global_sampler);
7602 NewVD->setInvalidDecl();
7603 }
7604 if (NewVD->isInvalidDecl())
7605 return false;
7606 }
7607
7608 return true;
7609}
7610
7611template <typename AttrTy>
7612static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7613 const TypedefNameDecl *TND = TT->getDecl();
7614 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7615 AttrTy *Clone = Attribute->clone(S.Context);
7616 Clone->setInherited(true);
7617 D->addAttr(A: Clone);
7618 }
7619}
7620
7621// This function emits warning and a corresponding note based on the
7622// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7623// declarations of an annotated type must be const qualified.
7624static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7625 QualType VarType = VD->getType().getCanonicalType();
7626
7627 // Ignore local declarations (for now) and those with const qualification.
7628 // TODO: Local variables should not be allowed if their type declaration has
7629 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7630 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7631 return;
7632
7633 if (VarType->isArrayType()) {
7634 // Retrieve element type for array declarations.
7635 VarType = S.getASTContext().getBaseElementType(QT: VarType);
7636 }
7637
7638 const RecordDecl *RD = VarType->getAsRecordDecl();
7639
7640 // Check if the record declaration is present and if it has any attributes.
7641 if (RD == nullptr)
7642 return;
7643
7644 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7645 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_var_decl_not_read_only) << RD;
7646 S.Diag(Loc: ConstDecl->getLocation(), DiagID: diag::note_enforce_read_only_placement);
7647 return;
7648 }
7649}
7650
7651void Sema::ProcessPragmaExport(DeclaratorDecl *NewD) {
7652 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7653 "NewD is not a function or variable");
7654
7655 if (PendingExportedNames.empty())
7656 return;
7657 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: NewD)) {
7658 if (getLangOpts().CPlusPlus && !FD->isExternC())
7659 return;
7660 }
7661 IdentifierInfo *IdentName = NewD->getIdentifier();
7662 if (IdentName == nullptr)
7663 return;
7664 auto PendingName = PendingExportedNames.find(Val: IdentName);
7665 if (PendingName != PendingExportedNames.end()) {
7666 auto &Label = PendingName->second;
7667 if (!Label.Used) {
7668 Label.Used = true;
7669 if (NewD->hasExternalFormalLinkage())
7670 mergeVisibilityType(D: NewD, Loc: Label.NameLoc, Type: VisibilityAttr::Default);
7671 else
7672 Diag(Loc: Label.NameLoc, DiagID: diag::warn_pragma_not_applied) << "export" << NewD;
7673 }
7674 }
7675}
7676
7677// Checks if VD is declared at global scope or with C language linkage.
7678static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7679 return Name.getAsIdentifierInfo() &&
7680 Name.getAsIdentifierInfo()->isStr(Str: "main") &&
7681 !VD->getDescribedVarTemplate() &&
7682 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7683 VD->isExternC());
7684}
7685
7686void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7687 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7688
7689 // Quickly return if the function does not have an `asm` attribute.
7690 if (E == nullptr)
7691 return;
7692
7693 // The parser guarantees this is a string.
7694 StringLiteral *SE = cast<StringLiteral>(Val: E);
7695 StringRef Label = SE->getString();
7696 QualType R = TInfo->getType();
7697 if (S->getFnParent() != nullptr) {
7698 switch (SC) {
7699 case SC_None:
7700 case SC_Auto:
7701 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_asm_label_on_auto_decl) << Label;
7702 break;
7703 case SC_Register:
7704 // Local Named register
7705 if (!Context.getTargetInfo().isValidGCCRegisterName(Name: Label) &&
7706 DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: getCurFunctionDecl()))
7707 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7708 break;
7709 case SC_Static:
7710 case SC_Extern:
7711 case SC_PrivateExtern:
7712 break;
7713 }
7714 } else if (SC == SC_Register) {
7715 // Global Named register
7716 if (DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) {
7717 const auto &TI = Context.getTargetInfo();
7718 bool HasSizeMismatch;
7719
7720 if (!TI.isValidGCCRegisterName(Name: Label))
7721 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_unknown_register_name) << Label;
7722 else if (!TI.validateGlobalRegisterVariable(RegName: Label, RegSize: Context.getTypeSize(T: R),
7723 HasSizeMismatch))
7724 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_invalid_global_var_reg) << Label;
7725 else if (HasSizeMismatch)
7726 Diag(Loc: E->getExprLoc(), DiagID: diag::err_asm_register_size_mismatch) << Label;
7727 }
7728
7729 if (!R->isIntegralType(Ctx: Context) && !R->isPointerType()) {
7730 Diag(Loc: TInfo->getTypeLoc().getBeginLoc(),
7731 DiagID: diag::err_asm_unsupported_register_type)
7732 << TInfo->getTypeLoc().getSourceRange();
7733 NewVD->setInvalidDecl(true);
7734 }
7735 }
7736}
7737
7738NamedDecl *Sema::ActOnVariableDeclarator(
7739 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7740 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7741 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7742 QualType R = TInfo->getType();
7743 DeclarationName Name = GetNameForDeclarator(D).getName();
7744
7745 IdentifierInfo *II = Name.getAsIdentifierInfo();
7746 bool IsPlaceholderVariable = false;
7747
7748 if (D.isDecompositionDeclarator()) {
7749 // Take the name of the first declarator as our name for diagnostic
7750 // purposes.
7751 auto &Decomp = D.getDecompositionDeclarator();
7752 if (!Decomp.bindings().empty()) {
7753 II = Decomp.bindings()[0].Name;
7754 Name = II;
7755 }
7756 } else if (!II) {
7757 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_variable_name) << Name;
7758 return nullptr;
7759 }
7760
7761
7762 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7763 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS: D.getDeclSpec());
7764 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7765 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7766
7767 IsPlaceholderVariable = true;
7768
7769 if (!Previous.empty()) {
7770 NamedDecl *PrevDecl = *Previous.begin();
7771 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7772 DC: DC->getRedeclContext());
7773 if (SameDC && isDeclInScope(D: PrevDecl, Ctx: CurContext, S, AllowInlineNamespace: false)) {
7774 IsPlaceholderVariable = !isa<ParmVarDecl>(Val: PrevDecl);
7775 if (IsPlaceholderVariable)
7776 DiagPlaceholderVariableDefinition(Loc: D.getIdentifierLoc());
7777 }
7778 }
7779 }
7780
7781 // dllimport globals without explicit storage class are treated as extern. We
7782 // have to change the storage class this early to get the right DeclContext.
7783 if (SC == SC_None && !DC->isRecord() &&
7784 hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLImport) &&
7785 !hasParsedAttr(S, PD: D, Kind: ParsedAttr::AT_DLLExport))
7786 SC = SC_Extern;
7787
7788 DeclContext *OriginalDC = DC;
7789 bool IsLocalExternDecl = SC == SC_Extern &&
7790 adjustContextForLocalExternDecl(DC);
7791
7792 if (SCSpec == DeclSpec::SCS_mutable) {
7793 // mutable can only appear on non-static class members, so it's always
7794 // an error here
7795 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_mutable_nonmember);
7796 D.setInvalidType();
7797 SC = SC_None;
7798 }
7799
7800 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7801 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7802 loc: D.getDeclSpec().getStorageClassSpecLoc())) {
7803 // In C++11, the 'register' storage class specifier is deprecated.
7804 // Suppress the warning in system macros, it's used in macros in some
7805 // popular C system headers, such as in glibc's htonl() macro.
7806 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7807 DiagID: getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7808 : diag::warn_deprecated_register)
7809 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7810 }
7811
7812 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
7813
7814 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7815 // C99 6.9p2: The storage-class specifiers auto and register shall not
7816 // appear in the declaration specifiers in an external declaration.
7817 // Global Register+Asm is a GNU extension we support.
7818 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7819 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_typecheck_sclass_fscope);
7820 D.setInvalidType();
7821 }
7822 }
7823
7824 // If this variable has a VLA type and an initializer, try to
7825 // fold to a constant-sized type. This is otherwise invalid.
7826 if (D.hasInitializer() && R->isVariableArrayType())
7827 tryToFixVariablyModifiedVarType(TInfo, T&: R, Loc: D.getIdentifierLoc(),
7828 /*DiagID=*/FailedFoldDiagID: 0);
7829
7830 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7831 const AutoType *AT = TL.getTypePtr();
7832 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
7833 }
7834
7835 bool IsMemberSpecialization = false;
7836 bool IsVariableTemplateSpecialization = false;
7837 bool IsPartialSpecialization = false;
7838 bool IsVariableTemplate = false;
7839 VarDecl *NewVD = nullptr;
7840 VarTemplateDecl *NewTemplate = nullptr;
7841 TemplateParameterList *TemplateParams = nullptr;
7842 if (!getLangOpts().CPlusPlus) {
7843 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(), IdLoc: D.getIdentifierLoc(),
7844 Id: II, T: R, TInfo, S: SC);
7845
7846 if (R->getContainedDeducedType())
7847 ParsingInitForAutoVars.insert(Ptr: NewVD);
7848
7849 if (D.isInvalidType())
7850 NewVD->setInvalidDecl();
7851
7852 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7853 NewVD->hasLocalStorage())
7854 checkNonTrivialCUnion(QT: NewVD->getType(), Loc: NewVD->getLocation(),
7855 UseContext: NonTrivialCUnionContext::AutoVar, NonTrivialKind: NTCUK_Destruct);
7856 } else {
7857 bool Invalid = false;
7858 // Match up the template parameter lists with the scope specifier, then
7859 // determine whether we have a template or a template specialization.
7860 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7861 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
7862 SS: D.getCXXScopeSpec(),
7863 TemplateId: D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7864 ? D.getName().TemplateId
7865 : nullptr,
7866 ParamLists: TemplateParamLists,
7867 /*never a friend*/ IsFriend: false, IsMemberSpecialization, Invalid);
7868
7869 if (TemplateParams) {
7870 if (DC->isDependentContext()) {
7871 ContextRAII SavedContext(*this, DC);
7872 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
7873 Invalid = true;
7874 }
7875
7876 if (!TemplateParams->size() &&
7877 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7878 // There is an extraneous 'template<>' for this variable. Complain
7879 // about it, but allow the declaration of the variable.
7880 Diag(Loc: TemplateParams->getTemplateLoc(),
7881 DiagID: diag::err_template_variable_noparams)
7882 << II
7883 << SourceRange(TemplateParams->getTemplateLoc(),
7884 TemplateParams->getRAngleLoc());
7885 TemplateParams = nullptr;
7886 } else {
7887 // Check that we can declare a template here.
7888 if (CheckTemplateDeclScope(S, TemplateParams))
7889 return nullptr;
7890
7891 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7892 // This is an explicit specialization or a partial specialization.
7893 IsVariableTemplateSpecialization = true;
7894 IsPartialSpecialization = TemplateParams->size() > 0;
7895 } else { // if (TemplateParams->size() > 0)
7896 // This is a template declaration.
7897 IsVariableTemplate = true;
7898
7899 // Only C++1y supports variable templates (N3651).
7900 DiagCompat(Loc: D.getIdentifierLoc(), CompatDiagId: diag_compat::variable_template);
7901 }
7902 }
7903 } else {
7904 // Check that we can declare a member specialization here.
7905 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7906 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
7907 return nullptr;
7908 assert((Invalid ||
7909 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7910 "should have a 'template<>' for this decl");
7911 }
7912
7913 bool IsExplicitSpecialization =
7914 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7915
7916 // C++ [temp.expl.spec]p2:
7917 // The declaration in an explicit-specialization shall not be an
7918 // export-declaration. An explicit specialization shall not use a
7919 // storage-class-specifier other than thread_local.
7920 //
7921 // We use the storage-class-specifier from DeclSpec because we may have
7922 // added implicit 'extern' for declarations with __declspec(dllimport)!
7923 if (SCSpec != DeclSpec::SCS_unspecified &&
7924 (IsExplicitSpecialization || IsMemberSpecialization)) {
7925 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7926 DiagID: diag::ext_explicit_specialization_storage_class)
7927 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7928 }
7929
7930 if (CurContext->isRecord()) {
7931 if (SC == SC_Static) {
7932 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
7933 // Walk up the enclosing DeclContexts to check for any that are
7934 // incompatible with static data members.
7935 const DeclContext *FunctionOrMethod = nullptr;
7936 const CXXRecordDecl *AnonStruct = nullptr;
7937 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7938 if (Ctxt->isFunctionOrMethod()) {
7939 FunctionOrMethod = Ctxt;
7940 break;
7941 }
7942 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Val: Ctxt);
7943 if (ParentDecl && !ParentDecl->getDeclName()) {
7944 AnonStruct = ParentDecl;
7945 break;
7946 }
7947 }
7948 if (FunctionOrMethod) {
7949 // C++ [class.static.data]p5: A local class shall not have static
7950 // data members.
7951 Diag(Loc: D.getIdentifierLoc(),
7952 DiagID: diag::err_static_data_member_not_allowed_in_local_class)
7953 << Name << RD->getDeclName() << RD->getTagKind();
7954 } else if (AnonStruct) {
7955 // C++ [class.static.data]p4: Unnamed classes and classes contained
7956 // directly or indirectly within unnamed classes shall not contain
7957 // static data members.
7958 Diag(Loc: D.getIdentifierLoc(),
7959 DiagID: diag::err_static_data_member_not_allowed_in_anon_struct)
7960 << Name << AnonStruct->getTagKind();
7961 Invalid = true;
7962 } else if (RD->isUnion()) {
7963 // C++98 [class.union]p1: If a union contains a static data member,
7964 // the program is ill-formed. C++11 drops this restriction.
7965 DiagCompat(Loc: D.getIdentifierLoc(),
7966 CompatDiagId: diag_compat::static_data_member_in_union)
7967 << Name;
7968 }
7969 }
7970 } else if (IsVariableTemplate || IsPartialSpecialization) {
7971 // There is no such thing as a member field template.
7972 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_member)
7973 << II << TemplateParams->getSourceRange();
7974 // Recover by pretending this is a static data member template.
7975 SC = SC_Static;
7976 }
7977 } else if (DC->isRecord()) {
7978 // This is an out-of-line definition of a static data member.
7979 switch (SC) {
7980 case SC_None:
7981 break;
7982 case SC_Static:
7983 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7984 DiagID: diag::err_static_out_of_line)
7985 << FixItHint::CreateRemoval(
7986 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
7987 break;
7988 case SC_Auto:
7989 case SC_Register:
7990 case SC_Extern:
7991 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7992 // to names of variables declared in a block or to function parameters.
7993 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7994 // of class members
7995
7996 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
7997 DiagID: diag::err_storage_class_for_static_member)
7998 << FixItHint::CreateRemoval(
7999 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
8000 break;
8001 case SC_PrivateExtern:
8002 llvm_unreachable("C storage class in c++!");
8003 }
8004 }
8005
8006 if (IsVariableTemplateSpecialization) {
8007 SourceLocation TemplateKWLoc =
8008 TemplateParamLists.size() > 0
8009 ? TemplateParamLists[0]->getTemplateLoc()
8010 : SourceLocation();
8011 DeclResult Res = ActOnVarTemplateSpecialization(
8012 S, D, TSI: TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8013 IsPartialSpecialization);
8014 if (Res.isInvalid())
8015 return nullptr;
8016 NewVD = cast<VarDecl>(Val: Res.get());
8017 AddToScope = false;
8018 } else if (D.isDecompositionDeclarator()) {
8019 NewVD = DecompositionDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8020 LSquareLoc: D.getIdentifierLoc(), T: R, TInfo, S: SC,
8021 Bindings);
8022 } else
8023 NewVD = VarDecl::Create(C&: Context, DC, StartLoc: D.getBeginLoc(),
8024 IdLoc: D.getIdentifierLoc(), Id: II, T: R, TInfo, S: SC);
8025
8026 // If this is supposed to be a variable template, create it as such.
8027 if (IsVariableTemplate) {
8028 NewTemplate =
8029 VarTemplateDecl::Create(C&: Context, DC, L: D.getIdentifierLoc(), Name,
8030 Params: TemplateParams, Decl: NewVD);
8031 NewVD->setDescribedVarTemplate(NewTemplate);
8032 }
8033
8034 // If this decl has an auto type in need of deduction, make a note of the
8035 // Decl so we can diagnose uses of it in its own initializer.
8036 if (R->getContainedDeducedType())
8037 ParsingInitForAutoVars.insert(Ptr: NewVD);
8038
8039 if (D.isInvalidType() || Invalid) {
8040 NewVD->setInvalidDecl();
8041 if (NewTemplate)
8042 NewTemplate->setInvalidDecl();
8043 }
8044
8045 SetNestedNameSpecifier(S&: *this, DD: NewVD, D);
8046
8047 // If we have any template parameter lists that don't directly belong to
8048 // the variable (matching the scope specifier), store them.
8049 // An explicit variable template specialization does not own any template
8050 // parameter lists.
8051 unsigned VDTemplateParamLists =
8052 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8053 if (TemplateParamLists.size() > VDTemplateParamLists)
8054 NewVD->setTemplateParameterListsInfo(
8055 Context, TPLists: TemplateParamLists.drop_back(N: VDTemplateParamLists));
8056 }
8057
8058 if (D.getDeclSpec().isInlineSpecified()) {
8059 if (!getLangOpts().CPlusPlus) {
8060 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
8061 << 0;
8062 } else if (CurContext->isFunctionOrMethod()) {
8063 // 'inline' is not allowed on block scope variable declaration.
8064 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8065 DiagID: diag::err_inline_declaration_block_scope) << Name
8066 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
8067 } else {
8068 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
8069 DiagID: getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8070 : diag::compat_pre_cxx17_inline_variable);
8071 NewVD->setInlineSpecified();
8072 }
8073 }
8074
8075 // Set the lexical context. If the declarator has a C++ scope specifier, the
8076 // lexical context will be different from the semantic context.
8077 NewVD->setLexicalDeclContext(CurContext);
8078 if (NewTemplate)
8079 NewTemplate->setLexicalDeclContext(CurContext);
8080
8081 if (IsLocalExternDecl) {
8082 if (D.isDecompositionDeclarator())
8083 for (auto *B : Bindings)
8084 B->setLocalExternDecl();
8085 else
8086 NewVD->setLocalExternDecl();
8087 }
8088
8089 bool EmitTLSUnsupportedError = false;
8090 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
8091 // C++11 [dcl.stc]p4:
8092 // When thread_local is applied to a variable of block scope the
8093 // storage-class-specifier static is implied if it does not appear
8094 // explicitly.
8095 // Core issue: 'static' is not implied if the variable is declared
8096 // 'extern'.
8097 if (NewVD->hasLocalStorage() &&
8098 (SCSpec != DeclSpec::SCS_unspecified ||
8099 TSCS != DeclSpec::TSCS_thread_local ||
8100 !DC->isFunctionOrMethod()))
8101 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8102 DiagID: diag::err_thread_non_global)
8103 << DeclSpec::getSpecifierName(S: TSCS);
8104 else if (!Context.getTargetInfo().isTLSSupported()) {
8105 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8106 // Postpone error emission until we've collected attributes required to
8107 // figure out whether it's a host or device variable and whether the
8108 // error should be ignored.
8109 EmitTLSUnsupportedError = true;
8110 // We still need to mark the variable as TLS so it shows up in AST with
8111 // proper storage class for other tools to use even if we're not going
8112 // to emit any code for it.
8113 NewVD->setTSCSpec(TSCS);
8114 } else
8115 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8116 DiagID: diag::err_thread_unsupported);
8117 } else
8118 NewVD->setTSCSpec(TSCS);
8119 }
8120
8121 switch (D.getDeclSpec().getConstexprSpecifier()) {
8122 case ConstexprSpecKind::Unspecified:
8123 break;
8124
8125 case ConstexprSpecKind::Consteval:
8126 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8127 DiagID: diag::err_constexpr_wrong_decl_kind)
8128 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8129 [[fallthrough]];
8130
8131 case ConstexprSpecKind::Constexpr:
8132 NewVD->setConstexpr(true);
8133 // C++1z [dcl.spec.constexpr]p1:
8134 // A static data member declared with the constexpr specifier is
8135 // implicitly an inline variable.
8136 if (NewVD->isStaticDataMember() &&
8137 (getLangOpts().CPlusPlus17 ||
8138 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8139 NewVD->setImplicitlyInline();
8140 break;
8141
8142 case ConstexprSpecKind::Constinit:
8143 if (!NewVD->hasGlobalStorage())
8144 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
8145 DiagID: diag::err_constinit_local_variable);
8146 else
8147 NewVD->addAttr(
8148 A: ConstInitAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getConstexprSpecLoc(),
8149 S: ConstInitAttr::Keyword_constinit));
8150 break;
8151 }
8152
8153 // C99 6.7.4p3
8154 // An inline definition of a function with external linkage shall
8155 // not contain a definition of a modifiable object with static or
8156 // thread storage duration...
8157 // We only apply this when the function is required to be defined
8158 // elsewhere, i.e. when the function is not 'extern inline'. Note
8159 // that a local variable with thread storage duration still has to
8160 // be marked 'static'. Also note that it's possible to get these
8161 // semantics in C++ using __attribute__((gnu_inline)).
8162 if (SC == SC_Static && S->getFnParent() != nullptr &&
8163 !NewVD->getType().isConstQualified()) {
8164 FunctionDecl *CurFD = getCurFunctionDecl();
8165 if (CurFD && isFunctionDefinitionDiscarded(S&: *this, FD: CurFD)) {
8166 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
8167 DiagID: diag::warn_static_local_in_extern_inline);
8168 MaybeSuggestAddingStaticToDecl(D: CurFD);
8169 }
8170 }
8171
8172 if (D.getDeclSpec().isModulePrivateSpecified()) {
8173 if (IsVariableTemplateSpecialization)
8174 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8175 << (IsPartialSpecialization ? 1 : 0)
8176 << FixItHint::CreateRemoval(
8177 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8178 else if (IsMemberSpecialization)
8179 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_specialization)
8180 << 2
8181 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8182 else if (NewVD->hasLocalStorage())
8183 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_module_private_local)
8184 << 0 << NewVD
8185 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8186 << FixItHint::CreateRemoval(
8187 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
8188 else {
8189 NewVD->setModulePrivate();
8190 if (NewTemplate)
8191 NewTemplate->setModulePrivate();
8192 for (auto *B : Bindings)
8193 B->setModulePrivate();
8194 }
8195 }
8196
8197 if (getLangOpts().OpenCL) {
8198 deduceOpenCLAddressSpace(Var: NewVD);
8199
8200 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
8201 if (TSC != TSCS_unspecified) {
8202 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8203 DiagID: diag::err_opencl_unknown_type_specifier)
8204 << getLangOpts().getOpenCLVersionString()
8205 << DeclSpec::getSpecifierName(S: TSC) << 1;
8206 NewVD->setInvalidDecl();
8207 }
8208 }
8209
8210 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8211 // address space if the table has local storage (semantic checks elsewhere
8212 // will produce an error anyway).
8213 if (const auto *ATy = dyn_cast<ArrayType>(Val: NewVD->getType())) {
8214 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8215 !NewVD->hasLocalStorage()) {
8216 QualType Type = Context.getAddrSpaceQualType(
8217 T: NewVD->getType(), AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: 1));
8218 NewVD->setType(Type);
8219 }
8220 }
8221
8222 if (Expr *E = D.getAsmLabel()) {
8223 // The parser guarantees this is a string.
8224 StringLiteral *SE = cast<StringLiteral>(Val: E);
8225 StringRef Label = SE->getString();
8226
8227 // Insert the asm attribute.
8228 NewVD->addAttr(A: AsmLabelAttr::Create(Ctx&: Context, Label, Range: SE->getStrTokenLoc(TokNum: 0)));
8229 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8230 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8231 ExtnameUndeclaredIdentifiers.find(Val: NewVD->getIdentifier());
8232 if (I != ExtnameUndeclaredIdentifiers.end()) {
8233 if (isDeclExternC(D: NewVD)) {
8234 NewVD->addAttr(A: I->second);
8235 ExtnameUndeclaredIdentifiers.erase(I);
8236 } else
8237 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
8238 << /*Variable*/ 1 << NewVD;
8239 }
8240 }
8241
8242 // Handle attributes prior to checking for duplicates in MergeVarDecl
8243 ProcessDeclAttributes(S, D: NewVD, PD: D);
8244
8245 if (getLangOpts().HLSL)
8246 HLSL().ActOnVariableDeclarator(VD: NewVD);
8247
8248 if (getLangOpts().OpenACC)
8249 OpenACC().ActOnVariableDeclarator(VD: NewVD);
8250
8251 // FIXME: This is probably the wrong location to be doing this and we should
8252 // probably be doing this for more attributes (especially for function
8253 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8254 // the code to copy attributes would be generated by TableGen.
8255 if (R->isFunctionPointerType())
8256 if (const auto *TT = R->getAs<TypedefType>())
8257 copyAttrFromTypedefToDecl<AllocSizeAttr>(S&: *this, D: NewVD, TT);
8258
8259 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8260 if (EmitTLSUnsupportedError &&
8261 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(LangOpts: getLangOpts(), D: NewVD)) ||
8262 (getLangOpts().OpenMPIsTargetDevice &&
8263 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: NewVD))))
8264 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
8265 DiagID: diag::err_thread_unsupported);
8266
8267 if (EmitTLSUnsupportedError &&
8268 (LangOpts.SYCLIsDevice ||
8269 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8270 targetDiag(Loc: D.getIdentifierLoc(), DiagID: diag::err_thread_unsupported);
8271 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8272 // storage [duration]."
8273 if (SC == SC_None && S->getFnParent() != nullptr &&
8274 (NewVD->hasAttr<CUDASharedAttr>() ||
8275 NewVD->hasAttr<CUDAConstantAttr>())) {
8276 NewVD->setStorageClass(SC_Static);
8277 }
8278 }
8279
8280 // Ensure that dllimport globals without explicit storage class are treated as
8281 // extern. The storage class is set above using parsed attributes. Now we can
8282 // check the VarDecl itself.
8283 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8284 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8285 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8286
8287 // In auto-retain/release, infer strong retension for variables of
8288 // retainable type.
8289 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewVD))
8290 NewVD->setInvalidDecl();
8291
8292 // Check the ASM label here, as we need to know all other attributes of the
8293 // Decl first. Otherwise, we can't know if the asm label refers to the
8294 // host or device in a CUDA context. The device has other registers than
8295 // host and we must know where the function will be placed.
8296 CheckAsmLabel(S, E: D.getAsmLabel(), SC, TInfo, NewVD);
8297
8298 // Find the shadowed declaration before filtering for scope.
8299 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8300 ? getShadowedDeclaration(D: NewVD, R: Previous)
8301 : nullptr;
8302
8303 // Don't consider existing declarations that are in a different
8304 // scope and are out-of-semantic-context declarations (if the new
8305 // declaration has linkage).
8306 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(VD: NewVD),
8307 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
8308 IsMemberSpecialization ||
8309 IsVariableTemplateSpecialization);
8310
8311 // Check whether the previous declaration is in the same block scope. This
8312 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8313 if (getLangOpts().CPlusPlus &&
8314 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8315 NewVD->setPreviousDeclInSameBlockScope(
8316 Previous.isSingleResult() && !Previous.isShadowed() &&
8317 isDeclInScope(D: Previous.getFoundDecl(), Ctx: OriginalDC, S, AllowInlineNamespace: false));
8318
8319 if (!getLangOpts().CPlusPlus) {
8320 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8321 } else {
8322 // If this is an explicit specialization of a static data member, check it.
8323 if (IsMemberSpecialization && !IsVariableTemplate &&
8324 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8325 CheckMemberSpecialization(Member: NewVD, Previous))
8326 NewVD->setInvalidDecl();
8327
8328 // Merge the decl with the existing one if appropriate.
8329 if (!Previous.empty()) {
8330 if (Previous.isSingleResult() &&
8331 isa<FieldDecl>(Val: Previous.getFoundDecl()) &&
8332 D.getCXXScopeSpec().isSet()) {
8333 // The user tried to define a non-static data member
8334 // out-of-line (C++ [dcl.meaning]p1).
8335 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_nonstatic_member_out_of_line)
8336 << D.getCXXScopeSpec().getRange();
8337 Previous.clear();
8338 NewVD->setInvalidDecl();
8339 }
8340 } else if (D.getCXXScopeSpec().isSet() &&
8341 !IsVariableTemplateSpecialization) {
8342 // No previous declaration in the qualifying scope.
8343 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_no_member)
8344 << Name << computeDeclContext(SS: D.getCXXScopeSpec(), EnteringContext: true)
8345 << D.getCXXScopeSpec().getRange();
8346 NewVD->setInvalidDecl();
8347 }
8348
8349 if (!IsPlaceholderVariable)
8350 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8351
8352 // CheckVariableDeclaration will set NewVD as invalid if something is in
8353 // error like WebAssembly tables being declared as arrays with a non-zero
8354 // size, but then parsing continues and emits further errors on that line.
8355 // To avoid that we check here if it happened and return nullptr.
8356 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8357 return nullptr;
8358
8359 if (NewTemplate) {
8360 VarTemplateDecl *PrevVarTemplate =
8361 NewVD->getPreviousDecl()
8362 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8363 : nullptr;
8364
8365 // Check the template parameter list of this declaration, possibly
8366 // merging in the template parameter list from the previous variable
8367 // template declaration.
8368 if (CheckTemplateParameterList(
8369 NewParams: TemplateParams,
8370 OldParams: PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8371 : nullptr,
8372 TPC: (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8373 DC->isDependentContext())
8374 ? TPC_ClassTemplateMember
8375 : TPC_Other))
8376 NewVD->setInvalidDecl();
8377
8378 // If we are providing an explicit specialization of a static variable
8379 // template, make a note of that.
8380 if (PrevVarTemplate &&
8381 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8382 PrevVarTemplate->setMemberSpecialization();
8383 }
8384 }
8385
8386 // Diagnose shadowed variables iff this isn't a redeclaration.
8387 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8388 CheckShadow(D: NewVD, ShadowedDecl, R: Previous);
8389
8390 ProcessPragmaWeak(S, D: NewVD);
8391 ProcessPragmaExport(NewD: NewVD);
8392
8393 // If this is the first declaration of an extern C variable, update
8394 // the map of such variables.
8395 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8396 isIncompleteDeclExternC(S&: *this, D: NewVD))
8397 RegisterLocallyScopedExternCDecl(ND: NewVD, S);
8398
8399 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8400 MangleNumberingContext *MCtx;
8401 Decl *ManglingContextDecl;
8402 std::tie(args&: MCtx, args&: ManglingContextDecl) =
8403 getCurrentMangleNumberContext(DC: NewVD->getDeclContext());
8404 if (MCtx) {
8405 Context.setManglingNumber(
8406 ND: NewVD, Number: MCtx->getManglingNumber(
8407 VD: NewVD, MSLocalManglingNumber: getMSManglingNumber(LO: getLangOpts(), S)));
8408 Context.setStaticLocalNumber(VD: NewVD, Number: MCtx->getStaticLocalNumber(VD: NewVD));
8409 }
8410 }
8411
8412 // Special handling of variable named 'main'.
8413 if (!getLangOpts().Freestanding && isMainVar(Name, VD: NewVD)) {
8414 // C++ [basic.start.main]p3:
8415 // A program that declares
8416 // - a variable main at global scope, or
8417 // - an entity named main with C language linkage (in any namespace)
8418 // is ill-formed
8419 if (getLangOpts().CPlusPlus)
8420 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_main_global_variable)
8421 << NewVD->isExternC();
8422
8423 // In C, and external-linkage variable named main results in undefined
8424 // behavior.
8425 else if (NewVD->hasExternalFormalLinkage())
8426 Diag(Loc: D.getBeginLoc(), DiagID: diag::warn_main_redefined);
8427 }
8428
8429 if (D.isRedeclaration() && !Previous.empty()) {
8430 NamedDecl *Prev = Previous.getRepresentativeDecl();
8431 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewVD, IsSpecialization: IsMemberSpecialization,
8432 IsDefinition: D.isFunctionDefinition());
8433 }
8434
8435 if (NewTemplate) {
8436 if (NewVD->isInvalidDecl())
8437 NewTemplate->setInvalidDecl();
8438 ActOnDocumentableDecl(D: NewTemplate);
8439 return NewTemplate;
8440 }
8441
8442 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8443 CompleteMemberSpecialization(Member: NewVD, Previous);
8444
8445 emitReadOnlyPlacementAttrWarning(S&: *this, VD: NewVD);
8446
8447 return NewVD;
8448}
8449
8450/// Enum describing the %select options in diag::warn_decl_shadow.
8451enum ShadowedDeclKind {
8452 SDK_Local,
8453 SDK_Global,
8454 SDK_StaticMember,
8455 SDK_Field,
8456 SDK_Typedef,
8457 SDK_Using,
8458 SDK_StructuredBinding
8459};
8460
8461/// Determine what kind of declaration we're shadowing.
8462static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8463 const DeclContext *OldDC) {
8464 if (isa<TypeAliasDecl>(Val: ShadowedDecl))
8465 return SDK_Using;
8466 else if (isa<TypedefDecl>(Val: ShadowedDecl))
8467 return SDK_Typedef;
8468 else if (isa<BindingDecl>(Val: ShadowedDecl))
8469 return SDK_StructuredBinding;
8470 else if (isa<RecordDecl>(Val: OldDC))
8471 return isa<FieldDecl>(Val: ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8472
8473 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8474}
8475
8476/// Return the location of the capture if the given lambda captures the given
8477/// variable \p VD, or an invalid source location otherwise.
8478static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8479 const ValueDecl *VD) {
8480 for (const Capture &Capture : LSI->Captures) {
8481 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8482 return Capture.getLocation();
8483 }
8484 return SourceLocation();
8485}
8486
8487static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8488 const LookupResult &R) {
8489 // Only diagnose if we're shadowing an unambiguous field or variable.
8490 if (R.getResultKind() != LookupResultKind::Found)
8491 return false;
8492
8493 // Return false if warning is ignored.
8494 return !Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: R.getNameLoc());
8495}
8496
8497NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8498 const LookupResult &R) {
8499 if (!shouldWarnIfShadowedDecl(Diags, R))
8500 return nullptr;
8501
8502 // Don't diagnose declarations at file scope.
8503 if (D->hasGlobalStorage() && !D->isStaticLocal())
8504 return nullptr;
8505
8506 NamedDecl *ShadowedDecl = R.getFoundDecl();
8507 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8508 : nullptr;
8509}
8510
8511NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8512 const LookupResult &R) {
8513 // Don't warn if typedef declaration is part of a class
8514 if (D->getDeclContext()->isRecord())
8515 return nullptr;
8516
8517 if (!shouldWarnIfShadowedDecl(Diags, R))
8518 return nullptr;
8519
8520 NamedDecl *ShadowedDecl = R.getFoundDecl();
8521 return isa<TypedefNameDecl>(Val: ShadowedDecl) ? ShadowedDecl : nullptr;
8522}
8523
8524NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8525 const LookupResult &R) {
8526 if (!shouldWarnIfShadowedDecl(Diags, R))
8527 return nullptr;
8528
8529 NamedDecl *ShadowedDecl = R.getFoundDecl();
8530 return isa<VarDecl, FieldDecl, BindingDecl>(Val: ShadowedDecl) ? ShadowedDecl
8531 : nullptr;
8532}
8533
8534void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8535 const LookupResult &R) {
8536 DeclContext *NewDC = D->getDeclContext();
8537
8538 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ShadowedDecl)) {
8539 if (const auto *MD =
8540 dyn_cast<CXXMethodDecl>(Val: getFunctionLevelDeclContext())) {
8541 // Fields aren't shadowed in C++ static members or in member functions
8542 // with an explicit object parameter.
8543 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8544 return;
8545 }
8546 // Fields shadowed by constructor parameters are a special case. Usually
8547 // the constructor initializes the field with the parameter.
8548 if (isa<CXXConstructorDecl>(Val: NewDC))
8549 if (const auto PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8550 // Remember that this was shadowed so we can either warn about its
8551 // modification or its existence depending on warning settings.
8552 ShadowingDecls.insert(KV: {PVD->getCanonicalDecl(), FD});
8553 return;
8554 }
8555 }
8556
8557 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(Val: ShadowedDecl))
8558 if (shadowedVar->isExternC()) {
8559 // For shadowing external vars, make sure that we point to the global
8560 // declaration, not a locally scoped extern declaration.
8561 for (auto *I : shadowedVar->redecls())
8562 if (I->isFileVarDecl()) {
8563 ShadowedDecl = I;
8564 break;
8565 }
8566 }
8567
8568 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8569
8570 unsigned WarningDiag = diag::warn_decl_shadow;
8571 SourceLocation CaptureLoc;
8572 if (isa<VarDecl>(Val: D) && NewDC && isa<CXXMethodDecl>(Val: NewDC)) {
8573 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: NewDC->getParent())) {
8574 if (RD->isLambda() && OldDC->Encloses(DC: NewDC->getLexicalParent())) {
8575 // Handle both VarDecl and BindingDecl in lambda contexts
8576 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8577 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8578 const auto *LSI = cast<LambdaScopeInfo>(Val: getCurFunction());
8579 if (RD->getLambdaCaptureDefault() == LCD_None) {
8580 // Try to avoid warnings for lambdas with an explicit capture
8581 // list. Warn only when the lambda captures the shadowed decl
8582 // explicitly.
8583 CaptureLoc = getCaptureLocation(LSI, VD);
8584 if (CaptureLoc.isInvalid())
8585 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8586 } else {
8587 // Remember that this was shadowed so we can avoid the warning if
8588 // the shadowed decl isn't captured and the warning settings allow
8589 // it.
8590 cast<LambdaScopeInfo>(Val: getCurFunction())
8591 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: VD});
8592 return;
8593 }
8594 }
8595 if (isa<FieldDecl>(Val: ShadowedDecl)) {
8596 // If lambda can capture this, then emit default shadowing warning,
8597 // Otherwise it is not really a shadowing case since field is not
8598 // available in lambda's body.
8599 // At this point we don't know that lambda can capture this, so
8600 // remember that this was shadowed and delay until we know.
8601 cast<LambdaScopeInfo>(Val: getCurFunction())
8602 ->ShadowingDecls.push_back(Elt: {.VD: D, .ShadowedDecl: ShadowedDecl});
8603 return;
8604 }
8605 }
8606 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8607 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8608 bool HasLocalStorage = false;
8609 if (const auto *VD = dyn_cast<VarDecl>(Val: ShadowedDecl))
8610 HasLocalStorage = VD->hasLocalStorage();
8611 else if (const auto *BD = dyn_cast<BindingDecl>(Val: ShadowedDecl))
8612 HasLocalStorage =
8613 cast<VarDecl>(Val: BD->getDecomposedDecl())->hasLocalStorage();
8614
8615 if (HasLocalStorage) {
8616 // A variable can't shadow a local variable or binding in an enclosing
8617 // scope, if they are separated by a non-capturing declaration
8618 // context.
8619 for (DeclContext *ParentDC = NewDC;
8620 ParentDC && !ParentDC->Equals(DC: OldDC);
8621 ParentDC = getLambdaAwareParentOfDeclContext(DC: ParentDC)) {
8622 // Only block literals, captured statements, and lambda expressions
8623 // can capture; other scopes don't.
8624 if (!isa<BlockDecl>(Val: ParentDC) && !isa<CapturedDecl>(Val: ParentDC) &&
8625 !isLambdaCallOperator(DC: ParentDC))
8626 return;
8627 }
8628 }
8629 }
8630 }
8631 }
8632
8633 // Never warn about shadowing a placeholder variable.
8634 if (ShadowedDecl->isPlaceholderVar(LangOpts: getLangOpts()))
8635 return;
8636
8637 // Only warn about certain kinds of shadowing for class members.
8638 if (NewDC) {
8639 // In particular, don't warn about shadowing non-class members.
8640 if (NewDC->isRecord() && !OldDC->isRecord())
8641 return;
8642
8643 // Skip shadowing check if we're in a class scope, dealing with an enum
8644 // constant in a different context.
8645 DeclContext *ReDC = NewDC->getRedeclContext();
8646 if (ReDC->isRecord() && isa<EnumConstantDecl>(Val: D) && !OldDC->Equals(DC: ReDC))
8647 return;
8648
8649 // TODO: should we warn about static data members shadowing
8650 // static data members from base classes?
8651
8652 // TODO: don't diagnose for inaccessible shadowed members.
8653 // This is hard to do perfectly because we might friend the
8654 // shadowing context, but that's just a false negative.
8655 }
8656
8657 DeclarationName Name = R.getLookupName();
8658
8659 // Emit warning and note.
8660 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8661 Diag(Loc: R.getNameLoc(), DiagID: WarningDiag) << Name << Kind << OldDC;
8662 if (!CaptureLoc.isInvalid())
8663 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8664 << Name << /*explicitly*/ 1;
8665 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8666}
8667
8668void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8669 for (const auto &Shadow : LSI->ShadowingDecls) {
8670 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8671 // Try to avoid the warning when the shadowed decl isn't captured.
8672 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8673 if (isa<VarDecl, BindingDecl>(Val: ShadowedDecl)) {
8674 const auto *VD = cast<ValueDecl>(Val: ShadowedDecl);
8675 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8676 Diag(Loc: Shadow.VD->getLocation(),
8677 DiagID: CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8678 : diag::warn_decl_shadow)
8679 << Shadow.VD->getDeclName()
8680 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8681 if (CaptureLoc.isValid())
8682 Diag(Loc: CaptureLoc, DiagID: diag::note_var_explicitly_captured_here)
8683 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8684 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8685 } else if (isa<FieldDecl>(Val: ShadowedDecl)) {
8686 Diag(Loc: Shadow.VD->getLocation(),
8687 DiagID: LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8688 : diag::warn_decl_shadow_uncaptured_local)
8689 << Shadow.VD->getDeclName()
8690 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8691 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8692 }
8693 }
8694}
8695
8696void Sema::CheckShadow(Scope *S, VarDecl *D) {
8697 if (Diags.isIgnored(DiagID: diag::warn_decl_shadow, Loc: D->getLocation()))
8698 return;
8699
8700 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8701 Sema::LookupOrdinaryName,
8702 RedeclarationKind::ForVisibleRedeclaration);
8703 LookupName(R, S);
8704 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8705 CheckShadow(D, ShadowedDecl, R);
8706}
8707
8708/// Check if 'E', which is an expression that is about to be modified, refers
8709/// to a constructor parameter that shadows a field.
8710void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8711 // Quickly ignore expressions that can't be shadowing ctor parameters.
8712 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8713 return;
8714 E = E->IgnoreParenImpCasts();
8715 auto *DRE = dyn_cast<DeclRefExpr>(Val: E);
8716 if (!DRE)
8717 return;
8718 const NamedDecl *D = cast<NamedDecl>(Val: DRE->getDecl()->getCanonicalDecl());
8719 auto I = ShadowingDecls.find(Val: D);
8720 if (I == ShadowingDecls.end())
8721 return;
8722 const NamedDecl *ShadowedDecl = I->second;
8723 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8724 Diag(Loc, DiagID: diag::warn_modifying_shadowing_decl) << D << OldDC;
8725 Diag(Loc: D->getLocation(), DiagID: diag::note_var_declared_here) << D;
8726 Diag(Loc: ShadowedDecl->getLocation(), DiagID: diag::note_previous_declaration);
8727
8728 // Avoid issuing multiple warnings about the same decl.
8729 ShadowingDecls.erase(I);
8730}
8731
8732/// Check for conflict between this global or extern "C" declaration and
8733/// previous global or extern "C" declarations. This is only used in C++.
8734template<typename T>
8735static bool checkGlobalOrExternCConflict(
8736 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8737 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8738 NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName());
8739
8740 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8741 // The common case: this global doesn't conflict with any extern "C"
8742 // declaration.
8743 return false;
8744 }
8745
8746 if (Prev) {
8747 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8748 // Both the old and new declarations have C language linkage. This is a
8749 // redeclaration.
8750 Previous.clear();
8751 Previous.addDecl(D: Prev);
8752 return true;
8753 }
8754
8755 // This is a global, non-extern "C" declaration, and there is a previous
8756 // non-global extern "C" declaration. Diagnose if this is a variable
8757 // declaration.
8758 if (!isa<VarDecl>(ND))
8759 return false;
8760 } else {
8761 // The declaration is extern "C". Check for any declaration in the
8762 // translation unit which might conflict.
8763 if (IsGlobal) {
8764 // We have already performed the lookup into the translation unit.
8765 IsGlobal = false;
8766 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8767 I != E; ++I) {
8768 if (isa<VarDecl>(Val: *I)) {
8769 Prev = *I;
8770 break;
8771 }
8772 }
8773 } else {
8774 DeclContext::lookup_result R =
8775 S.Context.getTranslationUnitDecl()->lookup(Name: ND->getDeclName());
8776 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8777 I != E; ++I) {
8778 if (isa<VarDecl>(Val: *I)) {
8779 Prev = *I;
8780 break;
8781 }
8782 // FIXME: If we have any other entity with this name in global scope,
8783 // the declaration is ill-formed, but that is a defect: it breaks the
8784 // 'stat' hack, for instance. Only variables can have mangled name
8785 // clashes with extern "C" declarations, so only they deserve a
8786 // diagnostic.
8787 }
8788 }
8789
8790 if (!Prev)
8791 return false;
8792 }
8793
8794 // Use the first declaration's location to ensure we point at something which
8795 // is lexically inside an extern "C" linkage-spec.
8796 assert(Prev && "should have found a previous declaration to diagnose");
8797 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: Prev))
8798 Prev = FD->getFirstDecl();
8799 else
8800 Prev = cast<VarDecl>(Val: Prev)->getFirstDecl();
8801
8802 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8803 << IsGlobal << ND;
8804 S.Diag(Loc: Prev->getLocation(), DiagID: diag::note_extern_c_global_conflict)
8805 << IsGlobal;
8806 return false;
8807}
8808
8809/// Apply special rules for handling extern "C" declarations. Returns \c true
8810/// if we have found that this is a redeclaration of some prior entity.
8811///
8812/// Per C++ [dcl.link]p6:
8813/// Two declarations [for a function or variable] with C language linkage
8814/// with the same name that appear in different scopes refer to the same
8815/// [entity]. An entity with C language linkage shall not be declared with
8816/// the same name as an entity in global scope.
8817template<typename T>
8818static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8819 LookupResult &Previous) {
8820 if (!S.getLangOpts().CPlusPlus) {
8821 // In C, when declaring a global variable, look for a corresponding 'extern'
8822 // variable declared in function scope. We don't need this in C++, because
8823 // we find local extern decls in the surrounding file-scope DeclContext.
8824 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8825 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(Name: ND->getDeclName())) {
8826 Previous.clear();
8827 Previous.addDecl(D: Prev);
8828 return true;
8829 }
8830 }
8831 return false;
8832 }
8833
8834 // A declaration in the translation unit can conflict with an extern "C"
8835 // declaration.
8836 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8837 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8838
8839 // An extern "C" declaration can conflict with a declaration in the
8840 // translation unit or can be a redeclaration of an extern "C" declaration
8841 // in another scope.
8842 if (isIncompleteDeclExternC(S,ND))
8843 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8844
8845 // Neither global nor extern "C": nothing to do.
8846 return false;
8847}
8848
8849static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8850 QualType T) {
8851 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8852 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8853 // any of its members, even recursively, shall not have an atomic type, or a
8854 // variably modified type, or a type that is volatile or restrict qualified.
8855 if (CanonT->isVariablyModifiedType()) {
8856 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8857 return true;
8858 }
8859
8860 // Arrays are qualified by their element type, so get the base type (this
8861 // works on non-arrays as well).
8862 CanonT = SemaRef.Context.getBaseElementType(QT: CanonT);
8863
8864 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8865 CanonT.isRestrictQualified()) {
8866 SemaRef.Diag(Loc: VarLoc, DiagID: diag::err_c23_constexpr_invalid_type) << T;
8867 return true;
8868 }
8869
8870 if (CanonT->isRecordType()) {
8871 const RecordDecl *RD = CanonT->getAsRecordDecl();
8872 if (!RD->isInvalidDecl() &&
8873 llvm::any_of(Range: RD->fields(), P: [&SemaRef, VarLoc](const FieldDecl *F) {
8874 return CheckC23ConstexprVarType(SemaRef, VarLoc, T: F->getType());
8875 }))
8876 return true;
8877 }
8878
8879 return false;
8880}
8881
8882void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8883 // If the decl is already known invalid, don't check it.
8884 if (NewVD->isInvalidDecl())
8885 return;
8886
8887 QualType T = NewVD->getType();
8888
8889 // Defer checking an 'auto' type until its initializer is attached.
8890 if (T->isUndeducedType())
8891 return;
8892
8893 if (NewVD->hasAttrs())
8894 CheckAlignasUnderalignment(D: NewVD);
8895
8896 if (T->isObjCObjectType()) {
8897 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_statically_allocated_object)
8898 << FixItHint::CreateInsertion(InsertionLoc: NewVD->getLocation(), Code: "*");
8899 T = Context.getObjCObjectPointerType(OIT: T);
8900 NewVD->setType(T);
8901 }
8902
8903 // Emit an error if an address space was applied to decl with local storage.
8904 // This includes arrays of objects with address space qualifiers, but not
8905 // automatic variables that point to other address spaces.
8906 // ISO/IEC TR 18037 S5.1.2
8907 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8908 T.getAddressSpace() != LangAS::Default) {
8909 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 0;
8910 NewVD->setInvalidDecl();
8911 return;
8912 }
8913
8914 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8915 // scope.
8916 if (getLangOpts().OpenCLVersion == 120 &&
8917 !getOpenCLOptions().isAvailableOption(Ext: "cl_clang_storage_class_specifiers",
8918 LO: getLangOpts()) &&
8919 NewVD->isStaticLocal()) {
8920 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_static_function_scope);
8921 NewVD->setInvalidDecl();
8922 return;
8923 }
8924
8925 if (getLangOpts().OpenCL) {
8926 if (!diagnoseOpenCLTypes(Se&: *this, NewVD))
8927 return;
8928
8929 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8930 if (NewVD->hasAttr<BlocksAttr>()) {
8931 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_block_storage_type);
8932 return;
8933 }
8934
8935 if (T->isBlockPointerType()) {
8936 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8937 // can't use 'extern' storage class.
8938 if (!T.isConstQualified()) {
8939 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
8940 << 0 /*const*/;
8941 NewVD->setInvalidDecl();
8942 return;
8943 }
8944 if (NewVD->hasExternalStorage()) {
8945 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_extern_block_declaration);
8946 NewVD->setInvalidDecl();
8947 return;
8948 }
8949 }
8950
8951 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8952 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8953 NewVD->hasExternalStorage()) {
8954 if (!T->isSamplerT() && !T->isDependentType() &&
8955 !(T.getAddressSpace() == LangAS::opencl_constant ||
8956 (T.getAddressSpace() == LangAS::opencl_global &&
8957 getOpenCLOptions().areProgramScopeVariablesSupported(
8958 Opts: getLangOpts())))) {
8959 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8960 if (getOpenCLOptions().areProgramScopeVariablesSupported(Opts: getLangOpts()))
8961 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8962 << Scope << "global or constant";
8963 else
8964 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_global_invalid_addr_space)
8965 << Scope << "constant";
8966 NewVD->setInvalidDecl();
8967 return;
8968 }
8969 } else {
8970 if (T.getAddressSpace() == LangAS::opencl_global) {
8971 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8972 << 1 /*is any function*/ << "global";
8973 NewVD->setInvalidDecl();
8974 return;
8975 }
8976 // When this extension is enabled, 'local' variables are permitted in
8977 // non-kernel functions and within nested scopes of kernel functions,
8978 // bypassing standard OpenCL address space restrictions.
8979 bool AllowFunctionScopeLocalVariables =
8980 T.getAddressSpace() == LangAS::opencl_local &&
8981 getOpenCLOptions().isAvailableOption(
8982 Ext: "__cl_clang_function_scope_local_variables", LO: getLangOpts());
8983 if (AllowFunctionScopeLocalVariables) {
8984 // Direct pass: No further diagnostics needed for this specific case.
8985 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
8986 T.getAddressSpace() == LangAS::opencl_local) {
8987 FunctionDecl *FD = getCurFunctionDecl();
8988 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8989 // in functions.
8990 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8991 if (T.getAddressSpace() == LangAS::opencl_constant)
8992 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8993 << 0 /*non-kernel only*/ << "constant";
8994 else
8995 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_function_variable)
8996 << 0 /*non-kernel only*/ << "local";
8997 NewVD->setInvalidDecl();
8998 return;
8999 }
9000 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9001 // in the outermost scope of a kernel function.
9002 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9003 if (!getCurScope()->isFunctionScope()) {
9004 if (T.getAddressSpace() == LangAS::opencl_constant)
9005 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9006 << "constant";
9007 else
9008 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_opencl_addrspace_scope)
9009 << "local";
9010 NewVD->setInvalidDecl();
9011 return;
9012 }
9013 }
9014 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9015 // If we are parsing a template we didn't deduce an addr
9016 // space yet.
9017 T.getAddressSpace() != LangAS::Default) {
9018 // Do not allow other address spaces on automatic variable.
9019 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_as_qualified_auto_decl) << 1;
9020 NewVD->setInvalidDecl();
9021 return;
9022 }
9023 }
9024 }
9025
9026 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9027 && !NewVD->hasAttr<BlocksAttr>()) {
9028 if (getLangOpts().getGC() != LangOptions::NonGC)
9029 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_gc_attribute_weak_on_local);
9030 else {
9031 assert(!getLangOpts().ObjCAutoRefCount);
9032 Diag(Loc: NewVD->getLocation(), DiagID: diag::warn_attribute_weak_on_local);
9033 }
9034 }
9035
9036 // WebAssembly tables must be static with a zero length and can't be
9037 // declared within functions.
9038 if (T->isWebAssemblyTableType()) {
9039 if (getCurScope()->getParent()) { // Parent is null at top-level
9040 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_in_function);
9041 NewVD->setInvalidDecl();
9042 return;
9043 }
9044 if (NewVD->getStorageClass() != SC_Static) {
9045 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_wasm_table_must_be_static);
9046 NewVD->setInvalidDecl();
9047 return;
9048 }
9049 const auto *ATy = dyn_cast<ConstantArrayType>(Val: T.getTypePtr());
9050 if (!ATy || ATy->getZExtSize() != 0) {
9051 Diag(Loc: NewVD->getLocation(),
9052 DiagID: diag::err_typecheck_wasm_table_must_have_zero_length);
9053 NewVD->setInvalidDecl();
9054 return;
9055 }
9056 }
9057
9058 // zero sized static arrays are not allowed in HIP device functions
9059 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9060 if (FunctionDecl *FD = getCurFunctionDecl();
9061 FD &&
9062 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9063 if (const ConstantArrayType *ArrayT =
9064 getASTContext().getAsConstantArrayType(T);
9065 ArrayT && ArrayT->isZeroSize()) {
9066 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_zero_array_size) << 2;
9067 }
9068 }
9069 }
9070
9071 bool isVM = T->isVariablyModifiedType();
9072 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9073 NewVD->hasAttr<BlocksAttr>())
9074 setFunctionHasBranchProtectedScope();
9075
9076 if ((isVM && NewVD->hasLinkage()) ||
9077 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9078 bool SizeIsNegative;
9079 llvm::APSInt Oversized;
9080 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
9081 TInfo: NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9082 QualType FixedT;
9083 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9084 FixedT = FixedTInfo->getType();
9085 else if (FixedTInfo) {
9086 // Type and type-as-written are canonically different. We need to fix up
9087 // both types separately.
9088 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9089 Oversized);
9090 }
9091 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9092 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9093 // FIXME: This won't give the correct result for
9094 // int a[10][n];
9095 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9096
9097 if (NewVD->isFileVarDecl())
9098 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_in_file_scope)
9099 << SizeRange;
9100 else if (NewVD->isStaticLocal())
9101 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_static_storage)
9102 << SizeRange;
9103 else
9104 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vla_decl_has_extern_linkage)
9105 << SizeRange;
9106 NewVD->setInvalidDecl();
9107 return;
9108 }
9109
9110 if (!FixedTInfo) {
9111 if (NewVD->isFileVarDecl())
9112 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_in_file_scope);
9113 else
9114 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_vm_decl_has_extern_linkage);
9115 NewVD->setInvalidDecl();
9116 return;
9117 }
9118
9119 Diag(Loc: NewVD->getLocation(), DiagID: diag::ext_vla_folded_to_constant);
9120 NewVD->setType(FixedT);
9121 NewVD->setTypeSourceInfo(FixedTInfo);
9122 }
9123
9124 if (T->isVoidType()) {
9125 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9126 // of objects and functions.
9127 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
9128 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
9129 << T;
9130 NewVD->setInvalidDecl();
9131 return;
9132 }
9133 }
9134
9135 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9136 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_nonlocal);
9137 NewVD->setInvalidDecl();
9138 return;
9139 }
9140
9141 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9142 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9143 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_sizeless_nonlocal) << T;
9144 NewVD->setInvalidDecl();
9145 return;
9146 }
9147
9148 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9149 Diag(Loc: NewVD->getLocation(), DiagID: diag::err_block_on_vm);
9150 NewVD->setInvalidDecl();
9151 return;
9152 }
9153
9154 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9155 CheckC23ConstexprVarType(SemaRef&: *this, VarLoc: NewVD->getLocation(), T)) {
9156 NewVD->setInvalidDecl();
9157 return;
9158 }
9159
9160 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9161 !T->isDependentType() &&
9162 RequireLiteralType(Loc: NewVD->getLocation(), T,
9163 DiagID: diag::err_constexpr_var_non_literal)) {
9164 NewVD->setInvalidDecl();
9165 return;
9166 }
9167
9168 // PPC MMA non-pointer types are not allowed as non-local variable types.
9169 if (Context.getTargetInfo().getTriple().isPPC64() &&
9170 !NewVD->isLocalVarDecl() &&
9171 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewVD->getLocation())) {
9172 NewVD->setInvalidDecl();
9173 return;
9174 }
9175
9176 // Check that SVE types are only used in functions with SVE available.
9177 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9178 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9179 llvm::StringMap<bool> CallerFeatureMap;
9180 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9181 if (ARM().checkSVETypeSupport(Ty: T, Loc: NewVD->getLocation(), FD,
9182 FeatureMap: CallerFeatureMap)) {
9183 NewVD->setInvalidDecl();
9184 return;
9185 }
9186 }
9187
9188 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(Val: CurContext)) {
9189 const FunctionDecl *FD = cast<FunctionDecl>(Val: CurContext);
9190 llvm::StringMap<bool> CallerFeatureMap;
9191 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, FD);
9192 RISCV().checkRVVTypeSupport(Ty: T, Loc: NewVD->getLocation(), D: cast<Decl>(Val: CurContext),
9193 FeatureMap: CallerFeatureMap);
9194 }
9195
9196 if (T.hasAddressSpace() &&
9197 !CheckVarDeclSizeAddressSpace(VD: NewVD, AS: T.getAddressSpace())) {
9198 NewVD->setInvalidDecl();
9199 return;
9200 }
9201}
9202
9203bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
9204 CheckVariableDeclarationType(NewVD);
9205
9206 // If the decl is already known invalid, don't check it.
9207 if (NewVD->isInvalidDecl())
9208 return false;
9209
9210 // If we did not find anything by this name, look for a non-visible
9211 // extern "C" declaration with the same name.
9212 if (Previous.empty() &&
9213 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewVD, Previous))
9214 Previous.setShadowed();
9215
9216 if (!Previous.empty()) {
9217 MergeVarDecl(New: NewVD, Previous);
9218 return true;
9219 }
9220 return false;
9221}
9222
9223bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
9224 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
9225
9226 // Look for methods in base classes that this method might override.
9227 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9228 /*DetectVirtual=*/false);
9229 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9230 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9231 DeclarationName Name = MD->getDeclName();
9232
9233 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9234 // We really want to find the base class destructor here.
9235 Name = Context.DeclarationNames.getCXXDestructorName(
9236 Ty: Context.getCanonicalTagType(TD: BaseRecord));
9237 }
9238
9239 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9240 CXXMethodDecl *BaseMD =
9241 dyn_cast<CXXMethodDecl>(Val: BaseND->getCanonicalDecl());
9242 if (!BaseMD || !BaseMD->isVirtual() ||
9243 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9244 /*ConsiderCudaAttrs=*/true))
9245 continue;
9246 if (!CheckExplicitObjectOverride(New: MD, Old: BaseMD))
9247 continue;
9248 if (Overridden.insert(Ptr: BaseMD).second) {
9249 MD->addOverriddenMethod(MD: BaseMD);
9250 CheckOverridingFunctionReturnType(New: MD, Old: BaseMD);
9251 CheckOverridingFunctionAttributes(New: MD, Old: BaseMD);
9252 CheckOverridingFunctionExceptionSpec(New: MD, Old: BaseMD);
9253 CheckIfOverriddenFunctionIsMarkedFinal(New: MD, Old: BaseMD);
9254 }
9255
9256 // A method can only override one function from each base class. We
9257 // don't track indirectly overridden methods from bases of bases.
9258 return true;
9259 }
9260
9261 return false;
9262 };
9263
9264 DC->lookupInBases(BaseMatches: VisitBase, Paths);
9265 return !Overridden.empty();
9266}
9267
9268namespace {
9269 // Struct for holding all of the extra arguments needed by
9270 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9271 struct ActOnFDArgs {
9272 Scope *S;
9273 Declarator &D;
9274 MultiTemplateParamsArg TemplateParamLists;
9275 bool AddToScope;
9276 };
9277} // end anonymous namespace
9278
9279namespace {
9280
9281// Callback to only accept typo corrections that have a non-zero edit distance.
9282// Also only accept corrections that have the same parent decl.
9283class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9284 public:
9285 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9286 CXXRecordDecl *Parent)
9287 : Context(Context), OriginalFD(TypoFD),
9288 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9289
9290 bool ValidateCandidate(const TypoCorrection &candidate) override {
9291 if (candidate.getEditDistance() == 0)
9292 return false;
9293
9294 SmallVector<unsigned, 1> MismatchedParams;
9295 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9296 CDeclEnd = candidate.end();
9297 CDecl != CDeclEnd; ++CDecl) {
9298 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9299
9300 if (FD && !FD->hasBody() &&
9301 hasSimilarParameters(Context, Declaration: FD, Definition: OriginalFD, Params&: MismatchedParams)) {
9302 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
9303 CXXRecordDecl *Parent = MD->getParent();
9304 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9305 return true;
9306 } else if (!ExpectedParent) {
9307 return true;
9308 }
9309 }
9310 }
9311
9312 return false;
9313 }
9314
9315 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9316 return std::make_unique<DifferentNameValidatorCCC>(args&: *this);
9317 }
9318
9319 private:
9320 ASTContext &Context;
9321 FunctionDecl *OriginalFD;
9322 CXXRecordDecl *ExpectedParent;
9323};
9324
9325} // end anonymous namespace
9326
9327void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9328 TypoCorrectedFunctionDefinitions.insert(Ptr: F);
9329}
9330
9331/// Generate diagnostics for an invalid function redeclaration.
9332///
9333/// This routine handles generating the diagnostic messages for an invalid
9334/// function redeclaration, including finding possible similar declarations
9335/// or performing typo correction if there are no previous declarations with
9336/// the same name.
9337///
9338/// Returns a NamedDecl iff typo correction was performed and substituting in
9339/// the new declaration name does not cause new errors.
9340static NamedDecl *DiagnoseInvalidRedeclaration(
9341 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9342 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9343 DeclarationName Name = NewFD->getDeclName();
9344 DeclContext *NewDC = NewFD->getDeclContext();
9345 SmallVector<unsigned, 1> MismatchedParams;
9346 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9347 TypoCorrection Correction;
9348 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9349 unsigned DiagMsg =
9350 IsLocalFriend ? diag::err_no_matching_local_friend :
9351 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9352 diag::err_member_decl_does_not_match;
9353 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9354 IsLocalFriend ? Sema::LookupLocalFriendName
9355 : Sema::LookupOrdinaryName,
9356 RedeclarationKind::ForVisibleRedeclaration);
9357
9358 NewFD->setInvalidDecl();
9359 if (IsLocalFriend)
9360 SemaRef.LookupName(R&: Prev, S);
9361 else
9362 SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: NewDC);
9363 assert(!Prev.isAmbiguous() &&
9364 "Cannot have an ambiguity in previous-declaration lookup");
9365 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9366 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9367 MD ? MD->getParent() : nullptr);
9368 if (!Prev.empty()) {
9369 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9370 Func != FuncEnd; ++Func) {
9371 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *Func);
9372 if (FD &&
9373 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9374 // Add 1 to the index so that 0 can mean the mismatch didn't
9375 // involve a parameter
9376 unsigned ParamNum =
9377 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9378 NearMatches.push_back(Elt: std::make_pair(x&: FD, y&: ParamNum));
9379 }
9380 }
9381 // If the qualified name lookup yielded nothing, try typo correction
9382 } else if ((Correction = SemaRef.CorrectTypo(
9383 Typo: Prev.getLookupNameInfo(), LookupKind: Prev.getLookupKind(), S,
9384 SS: &ExtraArgs.D.getCXXScopeSpec(), CCC,
9385 Mode: CorrectTypoKind::ErrorRecovery,
9386 MemberContext: IsLocalFriend ? nullptr : NewDC))) {
9387 // Set up everything for the call to ActOnFunctionDeclarator
9388 ExtraArgs.D.SetIdentifier(Id: Correction.getCorrectionAsIdentifierInfo(),
9389 IdLoc: ExtraArgs.D.getIdentifierLoc());
9390 Previous.clear();
9391 Previous.setLookupName(Correction.getCorrection());
9392 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9393 CDeclEnd = Correction.end();
9394 CDecl != CDeclEnd; ++CDecl) {
9395 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *CDecl);
9396 if (FD && !FD->hasBody() &&
9397 hasSimilarParameters(Context&: SemaRef.Context, Declaration: FD, Definition: NewFD, Params&: MismatchedParams)) {
9398 Previous.addDecl(D: FD);
9399 }
9400 }
9401 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9402
9403 NamedDecl *Result;
9404 // Retry building the function declaration with the new previous
9405 // declarations, and with errors suppressed.
9406 {
9407 // Trap errors.
9408 Sema::SFINAETrap Trap(SemaRef);
9409
9410 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9411 // pieces need to verify the typo-corrected C++ declaration and hopefully
9412 // eliminate the need for the parameter pack ExtraArgs.
9413 Result = SemaRef.ActOnFunctionDeclarator(
9414 S: ExtraArgs.S, D&: ExtraArgs.D,
9415 DC: Correction.getCorrectionDecl()->getDeclContext(),
9416 TInfo: NewFD->getTypeSourceInfo(), Previous, TemplateParamLists: ExtraArgs.TemplateParamLists,
9417 AddToScope&: ExtraArgs.AddToScope);
9418
9419 if (Trap.hasErrorOccurred())
9420 Result = nullptr;
9421 }
9422
9423 if (Result) {
9424 // Determine which correction we picked.
9425 Decl *Canonical = Result->getCanonicalDecl();
9426 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9427 I != E; ++I)
9428 if ((*I)->getCanonicalDecl() == Canonical)
9429 Correction.setCorrectionDecl(*I);
9430
9431 // Let Sema know about the correction.
9432 SemaRef.MarkTypoCorrectedFunctionDefinition(F: Result);
9433 SemaRef.diagnoseTypo(
9434 Correction,
9435 TypoDiag: SemaRef.PDiag(DiagID: IsLocalFriend
9436 ? diag::err_no_matching_local_friend_suggest
9437 : diag::err_member_decl_does_not_match_suggest)
9438 << Name << NewDC << IsDefinition);
9439 return Result;
9440 }
9441
9442 // Pretend the typo correction never occurred
9443 ExtraArgs.D.SetIdentifier(Id: Name.getAsIdentifierInfo(),
9444 IdLoc: ExtraArgs.D.getIdentifierLoc());
9445 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9446 Previous.clear();
9447 Previous.setLookupName(Name);
9448 }
9449
9450 SemaRef.Diag(Loc: NewFD->getLocation(), DiagID: DiagMsg)
9451 << Name << NewDC << IsDefinition << NewFD->getLocation();
9452
9453 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(Val: NewFD);
9454 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9455 CXXRecordDecl *RD = NewMD->getParent();
9456 SemaRef.Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here)
9457 << RD->getName() << RD->getLocation();
9458 }
9459
9460 bool NewFDisConst = NewMD && NewMD->isConst();
9461
9462 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9463 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9464 NearMatch != NearMatchEnd; ++NearMatch) {
9465 FunctionDecl *FD = NearMatch->first;
9466 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9467 bool FDisConst = MD && MD->isConst();
9468 bool IsMember = MD || !IsLocalFriend;
9469
9470 // FIXME: These notes are poorly worded for the local friend case.
9471 if (unsigned Idx = NearMatch->second) {
9472 ParmVarDecl *FDParam = FD->getParamDecl(i: Idx-1);
9473 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9474 if (Loc.isInvalid()) Loc = FD->getLocation();
9475 SemaRef.Diag(Loc, DiagID: IsMember ? diag::note_member_def_close_param_match
9476 : diag::note_local_decl_close_param_match)
9477 << Idx << FDParam->getType()
9478 << NewFD->getParamDecl(i: Idx - 1)->getType();
9479 } else if (FDisConst != NewFDisConst) {
9480 auto DB = SemaRef.Diag(Loc: FD->getLocation(),
9481 DiagID: diag::note_member_def_close_const_match)
9482 << NewFDisConst << FD->getSourceRange().getEnd();
9483 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9484 DB << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc().getLocWithOffset(Offset: 1),
9485 Code: " const");
9486 else if (FTI.hasMethodTypeQualifiers() &&
9487 FTI.getConstQualifierLoc().isValid())
9488 DB << FixItHint::CreateRemoval(RemoveRange: FTI.getConstQualifierLoc());
9489 } else {
9490 SemaRef.Diag(Loc: FD->getLocation(),
9491 DiagID: IsMember ? diag::note_member_def_close_match
9492 : diag::note_local_decl_close_match);
9493 }
9494 }
9495 return nullptr;
9496}
9497
9498static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9499 switch (D.getDeclSpec().getStorageClassSpec()) {
9500 default: llvm_unreachable("Unknown storage class!");
9501 case DeclSpec::SCS_auto:
9502 case DeclSpec::SCS_register:
9503 case DeclSpec::SCS_mutable:
9504 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9505 DiagID: diag::err_typecheck_sclass_func);
9506 D.getMutableDeclSpec().ClearStorageClassSpecs();
9507 D.setInvalidType();
9508 break;
9509 case DeclSpec::SCS_unspecified: break;
9510 case DeclSpec::SCS_extern:
9511 if (D.getDeclSpec().isExternInLinkageSpec())
9512 return SC_None;
9513 return SC_Extern;
9514 case DeclSpec::SCS_static: {
9515 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9516 // C99 6.7.1p5:
9517 // The declaration of an identifier for a function that has
9518 // block scope shall have no explicit storage-class specifier
9519 // other than extern
9520 // See also (C++ [dcl.stc]p4).
9521 SemaRef.Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
9522 DiagID: diag::err_static_block_func);
9523 break;
9524 } else
9525 return SC_Static;
9526 }
9527 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9528 }
9529
9530 // No explicit storage class has already been returned
9531 return SC_None;
9532}
9533
9534static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9535 DeclContext *DC, QualType &R,
9536 TypeSourceInfo *TInfo,
9537 StorageClass SC,
9538 bool &IsVirtualOkay) {
9539 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9540 DeclarationName Name = NameInfo.getName();
9541
9542 FunctionDecl *NewFD = nullptr;
9543 bool isInline = D.getDeclSpec().isInlineSpecified();
9544
9545 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9546 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9547 (SemaRef.getLangOpts().C23 &&
9548 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9549
9550 if (SemaRef.getLangOpts().C23)
9551 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9552 DiagID: diag::err_c23_constexpr_not_variable);
9553 else
9554 SemaRef.Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
9555 DiagID: diag::err_constexpr_wrong_decl_kind)
9556 << static_cast<int>(ConstexprKind);
9557 ConstexprKind = ConstexprSpecKind::Unspecified;
9558 D.getMutableDeclSpec().ClearConstexprSpec();
9559 }
9560
9561 if (!SemaRef.getLangOpts().CPlusPlus) {
9562 // Determine whether the function was written with a prototype. This is
9563 // true when:
9564 // - there is a prototype in the declarator, or
9565 // - the type R of the function is some kind of typedef or other non-
9566 // attributed reference to a type name (which eventually refers to a
9567 // function type). Note, we can't always look at the adjusted type to
9568 // check this case because attributes may cause a non-function
9569 // declarator to still have a function type. e.g.,
9570 // typedef void func(int a);
9571 // __attribute__((noreturn)) func other_func; // This has a prototype
9572 bool HasPrototype =
9573 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9574 (D.getDeclSpec().isTypeRep() &&
9575 SemaRef.GetTypeFromParser(Ty: D.getDeclSpec().getRepAsType(), TInfo: nullptr)
9576 ->isFunctionProtoType()) ||
9577 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9578 assert(
9579 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9580 "Strict prototypes are required");
9581
9582 NewFD = FunctionDecl::Create(
9583 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9584 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline, hasWrittenPrototype: HasPrototype,
9585 ConstexprKind: ConstexprSpecKind::Unspecified,
9586 /*TrailingRequiresClause=*/{});
9587 if (D.isInvalidType())
9588 NewFD->setInvalidDecl();
9589
9590 return NewFD;
9591 }
9592
9593 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9594 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9595
9596 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9597
9598 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9599 // This is a C++ constructor declaration.
9600 assert(DC->isRecord() &&
9601 "Constructors can only be declared in a member context");
9602
9603 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9604 return CXXConstructorDecl::Create(
9605 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9606 TInfo, ES: ExplicitSpecifier, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(),
9607 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9608 Inherited: InheritedConstructor(), TrailingRequiresClause);
9609
9610 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9611 // This is a C++ destructor declaration.
9612 if (DC->isRecord()) {
9613 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9614 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC);
9615 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9616 C&: SemaRef.Context, RD: Record, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo,
9617 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9618 /*isImplicitlyDeclared=*/false, ConstexprKind,
9619 TrailingRequiresClause);
9620 // User defined destructors start as not selected if the class definition is still
9621 // not done.
9622 if (Record->isBeingDefined())
9623 NewDD->setIneligibleOrNotSelected(true);
9624
9625 // If the destructor needs an implicit exception specification, set it
9626 // now. FIXME: It'd be nice to be able to create the right type to start
9627 // with, but the type needs to reference the destructor declaration.
9628 if (SemaRef.getLangOpts().CPlusPlus11)
9629 SemaRef.AdjustDestructorExceptionSpec(Destructor: NewDD);
9630
9631 IsVirtualOkay = true;
9632 return NewDD;
9633
9634 } else {
9635 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_not_member);
9636 D.setInvalidType();
9637
9638 // Create a FunctionDecl to satisfy the function definition parsing
9639 // code path.
9640 return FunctionDecl::Create(
9641 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NLoc: D.getIdentifierLoc(), N: Name, T: R,
9642 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9643 /*hasPrototype=*/hasWrittenPrototype: true, ConstexprKind, TrailingRequiresClause);
9644 }
9645
9646 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9647 if (!DC->isRecord()) {
9648 SemaRef.Diag(Loc: D.getIdentifierLoc(),
9649 DiagID: diag::err_conv_function_not_member);
9650 return nullptr;
9651 }
9652
9653 SemaRef.CheckConversionDeclarator(D, R, SC);
9654 if (D.isInvalidType())
9655 return nullptr;
9656
9657 IsVirtualOkay = true;
9658 return CXXConversionDecl::Create(
9659 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9660 TInfo, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9661 ES: ExplicitSpecifier, ConstexprKind, EndLocation: SourceLocation(),
9662 TrailingRequiresClause);
9663
9664 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9665 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9666 return nullptr;
9667 return CXXDeductionGuideDecl::Create(
9668 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), ES: ExplicitSpecifier, NameInfo, T: R,
9669 TInfo, EndLocation: D.getEndLoc(), /*Ctor=*/nullptr,
9670 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9671 } else if (DC->isRecord()) {
9672 // If the name of the function is the same as the name of the record,
9673 // then this must be an invalid constructor that has a return type.
9674 // (The parser checks for a return type and makes the declarator a
9675 // constructor if it has no return type).
9676 if (Name.getAsIdentifierInfo() &&
9677 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(Val: DC)->getIdentifier()){
9678 SemaRef.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_return_type)
9679 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9680 << SourceRange(D.getIdentifierLoc());
9681 return nullptr;
9682 }
9683
9684 // This is a C++ method declaration.
9685 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9686 C&: SemaRef.Context, RD: cast<CXXRecordDecl>(Val: DC), StartLoc: D.getBeginLoc(), NameInfo, T: R,
9687 TInfo, SC, UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9688 ConstexprKind, EndLocation: SourceLocation(), TrailingRequiresClause);
9689 IsVirtualOkay = !Ret->isStatic();
9690 return Ret;
9691 } else {
9692 bool isFriend =
9693 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9694 if (!isFriend && SemaRef.CurContext->isRecord())
9695 return nullptr;
9696
9697 // Determine whether the function was written with a
9698 // prototype. This true when:
9699 // - we're in C++ (where every function has a prototype),
9700 return FunctionDecl::Create(
9701 C&: SemaRef.Context, DC, StartLoc: D.getBeginLoc(), NameInfo, T: R, TInfo, SC,
9702 UsesFPIntrin: SemaRef.getCurFPFeatures().isFPConstrained(), isInlineSpecified: isInline,
9703 hasWrittenPrototype: true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9704 }
9705}
9706
9707enum OpenCLParamType {
9708 ValidKernelParam,
9709 PtrPtrKernelParam,
9710 PtrKernelParam,
9711 InvalidAddrSpacePtrKernelParam,
9712 InvalidKernelParam,
9713 RecordKernelParam
9714};
9715
9716static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9717 // Size dependent types are just typedefs to normal integer types
9718 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9719 // integers other than by their names.
9720 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9721
9722 // Remove typedefs one by one until we reach a typedef
9723 // for a size dependent type.
9724 QualType DesugaredTy = Ty;
9725 do {
9726 ArrayRef<StringRef> Names(SizeTypeNames);
9727 auto Match = llvm::find(Range&: Names, Val: DesugaredTy.getUnqualifiedType().getAsString());
9728 if (Names.end() != Match)
9729 return true;
9730
9731 Ty = DesugaredTy;
9732 DesugaredTy = Ty.getSingleStepDesugaredType(Context: C);
9733 } while (DesugaredTy != Ty);
9734
9735 return false;
9736}
9737
9738static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9739 if (PT->isDependentType())
9740 return InvalidKernelParam;
9741
9742 if (PT->isPointerOrReferenceType()) {
9743 QualType PointeeType = PT->getPointeeType();
9744 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9745 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9746 PointeeType.getAddressSpace() == LangAS::Default)
9747 return InvalidAddrSpacePtrKernelParam;
9748
9749 if (PointeeType->isPointerType()) {
9750 // This is a pointer to pointer parameter.
9751 // Recursively check inner type.
9752 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PT: PointeeType);
9753 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9754 ParamKind == InvalidKernelParam)
9755 return ParamKind;
9756
9757 // OpenCL v3.0 s6.11.a:
9758 // A restriction to pass pointers to pointers only applies to OpenCL C
9759 // v1.2 or below.
9760 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9761 return ValidKernelParam;
9762
9763 return PtrPtrKernelParam;
9764 }
9765
9766 // C++ for OpenCL v1.0 s2.4:
9767 // Moreover the types used in parameters of the kernel functions must be:
9768 // Standard layout types for pointer parameters. The same applies to
9769 // reference if an implementation supports them in kernel parameters.
9770 if (S.getLangOpts().OpenCLCPlusPlus &&
9771 !S.getOpenCLOptions().isAvailableOption(
9772 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts())) {
9773 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9774 bool IsStandardLayoutType = true;
9775 if (CXXRec) {
9776 // If template type is not ODR-used its definition is only available
9777 // in the template definition not its instantiation.
9778 // FIXME: This logic doesn't work for types that depend on template
9779 // parameter (PR58590).
9780 if (!CXXRec->hasDefinition())
9781 CXXRec = CXXRec->getTemplateInstantiationPattern();
9782 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9783 IsStandardLayoutType = false;
9784 }
9785 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9786 !IsStandardLayoutType)
9787 return InvalidKernelParam;
9788 }
9789
9790 // OpenCL v1.2 s6.9.p:
9791 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9792 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9793 return ValidKernelParam;
9794
9795 return PtrKernelParam;
9796 }
9797
9798 // OpenCL v1.2 s6.9.k:
9799 // Arguments to kernel functions in a program cannot be declared with the
9800 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9801 // uintptr_t or a struct and/or union that contain fields declared to be one
9802 // of these built-in scalar types.
9803 if (isOpenCLSizeDependentType(C&: S.getASTContext(), Ty: PT))
9804 return InvalidKernelParam;
9805
9806 if (PT->isImageType())
9807 return PtrKernelParam;
9808
9809 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9810 return InvalidKernelParam;
9811
9812 // OpenCL extension spec v1.2 s9.5:
9813 // This extension adds support for half scalar and vector types as built-in
9814 // types that can be used for arithmetic operations, conversions etc.
9815 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: S.getLangOpts()) &&
9816 PT->isHalfType())
9817 return InvalidKernelParam;
9818
9819 // Look into an array argument to check if it has a forbidden type.
9820 if (PT->isArrayType()) {
9821 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9822 // Call ourself to check an underlying type of an array. Since the
9823 // getPointeeOrArrayElementType returns an innermost type which is not an
9824 // array, this recursive call only happens once.
9825 return getOpenCLKernelParameterType(S, PT: QualType(UnderlyingTy, 0));
9826 }
9827
9828 // C++ for OpenCL v1.0 s2.4:
9829 // Moreover the types used in parameters of the kernel functions must be:
9830 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9831 // types) for parameters passed by value;
9832 if (S.getLangOpts().OpenCLCPlusPlus &&
9833 !S.getOpenCLOptions().isAvailableOption(
9834 Ext: "__cl_clang_non_portable_kernel_param_types", LO: S.getLangOpts()) &&
9835 !PT->isOpenCLSpecificType() && !PT.isPODType(Context: S.Context))
9836 return InvalidKernelParam;
9837
9838 if (PT->isRecordType())
9839 return RecordKernelParam;
9840
9841 return ValidKernelParam;
9842}
9843
9844static void checkIsValidOpenCLKernelParameter(
9845 Sema &S,
9846 Declarator &D,
9847 ParmVarDecl *Param,
9848 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9849 QualType PT = Param->getType();
9850
9851 // Cache the valid types we encounter to avoid rechecking structs that are
9852 // used again
9853 if (ValidTypes.count(Ptr: PT.getTypePtr()))
9854 return;
9855
9856 switch (getOpenCLKernelParameterType(S, PT)) {
9857 case PtrPtrKernelParam:
9858 // OpenCL v3.0 s6.11.a:
9859 // A kernel function argument cannot be declared as a pointer to a pointer
9860 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9861 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_ptrptr_kernel_param);
9862 D.setInvalidType();
9863 return;
9864
9865 case InvalidAddrSpacePtrKernelParam:
9866 // OpenCL v1.0 s6.5:
9867 // __kernel function arguments declared to be a pointer of a type can point
9868 // to one of the following address spaces only : __global, __local or
9869 // __constant.
9870 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_kernel_arg_address_space);
9871 D.setInvalidType();
9872 return;
9873
9874 // OpenCL v1.2 s6.9.k:
9875 // Arguments to kernel functions in a program cannot be declared with the
9876 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9877 // uintptr_t or a struct and/or union that contain fields declared to be
9878 // one of these built-in scalar types.
9879
9880 case InvalidKernelParam:
9881 // OpenCL v1.2 s6.8 n:
9882 // A kernel function argument cannot be declared
9883 // of event_t type.
9884 // Do not diagnose half type since it is diagnosed as invalid argument
9885 // type for any function elsewhere.
9886 if (!PT->isHalfType()) {
9887 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9888
9889 // Explain what typedefs are involved.
9890 const TypedefType *Typedef = nullptr;
9891 while ((Typedef = PT->getAs<TypedefType>())) {
9892 SourceLocation Loc = Typedef->getDecl()->getLocation();
9893 // SourceLocation may be invalid for a built-in type.
9894 if (Loc.isValid())
9895 S.Diag(Loc, DiagID: diag::note_entity_declared_at) << PT;
9896 PT = Typedef->desugar();
9897 }
9898 }
9899
9900 D.setInvalidType();
9901 return;
9902
9903 case PtrKernelParam:
9904 case ValidKernelParam:
9905 ValidTypes.insert(Ptr: PT.getTypePtr());
9906 return;
9907
9908 case RecordKernelParam:
9909 break;
9910 }
9911
9912 // Track nested structs we will inspect
9913 SmallVector<const Decl *, 4> VisitStack;
9914
9915 // Track where we are in the nested structs. Items will migrate from
9916 // VisitStack to HistoryStack as we do the DFS for bad field.
9917 SmallVector<const FieldDecl *, 4> HistoryStack;
9918 HistoryStack.push_back(Elt: nullptr);
9919
9920 // At this point we already handled everything except of a RecordType.
9921 assert(PT->isRecordType() && "Unexpected type.");
9922 const auto *PD = PT->castAsRecordDecl();
9923 VisitStack.push_back(Elt: PD);
9924 assert(VisitStack.back() && "First decl null?");
9925
9926 do {
9927 const Decl *Next = VisitStack.pop_back_val();
9928 if (!Next) {
9929 assert(!HistoryStack.empty());
9930 // Found a marker, we have gone up a level
9931 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9932 ValidTypes.insert(Ptr: Hist->getType().getTypePtr());
9933
9934 continue;
9935 }
9936
9937 // Adds everything except the original parameter declaration (which is not a
9938 // field itself) to the history stack.
9939 const RecordDecl *RD;
9940 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: Next)) {
9941 HistoryStack.push_back(Elt: Field);
9942
9943 QualType FieldTy = Field->getType();
9944 // Other field types (known to be valid or invalid) are handled while we
9945 // walk around RecordDecl::fields().
9946 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9947 "Unexpected type.");
9948 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9949
9950 RD = FieldRecTy->castAsRecordDecl();
9951 } else {
9952 RD = cast<RecordDecl>(Val: Next);
9953 }
9954
9955 // Add a null marker so we know when we've gone back up a level
9956 VisitStack.push_back(Elt: nullptr);
9957
9958 for (const auto *FD : RD->fields()) {
9959 QualType QT = FD->getType();
9960
9961 if (ValidTypes.count(Ptr: QT.getTypePtr()))
9962 continue;
9963
9964 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, PT: QT);
9965 if (ParamType == ValidKernelParam)
9966 continue;
9967
9968 if (ParamType == RecordKernelParam) {
9969 VisitStack.push_back(Elt: FD);
9970 continue;
9971 }
9972
9973 // OpenCL v1.2 s6.9.p:
9974 // Arguments to kernel functions that are declared to be a struct or union
9975 // do not allow OpenCL objects to be passed as elements of the struct or
9976 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9977 // of SVM.
9978 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9979 ParamType == InvalidAddrSpacePtrKernelParam) {
9980 S.Diag(Loc: Param->getLocation(),
9981 DiagID: diag::err_record_with_pointers_kernel_param)
9982 << PT->isUnionType()
9983 << PT;
9984 } else {
9985 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_bad_kernel_param_type) << PT;
9986 }
9987
9988 S.Diag(Loc: PD->getLocation(), DiagID: diag::note_within_field_of_type)
9989 << PD->getDeclName();
9990
9991 // We have an error, now let's go back up through history and show where
9992 // the offending field came from
9993 for (ArrayRef<const FieldDecl *>::const_iterator
9994 I = HistoryStack.begin() + 1,
9995 E = HistoryStack.end();
9996 I != E; ++I) {
9997 const FieldDecl *OuterField = *I;
9998 S.Diag(Loc: OuterField->getLocation(), DiagID: diag::note_within_field_of_type)
9999 << OuterField->getType();
10000 }
10001
10002 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_illegal_field_declared_here)
10003 << QT->isPointerType()
10004 << QT;
10005 D.setInvalidType();
10006 return;
10007 }
10008 } while (!VisitStack.empty());
10009}
10010
10011/// Find the DeclContext in which a tag is implicitly declared if we see an
10012/// elaborated type specifier in the specified context, and lookup finds
10013/// nothing.
10014static DeclContext *getTagInjectionContext(DeclContext *DC) {
10015 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10016 DC = DC->getParent();
10017 return DC;
10018}
10019
10020/// Find the Scope in which a tag is implicitly declared if we see an
10021/// elaborated type specifier in the specified context, and lookup finds
10022/// nothing.
10023static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10024 while (S->isClassScope() ||
10025 (LangOpts.CPlusPlus &&
10026 S->isFunctionPrototypeScope()) ||
10027 ((S->getFlags() & Scope::DeclScope) == 0) ||
10028 (S->getEntity() && S->getEntity()->isTransparentContext()))
10029 S = S->getParent();
10030 return S;
10031}
10032
10033/// Determine whether a declaration matches a known function in namespace std.
10034static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
10035 unsigned BuiltinID) {
10036 switch (BuiltinID) {
10037 case Builtin::BI__GetExceptionInfo:
10038 // No type checking whatsoever.
10039 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10040
10041 case Builtin::BIaddressof:
10042 case Builtin::BI__addressof:
10043 case Builtin::BIforward:
10044 case Builtin::BIforward_like:
10045 case Builtin::BImove:
10046 case Builtin::BImove_if_noexcept:
10047 case Builtin::BIas_const: {
10048 // Ensure that we don't treat the algorithm
10049 // OutputIt std::move(InputIt, InputIt, OutputIt)
10050 // as the builtin std::move.
10051 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10052 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10053 }
10054
10055 default:
10056 return false;
10057 }
10058}
10059
10060NamedDecl*
10061Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
10062 TypeSourceInfo *TInfo, LookupResult &Previous,
10063 MultiTemplateParamsArg TemplateParamListsRef,
10064 bool &AddToScope) {
10065 QualType R = TInfo->getType();
10066
10067 assert(R->isFunctionType());
10068 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10069 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_decl_cmse_ns_call);
10070
10071 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10072 llvm::append_range(C&: TemplateParamLists, R&: TemplateParamListsRef);
10073 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
10074 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10075 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10076 TemplateParamLists.back() = Invented;
10077 else
10078 TemplateParamLists.push_back(Elt: Invented);
10079 }
10080
10081 // TODO: consider using NameInfo for diagnostic.
10082 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10083 DeclarationName Name = NameInfo.getName();
10084 StorageClass SC = getFunctionStorageClass(SemaRef&: *this, D);
10085
10086 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
10087 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
10088 DiagID: diag::err_invalid_thread)
10089 << DeclSpec::getSpecifierName(S: TSCS);
10090
10091 if (D.isFirstDeclarationOfMember())
10092 adjustMemberFunctionCC(
10093 T&: R, HasThisPointer: !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
10094 IsCtorOrDtor: D.isCtorOrDtor(), Loc: D.getIdentifierLoc());
10095
10096 bool isFriend = false;
10097 FunctionTemplateDecl *FunctionTemplate = nullptr;
10098 bool isMemberSpecialization = false;
10099 bool isFunctionTemplateSpecialization = false;
10100
10101 bool HasExplicitTemplateArgs = false;
10102 TemplateArgumentListInfo TemplateArgs;
10103
10104 bool isVirtualOkay = false;
10105
10106 DeclContext *OriginalDC = DC;
10107 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10108
10109 FunctionDecl *NewFD = CreateNewFunctionDecl(SemaRef&: *this, D, DC, R, TInfo, SC,
10110 IsVirtualOkay&: isVirtualOkay);
10111 if (!NewFD) return nullptr;
10112
10113 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10114 NewFD->setTopLevelDeclInObjCContainer();
10115
10116 // Set the lexical context. If this is a function-scope declaration, or has a
10117 // C++ scope specifier, or is the object of a friend declaration, the lexical
10118 // context will be different from the semantic context.
10119 NewFD->setLexicalDeclContext(CurContext);
10120
10121 if (IsLocalExternDecl)
10122 NewFD->setLocalExternDecl();
10123
10124 if (getLangOpts().CPlusPlus) {
10125 // The rules for implicit inlines changed in C++20 for methods and friends
10126 // with an in-class definition (when such a definition is not attached to
10127 // the global module). This does not affect declarations that are already
10128 // inline (whether explicitly or implicitly by being declared constexpr,
10129 // consteval, etc).
10130 // FIXME: We need a better way to separate C++ standard and clang modules.
10131 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10132 !NewFD->getOwningModule() ||
10133 NewFD->isFromGlobalModule() ||
10134 NewFD->getOwningModule()->isHeaderLikeModule();
10135 bool isInline = D.getDeclSpec().isInlineSpecified();
10136 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10137 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10138 isFriend = D.getDeclSpec().isFriendSpecified();
10139 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10140 // Pre-C++20 [class.friend]p5
10141 // A function can be defined in a friend declaration of a
10142 // class . . . . Such a function is implicitly inline.
10143 // Post C++20 [class.friend]p7
10144 // Such a function is implicitly an inline function if it is attached
10145 // to the global module.
10146 NewFD->setImplicitlyInline();
10147 }
10148
10149 // If this is a method defined in an __interface, and is not a constructor
10150 // or an overloaded operator, then set the pure flag (isVirtual will already
10151 // return true).
10152 if (const CXXRecordDecl *Parent =
10153 dyn_cast<CXXRecordDecl>(Val: NewFD->getDeclContext())) {
10154 if (Parent->isInterface() && cast<CXXMethodDecl>(Val: NewFD)->isUserProvided())
10155 NewFD->setIsPureVirtual(true);
10156
10157 // C++ [class.union]p2
10158 // A union can have member functions, but not virtual functions.
10159 if (isVirtual && Parent->isUnion()) {
10160 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_virtual_in_union);
10161 NewFD->setInvalidDecl();
10162 }
10163 if ((Parent->isClass() || Parent->isStruct()) &&
10164 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10165 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10166 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10167 if (auto *Def = Parent->getDefinition())
10168 Def->setInitMethod(true);
10169 }
10170 }
10171
10172 SetNestedNameSpecifier(S&: *this, DD: NewFD, D);
10173 isMemberSpecialization = false;
10174 isFunctionTemplateSpecialization = false;
10175 if (D.isInvalidType())
10176 NewFD->setInvalidDecl();
10177
10178 // Match up the template parameter lists with the scope specifier, then
10179 // determine whether we have a template or a template specialization.
10180 bool Invalid = false;
10181 TemplateIdAnnotation *TemplateId =
10182 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
10183 ? D.getName().TemplateId
10184 : nullptr;
10185 TemplateParameterList *TemplateParams =
10186 MatchTemplateParametersToScopeSpecifier(
10187 DeclStartLoc: D.getDeclSpec().getBeginLoc(), DeclLoc: D.getIdentifierLoc(),
10188 SS: D.getCXXScopeSpec(), TemplateId, ParamLists: TemplateParamLists, IsFriend: isFriend,
10189 IsMemberSpecialization&: isMemberSpecialization, Invalid);
10190 if (TemplateParams) {
10191 // Check that we can declare a template here.
10192 if (CheckTemplateDeclScope(S, TemplateParams))
10193 NewFD->setInvalidDecl();
10194
10195 if (TemplateParams->size() > 0) {
10196 // This is a function template
10197
10198 // A destructor cannot be a template.
10199 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
10200 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_template);
10201 NewFD->setInvalidDecl();
10202 // Function template with explicit template arguments.
10203 } else if (TemplateId) {
10204 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_function_template_partial_spec)
10205 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10206 NewFD->setInvalidDecl();
10207 }
10208
10209 // If we're adding a template to a dependent context, we may need to
10210 // rebuilding some of the types used within the template parameter list,
10211 // now that we know what the current instantiation is.
10212 if (DC->isDependentContext()) {
10213 ContextRAII SavedContext(*this, DC);
10214 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
10215 Invalid = true;
10216 }
10217
10218 FunctionTemplate = FunctionTemplateDecl::Create(C&: Context, DC,
10219 L: NewFD->getLocation(),
10220 Name, Params: TemplateParams,
10221 Decl: NewFD);
10222 FunctionTemplate->setLexicalDeclContext(CurContext);
10223 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
10224
10225 // For source fidelity, store the other template param lists.
10226 if (TemplateParamLists.size() > 1) {
10227 NewFD->setTemplateParameterListsInfo(Context,
10228 TPLists: ArrayRef<TemplateParameterList *>(TemplateParamLists)
10229 .drop_back(N: 1));
10230 }
10231 } else {
10232 // This is a function template specialization.
10233 isFunctionTemplateSpecialization = true;
10234 // For source fidelity, store all the template param lists.
10235 if (TemplateParamLists.size() > 0)
10236 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10237
10238 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10239 if (isFriend) {
10240 // We want to remove the "template<>", found here.
10241 SourceRange RemoveRange = TemplateParams->getSourceRange();
10242
10243 // If we remove the template<> and the name is not a
10244 // template-id, we're actually silently creating a problem:
10245 // the friend declaration will refer to an untemplated decl,
10246 // and clearly the user wants a template specialization. So
10247 // we need to insert '<>' after the name.
10248 SourceLocation InsertLoc;
10249 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10250 InsertLoc = D.getName().getSourceRange().getEnd();
10251 InsertLoc = getLocForEndOfToken(Loc: InsertLoc);
10252 }
10253
10254 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_spec_decl_friend)
10255 << Name << RemoveRange
10256 << FixItHint::CreateRemoval(RemoveRange)
10257 << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: "<>");
10258 Invalid = true;
10259
10260 // Recover by faking up an empty template argument list.
10261 HasExplicitTemplateArgs = true;
10262 TemplateArgs.setLAngleLoc(InsertLoc);
10263 TemplateArgs.setRAngleLoc(InsertLoc);
10264 }
10265 }
10266 } else {
10267 // Check that we can declare a template here.
10268 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10269 CheckTemplateDeclScope(S, TemplateParams: TemplateParamLists.back()))
10270 NewFD->setInvalidDecl();
10271
10272 // All template param lists were matched against the scope specifier:
10273 // this is NOT (an explicit specialization of) a template.
10274 if (TemplateParamLists.size() > 0)
10275 // For source fidelity, store all the template param lists.
10276 NewFD->setTemplateParameterListsInfo(Context, TPLists: TemplateParamLists);
10277
10278 // "friend void foo<>(int);" is an implicit specialization decl.
10279 if (isFriend && TemplateId)
10280 isFunctionTemplateSpecialization = true;
10281 }
10282
10283 // If this is a function template specialization and the unqualified-id of
10284 // the declarator-id is a template-id, convert the template argument list
10285 // into our AST format and check for unexpanded packs.
10286 if (isFunctionTemplateSpecialization && TemplateId) {
10287 HasExplicitTemplateArgs = true;
10288
10289 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10290 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10291 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10292 TemplateId->NumArgs);
10293 translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgs);
10294
10295 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10296 // declaration of a function template partial specialization? Should we
10297 // consider the unexpanded pack context to be a partial specialization?
10298 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10299 if (DiagnoseUnexpandedParameterPack(
10300 Arg: ArgLoc, UPPC: isFriend ? UPPC_FriendDeclaration
10301 : UPPC_ExplicitSpecialization))
10302 NewFD->setInvalidDecl();
10303 }
10304 }
10305
10306 if (Invalid) {
10307 NewFD->setInvalidDecl();
10308 if (FunctionTemplate)
10309 FunctionTemplate->setInvalidDecl();
10310 }
10311
10312 // C++ [dcl.fct.spec]p5:
10313 // The virtual specifier shall only be used in declarations of
10314 // nonstatic class member functions that appear within a
10315 // member-specification of a class declaration; see 10.3.
10316 //
10317 if (isVirtual && !NewFD->isInvalidDecl()) {
10318 if (!isVirtualOkay) {
10319 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10320 DiagID: diag::err_virtual_non_function);
10321 } else if (!CurContext->isRecord()) {
10322 // 'virtual' was specified outside of the class.
10323 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10324 DiagID: diag::err_virtual_out_of_class)
10325 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10326 } else if (NewFD->getDescribedFunctionTemplate()) {
10327 // C++ [temp.mem]p3:
10328 // A member function template shall not be virtual.
10329 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(),
10330 DiagID: diag::err_virtual_member_function_template)
10331 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getVirtualSpecLoc());
10332 } else {
10333 // Okay: Add virtual to the method.
10334 NewFD->setVirtualAsWritten(true);
10335 }
10336
10337 if (getLangOpts().CPlusPlus14 &&
10338 NewFD->getReturnType()->isUndeducedType())
10339 Diag(Loc: D.getDeclSpec().getVirtualSpecLoc(), DiagID: diag::err_auto_fn_virtual);
10340 }
10341
10342 // C++ [dcl.fct.spec]p3:
10343 // The inline specifier shall not appear on a block scope function
10344 // declaration.
10345 if (isInline && !NewFD->isInvalidDecl()) {
10346 if (CurContext->isFunctionOrMethod()) {
10347 // 'inline' is not allowed on block scope function declaration.
10348 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10349 DiagID: diag::err_inline_declaration_block_scope) << Name
10350 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10351 }
10352 }
10353
10354 // C++ [dcl.fct.spec]p6:
10355 // The explicit specifier shall be used only in the declaration of a
10356 // constructor or conversion function within its class definition;
10357 // see 12.3.1 and 12.3.2.
10358 if (hasExplicit && !NewFD->isInvalidDecl() &&
10359 !isa<CXXDeductionGuideDecl>(Val: NewFD)) {
10360 if (!CurContext->isRecord()) {
10361 // 'explicit' was specified outside of the class.
10362 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10363 DiagID: diag::err_explicit_out_of_class)
10364 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10365 } else if (!isa<CXXConstructorDecl>(Val: NewFD) &&
10366 !isa<CXXConversionDecl>(Val: NewFD)) {
10367 // 'explicit' was specified on a function that wasn't a constructor
10368 // or conversion function.
10369 Diag(Loc: D.getDeclSpec().getExplicitSpecLoc(),
10370 DiagID: diag::err_explicit_non_ctor_or_conv_function)
10371 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getExplicitSpecRange());
10372 }
10373 }
10374
10375 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10376 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10377 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10378 // are implicitly inline.
10379 NewFD->setImplicitlyInline();
10380
10381 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10382 // be either constructors or to return a literal type. Therefore,
10383 // destructors cannot be declared constexpr.
10384 if (isa<CXXDestructorDecl>(Val: NewFD) &&
10385 (!getLangOpts().CPlusPlus20 ||
10386 ConstexprKind == ConstexprSpecKind::Consteval)) {
10387 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(), DiagID: diag::err_constexpr_dtor)
10388 << static_cast<int>(ConstexprKind);
10389 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10390 ? ConstexprSpecKind::Unspecified
10391 : ConstexprSpecKind::Constexpr);
10392 }
10393 // C++20 [dcl.constexpr]p2: An allocation function, or a
10394 // deallocation function shall not be declared with the consteval
10395 // specifier.
10396 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10397 NewFD->getDeclName().isAnyOperatorNewOrDelete()) {
10398 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10399 DiagID: diag::err_invalid_consteval_decl_kind)
10400 << NewFD;
10401 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10402 }
10403 }
10404
10405 // If __module_private__ was specified, mark the function accordingly.
10406 if (D.getDeclSpec().isModulePrivateSpecified()) {
10407 if (isFunctionTemplateSpecialization) {
10408 SourceLocation ModulePrivateLoc
10409 = D.getDeclSpec().getModulePrivateSpecLoc();
10410 Diag(Loc: ModulePrivateLoc, DiagID: diag::err_module_private_specialization)
10411 << 0
10412 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
10413 } else {
10414 NewFD->setModulePrivate();
10415 if (FunctionTemplate)
10416 FunctionTemplate->setModulePrivate();
10417 }
10418 }
10419
10420 if (isFriend) {
10421 if (FunctionTemplate) {
10422 FunctionTemplate->setObjectOfFriendDecl();
10423 FunctionTemplate->setAccess(AS_public);
10424 }
10425 NewFD->setObjectOfFriendDecl();
10426 NewFD->setAccess(AS_public);
10427 }
10428
10429 // If a function is defined as defaulted or deleted, mark it as such now.
10430 // We'll do the relevant checks on defaulted / deleted functions later.
10431 switch (D.getFunctionDefinitionKind()) {
10432 case FunctionDefinitionKind::Declaration:
10433 case FunctionDefinitionKind::Definition:
10434 break;
10435
10436 case FunctionDefinitionKind::Defaulted:
10437 NewFD->setDefaulted();
10438 break;
10439
10440 case FunctionDefinitionKind::Deleted:
10441 NewFD->setDeletedAsWritten();
10442 break;
10443 }
10444
10445 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(Val: NewFD) && DC == CurContext &&
10446 D.isFunctionDefinition()) {
10447 // Pre C++20 [class.mfct]p2:
10448 // A member function may be defined (8.4) in its class definition, in
10449 // which case it is an inline member function (7.1.2)
10450 // Post C++20 [class.mfct]p1:
10451 // If a member function is attached to the global module and is defined
10452 // in its class definition, it is inline.
10453 NewFD->setImplicitlyInline();
10454 }
10455
10456 if (!isFriend && SC != SC_None) {
10457 // C++ [temp.expl.spec]p2:
10458 // The declaration in an explicit-specialization shall not be an
10459 // export-declaration. An explicit specialization shall not use a
10460 // storage-class-specifier other than thread_local.
10461 //
10462 // We diagnose friend declarations with storage-class-specifiers
10463 // elsewhere.
10464 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10465 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10466 DiagID: diag::ext_explicit_specialization_storage_class)
10467 << FixItHint::CreateRemoval(
10468 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10469 }
10470
10471 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10472 assert(isa<CXXMethodDecl>(NewFD) &&
10473 "Out-of-line member function should be a CXXMethodDecl");
10474 // C++ [class.static]p1:
10475 // A data or function member of a class may be declared static
10476 // in a class definition, in which case it is a static member of
10477 // the class.
10478
10479 // Complain about the 'static' specifier if it's on an out-of-line
10480 // member function definition.
10481
10482 // MSVC permits the use of a 'static' storage specifier on an
10483 // out-of-line member function template declaration and class member
10484 // template declaration (MSVC versions before 2015), warn about this.
10485 Diag(Loc: D.getDeclSpec().getStorageClassSpecLoc(),
10486 DiagID: ((!getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
10487 cast<CXXRecordDecl>(Val: DC)->getDescribedClassTemplate()) ||
10488 (getLangOpts().MSVCCompat &&
10489 NewFD->getDescribedFunctionTemplate()))
10490 ? diag::ext_static_out_of_line
10491 : diag::err_static_out_of_line)
10492 << FixItHint::CreateRemoval(
10493 RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10494 }
10495 }
10496
10497 // C++11 [except.spec]p15:
10498 // A deallocation function with no exception-specification is treated
10499 // as if it were specified with noexcept(true).
10500 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10501 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10502 !FPT->hasExceptionSpec())
10503 NewFD->setType(Context.getFunctionType(
10504 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
10505 EPI: FPT->getExtProtoInfo().withExceptionSpec(ESI: EST_BasicNoexcept)));
10506
10507 // C++20 [dcl.inline]/7
10508 // If an inline function or variable that is attached to a named module
10509 // is declared in a definition domain, it shall be defined in that
10510 // domain.
10511 // So, if the current declaration does not have a definition, we must
10512 // check at the end of the TU (or when the PMF starts) to see that we
10513 // have a definition at that point.
10514 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10515 NewFD->isInNamedModule()) {
10516 PendingInlineFuncDecls.insert(Ptr: NewFD);
10517 }
10518 }
10519
10520 // Filter out previous declarations that don't match the scope.
10521 FilterLookupForScope(R&: Previous, Ctx: OriginalDC, S, ConsiderLinkage: shouldConsiderLinkage(FD: NewFD),
10522 AllowInlineNamespace: D.getCXXScopeSpec().isNotEmpty() ||
10523 isMemberSpecialization ||
10524 isFunctionTemplateSpecialization);
10525
10526 // Handle GNU asm-label extension (encoded as an attribute).
10527 if (Expr *E = D.getAsmLabel()) {
10528 // The parser guarantees this is a string.
10529 StringLiteral *SE = cast<StringLiteral>(Val: E);
10530 NewFD->addAttr(
10531 A: AsmLabelAttr::Create(Ctx&: Context, Label: SE->getString(), Range: SE->getStrTokenLoc(TokNum: 0)));
10532 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10533 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10534 ExtnameUndeclaredIdentifiers.find(Val: NewFD->getIdentifier());
10535 if (I != ExtnameUndeclaredIdentifiers.end()) {
10536 if (isDeclExternC(D: NewFD)) {
10537 NewFD->addAttr(A: I->second);
10538 ExtnameUndeclaredIdentifiers.erase(I);
10539 } else
10540 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
10541 << /*Variable*/0 << NewFD;
10542 }
10543 }
10544
10545 // Copy the parameter declarations from the declarator D to the function
10546 // declaration NewFD, if they are available. First scavenge them into Params.
10547 SmallVector<ParmVarDecl*, 16> Params;
10548 unsigned FTIIdx;
10549 if (D.isFunctionDeclarator(idx&: FTIIdx)) {
10550 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(i: FTIIdx).Fun;
10551
10552 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10553 // function that takes no arguments, not a function that takes a
10554 // single void argument.
10555 // We let through "const void" here because Sema::GetTypeForDeclarator
10556 // already checks for that case.
10557 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10558 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10559 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
10560 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10561 Param->setDeclContext(NewFD);
10562 Params.push_back(Elt: Param);
10563
10564 if (Param->isInvalidDecl())
10565 NewFD->setInvalidDecl();
10566 }
10567 }
10568
10569 if (!getLangOpts().CPlusPlus) {
10570 // In C, find all the tag declarations from the prototype and move them
10571 // into the function DeclContext. Remove them from the surrounding tag
10572 // injection context of the function, which is typically but not always
10573 // the TU.
10574 DeclContext *PrototypeTagContext =
10575 getTagInjectionContext(DC: NewFD->getLexicalDeclContext());
10576 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10577 auto *TD = dyn_cast<TagDecl>(Val: NonParmDecl);
10578
10579 // We don't want to reparent enumerators. Look at their parent enum
10580 // instead.
10581 if (!TD) {
10582 if (auto *ECD = dyn_cast<EnumConstantDecl>(Val: NonParmDecl))
10583 TD = cast<EnumDecl>(Val: ECD->getDeclContext());
10584 }
10585 if (!TD)
10586 continue;
10587 DeclContext *TagDC = TD->getLexicalDeclContext();
10588 if (!TagDC->containsDecl(D: TD))
10589 continue;
10590 TagDC->removeDecl(D: TD);
10591 TD->setDeclContext(NewFD);
10592 NewFD->addDecl(D: TD);
10593
10594 // Preserve the lexical DeclContext if it is not the surrounding tag
10595 // injection context of the FD. In this example, the semantic context of
10596 // E will be f and the lexical context will be S, while both the
10597 // semantic and lexical contexts of S will be f:
10598 // void f(struct S { enum E { a } f; } s);
10599 if (TagDC != PrototypeTagContext)
10600 TD->setLexicalDeclContext(TagDC);
10601 }
10602 }
10603 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10604 // When we're declaring a function with a typedef, typeof, etc as in the
10605 // following example, we'll need to synthesize (unnamed)
10606 // parameters for use in the declaration.
10607 //
10608 // @code
10609 // typedef void fn(int);
10610 // fn f;
10611 // @endcode
10612
10613 // Synthesize a parameter for each argument type.
10614 for (const auto &AI : FT->param_types()) {
10615 ParmVarDecl *Param =
10616 BuildParmVarDeclForTypedef(DC: NewFD, Loc: D.getIdentifierLoc(), T: AI);
10617 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
10618 Params.push_back(Elt: Param);
10619 }
10620 } else {
10621 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10622 "Should not need args for typedef of non-prototype fn");
10623 }
10624
10625 // Finally, we know we have the right number of parameters, install them.
10626 NewFD->setParams(Params);
10627
10628 // If this declarator is a declaration and not a definition, its parameters
10629 // will not be pushed onto a scope chain. That means we will not issue any
10630 // reserved identifier warnings for the declaration, but we will for the
10631 // definition. Handle those here.
10632 if (!D.isFunctionDefinition()) {
10633 for (const ParmVarDecl *PVD : Params)
10634 warnOnReservedIdentifier(D: PVD);
10635 }
10636
10637 if (D.getDeclSpec().isNoreturnSpecified())
10638 NewFD->addAttr(
10639 A: C11NoReturnAttr::Create(Ctx&: Context, Range: D.getDeclSpec().getNoreturnSpecLoc()));
10640
10641 // Functions returning a variably modified type violate C99 6.7.5.2p2
10642 // because all functions have linkage.
10643 if (!NewFD->isInvalidDecl() &&
10644 NewFD->getReturnType()->isVariablyModifiedType()) {
10645 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_vm_func_decl);
10646 NewFD->setInvalidDecl();
10647 }
10648
10649 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10650 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10651 !NewFD->hasAttr<SectionAttr>())
10652 NewFD->addAttr(A: PragmaClangTextSectionAttr::CreateImplicit(
10653 Ctx&: Context, Name: PragmaClangTextSection.SectionName,
10654 Range: PragmaClangTextSection.PragmaLocation));
10655
10656 // Apply an implicit SectionAttr if #pragma code_seg is active.
10657 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10658 !NewFD->hasAttr<SectionAttr>()) {
10659 NewFD->addAttr(A: SectionAttr::CreateImplicit(
10660 Ctx&: Context, Name: CodeSegStack.CurrentValue->getString(),
10661 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate));
10662 if (UnifySection(SectionName: CodeSegStack.CurrentValue->getString(),
10663 SectionFlags: ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10664 ASTContext::PSF_Read,
10665 TheDecl: NewFD))
10666 NewFD->dropAttr<SectionAttr>();
10667 }
10668
10669 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10670 // active.
10671 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10672 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10673 NewFD->addAttr(A: StrictGuardStackCheckAttr::CreateImplicit(
10674 Ctx&: Context, Range: PragmaClangTextSection.PragmaLocation));
10675
10676 // Apply an implicit CodeSegAttr from class declspec or
10677 // apply an implicit SectionAttr from #pragma code_seg if active.
10678 if (!NewFD->hasAttr<CodeSegAttr>()) {
10679 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(FD: NewFD,
10680 IsDefinition: D.isFunctionDefinition())) {
10681 NewFD->addAttr(A: SAttr);
10682 }
10683 }
10684
10685 // Handle attributes.
10686 ProcessDeclAttributes(S, D: NewFD, PD: D);
10687 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10688 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10689 !NewTVA->isDefaultVersion() &&
10690 !Context.getTargetInfo().hasFeature(Feature: "fmv")) {
10691 // Don't add to scope fmv functions declarations if fmv disabled
10692 AddToScope = false;
10693 return NewFD;
10694 }
10695
10696 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10697 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10698 // type.
10699 //
10700 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10701 // type declaration will generate a compilation error.
10702 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10703 if (AddressSpace != LangAS::Default) {
10704 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_return_value_with_address_space);
10705 NewFD->setInvalidDecl();
10706 }
10707 }
10708
10709 if (!getLangOpts().CPlusPlus) {
10710 // Perform semantic checking on the function declaration.
10711 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10712 CheckMain(FD: NewFD, D: D.getDeclSpec());
10713
10714 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10715 CheckMSVCRTEntryPoint(FD: NewFD);
10716
10717 if (!NewFD->isInvalidDecl())
10718 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10719 IsMemberSpecialization: isMemberSpecialization,
10720 DeclIsDefn: D.isFunctionDefinition()));
10721 else if (!Previous.empty())
10722 // Recover gracefully from an invalid redeclaration.
10723 D.setRedeclaration(true);
10724 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10725 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10726 "previous declaration set still overloaded");
10727
10728 // Diagnose no-prototype function declarations with calling conventions that
10729 // don't support variadic calls. Only do this in C and do it after merging
10730 // possibly prototyped redeclarations.
10731 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10732 if (isa<FunctionNoProtoType>(Val: FT) && !D.isFunctionDefinition()) {
10733 CallingConv CC = FT->getExtInfo().getCC();
10734 if (!supportsVariadicCall(CC)) {
10735 // Windows system headers sometimes accidentally use stdcall without
10736 // (void) parameters, so we relax this to a warning.
10737 int DiagID =
10738 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10739 Diag(Loc: NewFD->getLocation(), DiagID)
10740 << FunctionType::getNameForCallConv(CC);
10741 }
10742 }
10743
10744 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10745 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10746 checkNonTrivialCUnion(
10747 QT: NewFD->getReturnType(), Loc: NewFD->getReturnTypeSourceRange().getBegin(),
10748 UseContext: NonTrivialCUnionContext::FunctionReturn, NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
10749 } else {
10750 // C++11 [replacement.functions]p3:
10751 // The program's definitions shall not be specified as inline.
10752 //
10753 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10754 //
10755 // Suppress the diagnostic if the function is __attribute__((used)), since
10756 // that forces an external definition to be emitted.
10757 if (D.getDeclSpec().isInlineSpecified() &&
10758 NewFD->isReplaceableGlobalAllocationFunction() &&
10759 !NewFD->hasAttr<UsedAttr>())
10760 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10761 DiagID: diag::ext_operator_new_delete_declared_inline)
10762 << NewFD->getDeclName();
10763
10764 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10765 // C++20 [dcl.decl.general]p4:
10766 // The optional requires-clause in an init-declarator or
10767 // member-declarator shall be present only if the declarator declares a
10768 // templated function.
10769 //
10770 // C++20 [temp.pre]p8:
10771 // An entity is templated if it is
10772 // - a template,
10773 // - an entity defined or created in a templated entity,
10774 // - a member of a templated entity,
10775 // - an enumerator for an enumeration that is a templated entity, or
10776 // - the closure type of a lambda-expression appearing in the
10777 // declaration of a templated entity.
10778 //
10779 // [Note 6: A local class, a local or block variable, or a friend
10780 // function defined in a templated entity is a templated entity.
10781 // — end note]
10782 //
10783 // A templated function is a function template or a function that is
10784 // templated. A templated class is a class template or a class that is
10785 // templated. A templated variable is a variable template or a variable
10786 // that is templated.
10787 if (!FunctionTemplate) {
10788 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10789 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10790 // An explicit specialization shall not have a trailing
10791 // requires-clause unless it declares a function template.
10792 //
10793 // Since a friend function template specialization cannot be
10794 // definition, and since a non-template friend declaration with a
10795 // trailing requires-clause must be a definition, we diagnose
10796 // friend function template specializations with trailing
10797 // requires-clauses on the same path as explicit specializations
10798 // even though they aren't necessarily prohibited by the same
10799 // language rule.
10800 Diag(Loc: TRC->getBeginLoc(), DiagID: diag::err_non_temp_spec_requires_clause)
10801 << isFriend;
10802 } else if (isFriend && NewFD->isTemplated() &&
10803 !D.isFunctionDefinition()) {
10804 // C++ [temp.friend]p9:
10805 // A non-template friend declaration with a requires-clause shall be
10806 // a definition.
10807 Diag(Loc: NewFD->getBeginLoc(),
10808 DiagID: diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10809 NewFD->setInvalidDecl();
10810 } else if (!NewFD->isTemplated() ||
10811 !(isa<CXXMethodDecl>(Val: NewFD) || D.isFunctionDefinition())) {
10812 Diag(Loc: TRC->getBeginLoc(),
10813 DiagID: diag::err_constrained_non_templated_function);
10814 }
10815 }
10816 }
10817
10818 // We do not add HD attributes to specializations here because
10819 // they may have different constexpr-ness compared to their
10820 // templates and, after maybeAddHostDeviceAttrs() is applied,
10821 // may end up with different effective targets. Instead, a
10822 // specialization inherits its target attributes from its template
10823 // in the CheckFunctionTemplateSpecialization() call below.
10824 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10825 CUDA().maybeAddHostDeviceAttrs(FD: NewFD, Previous);
10826
10827 // Handle explicit specializations of function templates
10828 // and friend function declarations with an explicit
10829 // template argument list.
10830 if (isFunctionTemplateSpecialization) {
10831 bool isDependentSpecialization = false;
10832 if (isFriend) {
10833 // For friend function specializations, this is a dependent
10834 // specialization if its semantic context is dependent, its
10835 // type is dependent, or if its template-id is dependent.
10836 isDependentSpecialization =
10837 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10838 (HasExplicitTemplateArgs &&
10839 TemplateSpecializationType::
10840 anyInstantiationDependentTemplateArguments(
10841 Args: TemplateArgs.arguments()));
10842 assert((!isDependentSpecialization ||
10843 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10844 "dependent friend function specialization without template "
10845 "args");
10846 } else {
10847 // For class-scope explicit specializations of function templates,
10848 // if the lexical context is dependent, then the specialization
10849 // is dependent.
10850 isDependentSpecialization =
10851 CurContext->isRecord() && CurContext->isDependentContext();
10852 }
10853
10854 TemplateArgumentListInfo *ExplicitTemplateArgs =
10855 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10856 if (isDependentSpecialization) {
10857 // If it's a dependent specialization, it may not be possible
10858 // to determine the primary template (for explicit specializations)
10859 // or befriended declaration (for friends) until the enclosing
10860 // template is instantiated. In such cases, we store the declarations
10861 // found by name lookup and defer resolution until instantiation.
10862 if (CheckDependentFunctionTemplateSpecialization(
10863 FD: NewFD, ExplicitTemplateArgs, Previous))
10864 NewFD->setInvalidDecl();
10865 } else if (!NewFD->isInvalidDecl()) {
10866 if (CheckFunctionTemplateSpecialization(FD: NewFD, ExplicitTemplateArgs,
10867 Previous))
10868 NewFD->setInvalidDecl();
10869 }
10870 } else if (isMemberSpecialization && !FunctionTemplate) {
10871 if (CheckMemberSpecialization(Member: NewFD, Previous))
10872 NewFD->setInvalidDecl();
10873 }
10874
10875 // Perform semantic checking on the function declaration.
10876 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10877 CheckMain(FD: NewFD, D: D.getDeclSpec());
10878
10879 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10880 CheckMSVCRTEntryPoint(FD: NewFD);
10881
10882 if (!NewFD->isInvalidDecl())
10883 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10884 IsMemberSpecialization: isMemberSpecialization,
10885 DeclIsDefn: D.isFunctionDefinition()));
10886 else if (!Previous.empty())
10887 // Recover gracefully from an invalid redeclaration.
10888 D.setRedeclaration(true);
10889
10890 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10891 !D.isRedeclaration() ||
10892 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10893 "previous declaration set still overloaded");
10894
10895 NamedDecl *PrincipalDecl = (FunctionTemplate
10896 ? cast<NamedDecl>(Val: FunctionTemplate)
10897 : NewFD);
10898
10899 if (isFriend && NewFD->getPreviousDecl()) {
10900 AccessSpecifier Access = AS_public;
10901 if (!NewFD->isInvalidDecl())
10902 Access = NewFD->getPreviousDecl()->getAccess();
10903
10904 NewFD->setAccess(Access);
10905 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10906 }
10907
10908 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10909 PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary))
10910 PrincipalDecl->setNonMemberOperator();
10911
10912 // If we have a function template, check the template parameter
10913 // list. This will check and merge default template arguments.
10914 if (FunctionTemplate) {
10915 FunctionTemplateDecl *PrevTemplate =
10916 FunctionTemplate->getPreviousDecl();
10917 CheckTemplateParameterList(NewParams: FunctionTemplate->getTemplateParameters(),
10918 OldParams: PrevTemplate ? PrevTemplate->getTemplateParameters()
10919 : nullptr,
10920 TPC: D.getDeclSpec().isFriendSpecified()
10921 ? (D.isFunctionDefinition()
10922 ? TPC_FriendFunctionTemplateDefinition
10923 : TPC_FriendFunctionTemplate)
10924 : (D.getCXXScopeSpec().isSet() &&
10925 DC && DC->isRecord() &&
10926 DC->isDependentContext())
10927 ? TPC_ClassTemplateMember
10928 : TPC_FunctionTemplate);
10929 }
10930
10931 if (NewFD->isInvalidDecl()) {
10932 // Ignore all the rest of this.
10933 } else if (!D.isRedeclaration()) {
10934 struct ActOnFDArgs ExtraArgs = { .S: S, .D: D, .TemplateParamLists: TemplateParamLists,
10935 .AddToScope: AddToScope };
10936 // Fake up an access specifier if it's supposed to be a class member.
10937 if (isa<CXXRecordDecl>(Val: NewFD->getDeclContext()))
10938 NewFD->setAccess(AS_public);
10939
10940 // Qualified decls generally require a previous declaration.
10941 if (D.getCXXScopeSpec().isSet()) {
10942 // ...with the major exception of templated-scope or
10943 // dependent-scope friend declarations.
10944
10945 // TODO: we currently also suppress this check in dependent
10946 // contexts because (1) the parameter depth will be off when
10947 // matching friend templates and (2) we might actually be
10948 // selecting a friend based on a dependent factor. But there
10949 // are situations where these conditions don't apply and we
10950 // can actually do this check immediately.
10951 //
10952 // Unless the scope is dependent, it's always an error if qualified
10953 // redeclaration lookup found nothing at all. Diagnose that now;
10954 // nothing will diagnose that error later.
10955 if (isFriend &&
10956 (D.getCXXScopeSpec().getScopeRep().isDependent() ||
10957 (!Previous.empty() && CurContext->isDependentContext()))) {
10958 // ignore these
10959 } else if (NewFD->isCPUDispatchMultiVersion() ||
10960 NewFD->isCPUSpecificMultiVersion()) {
10961 // ignore this, we allow the redeclaration behavior here to create new
10962 // versions of the function.
10963 } else {
10964 // The user tried to provide an out-of-line definition for a
10965 // function that is a member of a class or namespace, but there
10966 // was no such member function declared (C++ [class.mfct]p2,
10967 // C++ [namespace.memdef]p2). For example:
10968 //
10969 // class X {
10970 // void f() const;
10971 // };
10972 //
10973 // void X::f() { } // ill-formed
10974 //
10975 // Complain about this problem, and attempt to suggest close
10976 // matches (e.g., those that differ only in cv-qualifiers and
10977 // whether the parameter types are references).
10978
10979 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10980 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: false, S: nullptr)) {
10981 AddToScope = ExtraArgs.AddToScope;
10982 return Result;
10983 }
10984 }
10985
10986 // Unqualified local friend declarations are required to resolve
10987 // to something.
10988 } else if (isFriend && cast<CXXRecordDecl>(Val: CurContext)->isLocalClass()) {
10989 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10990 SemaRef&: *this, Previous, NewFD, ExtraArgs, IsLocalFriend: true, S)) {
10991 AddToScope = ExtraArgs.AddToScope;
10992 return Result;
10993 }
10994 }
10995 } else if (!D.isFunctionDefinition() &&
10996 isa<CXXMethodDecl>(Val: NewFD) && NewFD->isOutOfLine() &&
10997 !isFriend && !isFunctionTemplateSpecialization &&
10998 !isMemberSpecialization) {
10999 // An out-of-line member function declaration must also be a
11000 // definition (C++ [class.mfct]p2).
11001 // Note that this is not the case for explicit specializations of
11002 // function templates or member functions of class templates, per
11003 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11004 // extension for compatibility with old SWIG code which likes to
11005 // generate them.
11006 Diag(Loc: NewFD->getLocation(), DiagID: diag::ext_out_of_line_declaration)
11007 << D.getCXXScopeSpec().getRange();
11008 }
11009 }
11010
11011 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11012 // Any top level function could potentially be specified as an entry.
11013 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11014 HLSL().ActOnTopLevelFunction(FD: NewFD);
11015
11016 if (NewFD->hasAttr<HLSLShaderAttr>())
11017 HLSL().CheckEntryPoint(FD: NewFD);
11018 }
11019
11020 // If this is the first declaration of a library builtin function, add
11021 // attributes as appropriate.
11022 if (!D.isRedeclaration()) {
11023 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11024 if (unsigned BuiltinID = II->getBuiltinID()) {
11025 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(ID: BuiltinID);
11026 if (!InStdNamespace &&
11027 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
11028 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11029 // Validate the type matches unless this builtin is specified as
11030 // matching regardless of its declared type.
11031 if (Context.BuiltinInfo.allowTypeMismatch(ID: BuiltinID)) {
11032 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11033 } else {
11034 ASTContext::GetBuiltinTypeError Error;
11035 LookupNecessaryTypesForBuiltin(S, ID: BuiltinID);
11036 QualType BuiltinType = Context.GetBuiltinType(ID: BuiltinID, Error);
11037
11038 if (!Error && !BuiltinType.isNull() &&
11039 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11040 T: NewFD->getType(), U: BuiltinType))
11041 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11042 }
11043 }
11044 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11045 isStdBuiltin(Ctx&: Context, FD: NewFD, BuiltinID)) {
11046 NewFD->addAttr(A: BuiltinAttr::CreateImplicit(Ctx&: Context, ID: BuiltinID));
11047 }
11048 }
11049 }
11050 }
11051
11052 ProcessPragmaWeak(S, D: NewFD);
11053 ProcessPragmaExport(NewD: NewFD);
11054 checkAttributesAfterMerging(S&: *this, ND&: *NewFD);
11055
11056 AddKnownFunctionAttributes(FD: NewFD);
11057
11058 if (NewFD->hasAttr<OverloadableAttr>() &&
11059 !NewFD->getType()->getAs<FunctionProtoType>()) {
11060 Diag(Loc: NewFD->getLocation(),
11061 DiagID: diag::err_attribute_overloadable_no_prototype)
11062 << NewFD;
11063 NewFD->dropAttr<OverloadableAttr>();
11064 }
11065
11066 // If there's a #pragma GCC visibility in scope, and this isn't a class
11067 // member, set the visibility of this function.
11068 if (!DC->isRecord() && NewFD->isExternallyVisible())
11069 AddPushedVisibilityAttribute(RD: NewFD);
11070
11071 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11072 // marking the function.
11073 ObjC().AddCFAuditedAttribute(D: NewFD);
11074
11075 // If this is a function definition, check if we have to apply any
11076 // attributes (i.e. optnone and no_builtin) due to a pragma.
11077 if (D.isFunctionDefinition()) {
11078 AddRangeBasedOptnone(FD: NewFD);
11079 AddImplicitMSFunctionNoBuiltinAttr(FD: NewFD);
11080 AddSectionMSAllocText(FD: NewFD);
11081 ModifyFnAttributesMSPragmaOptimize(FD: NewFD);
11082 }
11083
11084 // If this is the first declaration of an extern C variable, update
11085 // the map of such variables.
11086 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11087 isIncompleteDeclExternC(S&: *this, D: NewFD))
11088 RegisterLocallyScopedExternCDecl(ND: NewFD, S);
11089
11090 // Set this FunctionDecl's range up to the right paren.
11091 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11092
11093 if (D.isRedeclaration() && !Previous.empty()) {
11094 NamedDecl *Prev = Previous.getRepresentativeDecl();
11095 checkDLLAttributeRedeclaration(S&: *this, OldDecl: Prev, NewDecl: NewFD,
11096 IsSpecialization: isMemberSpecialization ||
11097 isFunctionTemplateSpecialization,
11098 IsDefinition: D.isFunctionDefinition());
11099 }
11100
11101 if (getLangOpts().CUDA) {
11102 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11103 if (II->isStr(Str: CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11104 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11105 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11106 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11107 << CUDA().getConfigureFuncName();
11108 Context.setcudaConfigureCallDecl(NewFD);
11109 }
11110 if (II->isStr(Str: CUDA().getGetParameterBufferFuncName()) &&
11111 !NewFD->isInvalidDecl() &&
11112 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11113 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11114 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_pointer_return)
11115 << CUDA().getConfigureFuncName();
11116 Context.setcudaGetParameterBufferDecl(NewFD);
11117 }
11118 if (II->isStr(Str: CUDA().getLaunchDeviceFuncName()) &&
11119 !NewFD->isInvalidDecl() &&
11120 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
11121 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11122 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_config_scalar_return)
11123 << CUDA().getConfigureFuncName();
11124 Context.setcudaLaunchDeviceDecl(NewFD);
11125 }
11126 }
11127 }
11128
11129 MarkUnusedFileScopedDecl(D: NewFD);
11130
11131 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11132 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11133 if (SC == SC_Static) {
11134 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_static_kernel);
11135 D.setInvalidType();
11136 }
11137
11138 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11139 if (!NewFD->getReturnType()->isVoidType()) {
11140 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11141 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_expected_kernel_void_return_type)
11142 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
11143 : FixItHint());
11144 D.setInvalidType();
11145 }
11146
11147 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
11148 for (auto *Param : NewFD->parameters())
11149 checkIsValidOpenCLKernelParameter(S&: *this, D, Param, ValidTypes);
11150
11151 if (getLangOpts().OpenCLCPlusPlus) {
11152 if (DC->isRecord()) {
11153 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_method_kernel);
11154 D.setInvalidType();
11155 }
11156 if (FunctionTemplate) {
11157 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_template_kernel);
11158 D.setInvalidType();
11159 }
11160 }
11161 }
11162
11163 if (getLangOpts().CPlusPlus) {
11164 // Precalculate whether this is a friend function template with a constraint
11165 // that depends on an enclosing template, per [temp.friend]p9.
11166 if (isFriend && FunctionTemplate &&
11167 FriendConstraintsDependOnEnclosingTemplate(FD: NewFD)) {
11168 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
11169
11170 // C++ [temp.friend]p9:
11171 // A friend function template with a constraint that depends on a
11172 // template parameter from an enclosing template shall be a definition.
11173 if (!D.isFunctionDefinition()) {
11174 Diag(Loc: NewFD->getBeginLoc(),
11175 DiagID: diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11176 NewFD->setInvalidDecl();
11177 }
11178 }
11179
11180 if (FunctionTemplate) {
11181 if (NewFD->isInvalidDecl())
11182 FunctionTemplate->setInvalidDecl();
11183 return FunctionTemplate;
11184 }
11185
11186 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11187 CompleteMemberSpecialization(Member: NewFD, Previous);
11188 }
11189
11190 for (const ParmVarDecl *Param : NewFD->parameters()) {
11191 QualType PT = Param->getType();
11192
11193 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11194 // types.
11195 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11196 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11197 QualType ElemTy = PipeTy->getElementType();
11198 if (ElemTy->isPointerOrReferenceType()) {
11199 Diag(Loc: Param->getTypeSpecStartLoc(), DiagID: diag::err_reference_pipe_type);
11200 D.setInvalidType();
11201 }
11202 }
11203 }
11204 // WebAssembly tables can't be used as function parameters.
11205 if (Context.getTargetInfo().getTriple().isWasm()) {
11206 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
11207 Diag(Loc: Param->getTypeSpecStartLoc(),
11208 DiagID: diag::err_wasm_table_as_function_parameter);
11209 D.setInvalidType();
11210 }
11211 }
11212 }
11213
11214 // Diagnose availability attributes. Availability cannot be used on functions
11215 // that are run during load/unload.
11216 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11217 if (NewFD->hasAttr<ConstructorAttr>()) {
11218 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11219 << 1;
11220 NewFD->dropAttr<AvailabilityAttr>();
11221 }
11222 if (NewFD->hasAttr<DestructorAttr>()) {
11223 Diag(Loc: attr->getLocation(), DiagID: diag::warn_availability_on_static_initializer)
11224 << 2;
11225 NewFD->dropAttr<AvailabilityAttr>();
11226 }
11227 }
11228
11229 // Diagnose no_builtin attribute on function declaration that are not a
11230 // definition.
11231 // FIXME: We should really be doing this in
11232 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11233 // the FunctionDecl and at this point of the code
11234 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11235 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11236 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11237 switch (D.getFunctionDefinitionKind()) {
11238 case FunctionDefinitionKind::Defaulted:
11239 case FunctionDefinitionKind::Deleted:
11240 Diag(Loc: NBA->getLocation(),
11241 DiagID: diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11242 << NBA->getSpelling();
11243 break;
11244 case FunctionDefinitionKind::Declaration:
11245 Diag(Loc: NBA->getLocation(), DiagID: diag::err_attribute_no_builtin_on_non_definition)
11246 << NBA->getSpelling();
11247 break;
11248 case FunctionDefinitionKind::Definition:
11249 break;
11250 }
11251
11252 // Similar to no_builtin logic above, at this point of the code
11253 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11254 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11255 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11256 !NewFD->isInvalidDecl() &&
11257 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
11258 ExternalDeclarations.push_back(Elt: NewFD);
11259
11260 // Used for a warning on the 'next' declaration when used with a
11261 // `routine(name)`.
11262 if (getLangOpts().OpenACC)
11263 OpenACC().ActOnFunctionDeclarator(FD: NewFD);
11264
11265 return NewFD;
11266}
11267
11268/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11269/// when __declspec(code_seg) "is applied to a class, all member functions of
11270/// the class and nested classes -- this includes compiler-generated special
11271/// member functions -- are put in the specified segment."
11272/// The actual behavior is a little more complicated. The Microsoft compiler
11273/// won't check outer classes if there is an active value from #pragma code_seg.
11274/// The CodeSeg is always applied from the direct parent but only from outer
11275/// classes when the #pragma code_seg stack is empty. See:
11276/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11277/// available since MS has removed the page.
11278static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
11279 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
11280 if (!Method)
11281 return nullptr;
11282 const CXXRecordDecl *Parent = Method->getParent();
11283 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11284 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11285 NewAttr->setImplicit(true);
11286 return NewAttr;
11287 }
11288
11289 // The Microsoft compiler won't check outer classes for the CodeSeg
11290 // when the #pragma code_seg stack is active.
11291 if (S.CodeSegStack.CurrentValue)
11292 return nullptr;
11293
11294 while ((Parent = dyn_cast<CXXRecordDecl>(Val: Parent->getParent()))) {
11295 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11296 Attr *NewAttr = SAttr->clone(C&: S.getASTContext());
11297 NewAttr->setImplicit(true);
11298 return NewAttr;
11299 }
11300 }
11301 return nullptr;
11302}
11303
11304Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
11305 bool IsDefinition) {
11306 if (Attr *A = getImplicitCodeSegAttrFromClass(S&: *this, FD))
11307 return A;
11308 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11309 CodeSegStack.CurrentValue)
11310 return SectionAttr::CreateImplicit(
11311 Ctx&: getASTContext(), Name: CodeSegStack.CurrentValue->getString(),
11312 Range: CodeSegStack.CurrentPragmaLocation, S: SectionAttr::Declspec_allocate);
11313 return nullptr;
11314}
11315
11316bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
11317 QualType NewT, QualType OldT) {
11318 if (!NewD->getLexicalDeclContext()->isDependentContext())
11319 return true;
11320
11321 // For dependently-typed local extern declarations and friends, we can't
11322 // perform a correct type check in general until instantiation:
11323 //
11324 // int f();
11325 // template<typename T> void g() { T f(); }
11326 //
11327 // (valid if g() is only instantiated with T = int).
11328 if (NewT->isDependentType() &&
11329 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11330 return false;
11331
11332 // Similarly, if the previous declaration was a dependent local extern
11333 // declaration, we don't really know its type yet.
11334 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11335 return false;
11336
11337 return true;
11338}
11339
11340bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11341 if (!D->getLexicalDeclContext()->isDependentContext())
11342 return true;
11343
11344 // Don't chain dependent friend function definitions until instantiation, to
11345 // permit cases like
11346 //
11347 // void func();
11348 // template<typename T> class C1 { friend void func() {} };
11349 // template<typename T> class C2 { friend void func() {} };
11350 //
11351 // ... which is valid if only one of C1 and C2 is ever instantiated.
11352 //
11353 // FIXME: This need only apply to function definitions. For now, we proxy
11354 // this by checking for a file-scope function. We do not want this to apply
11355 // to friend declarations nominating member functions, because that gets in
11356 // the way of access checks.
11357 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11358 return false;
11359
11360 auto *VD = dyn_cast<ValueDecl>(Val: D);
11361 auto *PrevVD = dyn_cast<ValueDecl>(Val: PrevDecl);
11362 return !VD || !PrevVD ||
11363 canFullyTypeCheckRedeclaration(NewD: VD, OldD: PrevVD, NewT: VD->getType(),
11364 OldT: PrevVD->getType());
11365}
11366
11367/// Check the target or target_version attribute of the function for
11368/// MultiVersion validity.
11369///
11370/// Returns true if there was an error, false otherwise.
11371static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11372 const auto *TA = FD->getAttr<TargetAttr>();
11373 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11374
11375 assert((TA || TVA) && "Expecting target or target_version attribute");
11376
11377 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11378 enum ErrType { Feature = 0, Architecture = 1 };
11379
11380 if (TA) {
11381 ParsedTargetAttr ParseInfo =
11382 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TA->getFeaturesStr());
11383 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(Name: ParseInfo.CPU)) {
11384 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11385 << Architecture << ParseInfo.CPU;
11386 return true;
11387 }
11388 for (const auto &Feat : ParseInfo.Features) {
11389 auto BareFeat = StringRef{Feat}.substr(Start: 1);
11390 if (Feat[0] == '-') {
11391 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11392 << Feature << ("no-" + BareFeat).str();
11393 return true;
11394 }
11395
11396 if (!TargetInfo.validateCpuSupports(Name: BareFeat) ||
11397 !TargetInfo.isValidFeatureName(Feature: BareFeat) ||
11398 (BareFeat != "default" && TargetInfo.getFMVPriority(Features: BareFeat) == 0)) {
11399 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11400 << Feature << BareFeat;
11401 return true;
11402 }
11403 }
11404 }
11405
11406 if (TVA) {
11407 llvm::SmallVector<StringRef, 8> Feats;
11408 ParsedTargetAttr ParseInfo;
11409 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11410 ParseInfo =
11411 S.getASTContext().getTargetInfo().parseTargetAttr(Str: TVA->getName());
11412 for (auto &Feat : ParseInfo.Features)
11413 Feats.push_back(Elt: StringRef{Feat}.substr(Start: 1));
11414 } else {
11415 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11416 TVA->getFeatures(Out&: Feats);
11417 }
11418 for (const auto &Feat : Feats) {
11419 if (!TargetInfo.validateCpuSupports(Name: Feat)) {
11420 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_bad_multiversion_option)
11421 << Feature << Feat;
11422 return true;
11423 }
11424 }
11425 }
11426 return false;
11427}
11428
11429// Provide a white-list of attributes that are allowed to be combined with
11430// multiversion functions.
11431static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11432 MultiVersionKind MVKind) {
11433 // Note: this list/diagnosis must match the list in
11434 // checkMultiversionAttributesAllSame.
11435 switch (Kind) {
11436 default:
11437 return false;
11438 case attr::ArmLocallyStreaming:
11439 return MVKind == MultiVersionKind::TargetVersion ||
11440 MVKind == MultiVersionKind::TargetClones;
11441 case attr::Used:
11442 return MVKind == MultiVersionKind::Target;
11443 case attr::NonNull:
11444 case attr::NoThrow:
11445 return true;
11446 }
11447}
11448
11449static bool checkNonMultiVersionCompatAttributes(Sema &S,
11450 const FunctionDecl *FD,
11451 const FunctionDecl *CausedFD,
11452 MultiVersionKind MVKind) {
11453 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11454 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_disallowed_other_attr)
11455 << static_cast<unsigned>(MVKind) << A;
11456 if (CausedFD)
11457 S.Diag(Loc: CausedFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11458 return true;
11459 };
11460
11461 for (const Attr *A : FD->attrs()) {
11462 switch (A->getKind()) {
11463 case attr::CPUDispatch:
11464 case attr::CPUSpecific:
11465 if (MVKind != MultiVersionKind::CPUDispatch &&
11466 MVKind != MultiVersionKind::CPUSpecific)
11467 return Diagnose(S, A);
11468 break;
11469 case attr::Target:
11470 if (MVKind != MultiVersionKind::Target)
11471 return Diagnose(S, A);
11472 break;
11473 case attr::TargetVersion:
11474 if (MVKind != MultiVersionKind::TargetVersion &&
11475 MVKind != MultiVersionKind::TargetClones)
11476 return Diagnose(S, A);
11477 break;
11478 case attr::TargetClones:
11479 if (MVKind != MultiVersionKind::TargetClones &&
11480 MVKind != MultiVersionKind::TargetVersion)
11481 return Diagnose(S, A);
11482 break;
11483 default:
11484 if (!AttrCompatibleWithMultiVersion(Kind: A->getKind(), MVKind))
11485 return Diagnose(S, A);
11486 break;
11487 }
11488 }
11489 return false;
11490}
11491
11492bool Sema::areMultiversionVariantFunctionsCompatible(
11493 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11494 const PartialDiagnostic &NoProtoDiagID,
11495 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11496 const PartialDiagnosticAt &NoSupportDiagIDAt,
11497 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11498 bool ConstexprSupported, bool CLinkageMayDiffer) {
11499 enum DoesntSupport {
11500 FuncTemplates = 0,
11501 VirtFuncs = 1,
11502 DeducedReturn = 2,
11503 Constructors = 3,
11504 Destructors = 4,
11505 DeletedFuncs = 5,
11506 DefaultedFuncs = 6,
11507 ConstexprFuncs = 7,
11508 ConstevalFuncs = 8,
11509 Lambda = 9,
11510 };
11511 enum Different {
11512 CallingConv = 0,
11513 ReturnType = 1,
11514 ConstexprSpec = 2,
11515 InlineSpec = 3,
11516 Linkage = 4,
11517 LanguageLinkage = 5,
11518 };
11519
11520 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11521 !OldFD->getType()->getAs<FunctionProtoType>()) {
11522 Diag(Loc: OldFD->getLocation(), PD: NoProtoDiagID);
11523 Diag(Loc: NoteCausedDiagIDAt.first, PD: NoteCausedDiagIDAt.second);
11524 return true;
11525 }
11526
11527 if (NoProtoDiagID.getDiagID() != 0 &&
11528 !NewFD->getType()->getAs<FunctionProtoType>())
11529 return Diag(Loc: NewFD->getLocation(), PD: NoProtoDiagID);
11530
11531 if (!TemplatesSupported &&
11532 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11533 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11534 << FuncTemplates;
11535
11536 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
11537 if (NewCXXFD->isVirtual())
11538 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11539 << VirtFuncs;
11540
11541 if (isa<CXXConstructorDecl>(Val: NewCXXFD))
11542 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11543 << Constructors;
11544
11545 if (isa<CXXDestructorDecl>(Val: NewCXXFD))
11546 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11547 << Destructors;
11548 }
11549
11550 if (NewFD->isDeleted())
11551 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11552 << DeletedFuncs;
11553
11554 if (NewFD->isDefaulted())
11555 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11556 << DefaultedFuncs;
11557
11558 if (!ConstexprSupported && NewFD->isConstexpr())
11559 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11560 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11561
11562 QualType NewQType = Context.getCanonicalType(T: NewFD->getType());
11563 const auto *NewType = cast<FunctionType>(Val&: NewQType);
11564 QualType NewReturnType = NewType->getReturnType();
11565
11566 if (NewReturnType->isUndeducedType())
11567 return Diag(Loc: NoSupportDiagIDAt.first, PD: NoSupportDiagIDAt.second)
11568 << DeducedReturn;
11569
11570 // Ensure the return type is identical.
11571 if (OldFD) {
11572 QualType OldQType = Context.getCanonicalType(T: OldFD->getType());
11573 const auto *OldType = cast<FunctionType>(Val&: OldQType);
11574 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11575 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11576
11577 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11578 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11579
11580 bool ArmStreamingCCMismatched = false;
11581 if (OldFPT && NewFPT) {
11582 unsigned Diff =
11583 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11584 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11585 // cannot be mixed.
11586 if (Diff & (FunctionType::SME_PStateSMEnabledMask |
11587 FunctionType::SME_PStateSMCompatibleMask))
11588 ArmStreamingCCMismatched = true;
11589 }
11590
11591 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11592 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << CallingConv;
11593
11594 QualType OldReturnType = OldType->getReturnType();
11595
11596 if (OldReturnType != NewReturnType)
11597 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ReturnType;
11598
11599 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11600 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << ConstexprSpec;
11601
11602 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11603 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << InlineSpec;
11604
11605 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11606 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << Linkage;
11607
11608 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11609 return Diag(Loc: DiffDiagIDAt.first, PD: DiffDiagIDAt.second) << LanguageLinkage;
11610
11611 if (CheckEquivalentExceptionSpec(Old: OldFPT, OldLoc: OldFD->getLocation(), New: NewFPT,
11612 NewLoc: NewFD->getLocation()))
11613 return true;
11614 }
11615 return false;
11616}
11617
11618static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11619 const FunctionDecl *NewFD,
11620 bool CausesMV,
11621 MultiVersionKind MVKind) {
11622 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11623 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_supported);
11624 if (OldFD)
11625 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11626 return true;
11627 }
11628
11629 bool IsCPUSpecificCPUDispatchMVKind =
11630 MVKind == MultiVersionKind::CPUDispatch ||
11631 MVKind == MultiVersionKind::CPUSpecific;
11632
11633 if (CausesMV && OldFD &&
11634 checkNonMultiVersionCompatAttributes(S, FD: OldFD, CausedFD: NewFD, MVKind))
11635 return true;
11636
11637 if (checkNonMultiVersionCompatAttributes(S, FD: NewFD, CausedFD: nullptr, MVKind))
11638 return true;
11639
11640 // Only allow transition to MultiVersion if it hasn't been used.
11641 if (OldFD && CausesMV && OldFD->isUsed(CheckUsedAttr: false)) {
11642 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
11643 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11644 return true;
11645 }
11646
11647 return S.areMultiversionVariantFunctionsCompatible(
11648 OldFD, NewFD, NoProtoDiagID: S.PDiag(DiagID: diag::err_multiversion_noproto),
11649 NoteCausedDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11650 S.PDiag(DiagID: diag::note_multiversioning_caused_here)),
11651 NoSupportDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11652 S.PDiag(DiagID: diag::err_multiversion_doesnt_support)
11653 << static_cast<unsigned>(MVKind)),
11654 DiffDiagIDAt: PartialDiagnosticAt(NewFD->getLocation(),
11655 S.PDiag(DiagID: diag::err_multiversion_diff)),
11656 /*TemplatesSupported=*/false,
11657 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11658 /*CLinkageMayDiffer=*/false);
11659}
11660
11661/// Check the validity of a multiversion function declaration that is the
11662/// first of its kind. Also sets the multiversion'ness' of the function itself.
11663///
11664/// This sets NewFD->isInvalidDecl() to true if there was an error.
11665///
11666/// Returns true if there was an error, false otherwise.
11667static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11668 MultiVersionKind MVKind = FD->getMultiVersionKind();
11669 assert(MVKind != MultiVersionKind::None &&
11670 "Function lacks multiversion attribute");
11671 const auto *TA = FD->getAttr<TargetAttr>();
11672 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11673 // The target attribute only causes MV if this declaration is the default,
11674 // otherwise it is treated as a normal function.
11675 if (TA && !TA->isDefaultVersion())
11676 return false;
11677
11678 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11679 FD->setInvalidDecl();
11680 return true;
11681 }
11682
11683 if (CheckMultiVersionAdditionalRules(S, OldFD: nullptr, NewFD: FD, CausesMV: true, MVKind)) {
11684 FD->setInvalidDecl();
11685 return true;
11686 }
11687
11688 FD->setIsMultiVersion();
11689 return false;
11690}
11691
11692static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11693 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11694 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11695 return true;
11696 }
11697
11698 return false;
11699}
11700
11701static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To) {
11702 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11703 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11704 return;
11705
11706 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11707 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11708
11709 if (MVKindTo == MultiVersionKind::None &&
11710 (MVKindFrom == MultiVersionKind::TargetVersion ||
11711 MVKindFrom == MultiVersionKind::TargetClones))
11712 To->addAttr(A: TargetVersionAttr::CreateImplicit(
11713 Ctx&: To->getASTContext(), NamesStr: "default", Range: To->getSourceRange()));
11714}
11715
11716static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11717 FunctionDecl *NewFD,
11718 bool &Redeclaration,
11719 NamedDecl *&OldDecl,
11720 LookupResult &Previous) {
11721 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11722
11723 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11724 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11725 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11726 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11727
11728 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11729
11730 // The definitions should be allowed in any order. If we have discovered
11731 // a new target version and the preceeding was the default, then add the
11732 // corresponding attribute to it.
11733 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11734
11735 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11736 // to change, this is a simple redeclaration.
11737 if (NewTA && !NewTA->isDefaultVersion() &&
11738 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11739 return false;
11740
11741 // Otherwise, this decl causes MultiVersioning.
11742 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, CausesMV: true,
11743 MVKind: NewTVA ? MultiVersionKind::TargetVersion
11744 : MultiVersionKind::Target)) {
11745 NewFD->setInvalidDecl();
11746 return true;
11747 }
11748
11749 if (CheckMultiVersionValue(S, FD: NewFD)) {
11750 NewFD->setInvalidDecl();
11751 return true;
11752 }
11753
11754 // If this is 'default', permit the forward declaration.
11755 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11756 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11757 Redeclaration = true;
11758 OldDecl = OldFD;
11759 OldFD->setIsMultiVersion();
11760 NewFD->setIsMultiVersion();
11761 return false;
11762 }
11763
11764 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, FD: OldFD)) {
11765 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11766 NewFD->setInvalidDecl();
11767 return true;
11768 }
11769
11770 if (NewTA) {
11771 ParsedTargetAttr OldParsed =
11772 S.getASTContext().getTargetInfo().parseTargetAttr(
11773 Str: OldTA->getFeaturesStr());
11774 llvm::sort(C&: OldParsed.Features);
11775 ParsedTargetAttr NewParsed =
11776 S.getASTContext().getTargetInfo().parseTargetAttr(
11777 Str: NewTA->getFeaturesStr());
11778 // Sort order doesn't matter, it just needs to be consistent.
11779 llvm::sort(C&: NewParsed.Features);
11780 if (OldParsed == NewParsed) {
11781 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11782 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11783 NewFD->setInvalidDecl();
11784 return true;
11785 }
11786 }
11787
11788 for (const auto *FD : OldFD->redecls()) {
11789 const auto *CurTA = FD->getAttr<TargetAttr>();
11790 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11791 // We allow forward declarations before ANY multiversioning attributes, but
11792 // nothing after the fact.
11793 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11794 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11795 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11796 S.Diag(Loc: FD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
11797 << (NewTA ? 0 : 2);
11798 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::note_multiversioning_caused_here);
11799 NewFD->setInvalidDecl();
11800 return true;
11801 }
11802 }
11803
11804 OldFD->setIsMultiVersion();
11805 NewFD->setIsMultiVersion();
11806 Redeclaration = false;
11807 OldDecl = nullptr;
11808 Previous.clear();
11809 return false;
11810}
11811
11812static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New) {
11813 MultiVersionKind OldKind = Old->getMultiVersionKind();
11814 MultiVersionKind NewKind = New->getMultiVersionKind();
11815
11816 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11817 NewKind == MultiVersionKind::None)
11818 return true;
11819
11820 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11821 switch (OldKind) {
11822 case MultiVersionKind::TargetVersion:
11823 return NewKind == MultiVersionKind::TargetClones;
11824 case MultiVersionKind::TargetClones:
11825 return NewKind == MultiVersionKind::TargetVersion;
11826 default:
11827 return false;
11828 }
11829 } else {
11830 switch (OldKind) {
11831 case MultiVersionKind::CPUDispatch:
11832 return NewKind == MultiVersionKind::CPUSpecific;
11833 case MultiVersionKind::CPUSpecific:
11834 return NewKind == MultiVersionKind::CPUDispatch;
11835 default:
11836 return false;
11837 }
11838 }
11839}
11840
11841/// Check the validity of a new function declaration being added to an existing
11842/// multiversioned declaration collection.
11843static bool CheckMultiVersionAdditionalDecl(
11844 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11845 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11846 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11847 LookupResult &Previous) {
11848
11849 // Disallow mixing of multiversioning types.
11850 if (!MultiVersionTypesCompatible(Old: OldFD, New: NewFD)) {
11851 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_types_mixed);
11852 S.Diag(Loc: OldFD->getLocation(), DiagID: diag::note_previous_declaration);
11853 NewFD->setInvalidDecl();
11854 return true;
11855 }
11856
11857 // Add the default target_version attribute if it's missing.
11858 patchDefaultTargetVersion(From: OldFD, To: NewFD);
11859 patchDefaultTargetVersion(From: NewFD, To: OldFD);
11860
11861 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11862 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11863 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11864 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11865
11866 ParsedTargetAttr NewParsed;
11867 if (NewTA) {
11868 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11869 Str: NewTA->getFeaturesStr());
11870 llvm::sort(C&: NewParsed.Features);
11871 }
11872 llvm::SmallVector<StringRef, 8> NewFeats;
11873 if (NewTVA) {
11874 NewTVA->getFeatures(Out&: NewFeats);
11875 llvm::sort(C&: NewFeats);
11876 }
11877
11878 bool UseMemberUsingDeclRules =
11879 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11880
11881 bool MayNeedOverloadableChecks =
11882 AllowOverloadingOfFunction(Previous, Context&: S.Context, New: NewFD);
11883
11884 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11885 // of a previous member of the MultiVersion set.
11886 for (NamedDecl *ND : Previous) {
11887 FunctionDecl *CurFD = ND->getAsFunction();
11888 if (!CurFD || CurFD->isInvalidDecl())
11889 continue;
11890 if (MayNeedOverloadableChecks &&
11891 S.IsOverload(New: NewFD, Old: CurFD, UseMemberUsingDeclRules))
11892 continue;
11893
11894 switch (NewMVKind) {
11895 case MultiVersionKind::None:
11896 assert(OldMVKind == MultiVersionKind::TargetClones &&
11897 "Only target_clones can be omitted in subsequent declarations");
11898 break;
11899 case MultiVersionKind::Target: {
11900 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11901 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11902 NewFD->setIsMultiVersion();
11903 Redeclaration = true;
11904 OldDecl = ND;
11905 return false;
11906 }
11907
11908 ParsedTargetAttr CurParsed =
11909 S.getASTContext().getTargetInfo().parseTargetAttr(
11910 Str: CurTA->getFeaturesStr());
11911 llvm::sort(C&: CurParsed.Features);
11912 if (CurParsed == NewParsed) {
11913 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11914 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11915 NewFD->setInvalidDecl();
11916 return true;
11917 }
11918 break;
11919 }
11920 case MultiVersionKind::TargetVersion: {
11921 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11922 if (CurTVA->getName() == NewTVA->getName()) {
11923 NewFD->setIsMultiVersion();
11924 Redeclaration = true;
11925 OldDecl = ND;
11926 return false;
11927 }
11928 llvm::SmallVector<StringRef, 8> CurFeats;
11929 CurTVA->getFeatures(Out&: CurFeats);
11930 llvm::sort(C&: CurFeats);
11931
11932 if (CurFeats == NewFeats) {
11933 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11934 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11935 NewFD->setInvalidDecl();
11936 return true;
11937 }
11938 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11939 // Default
11940 if (NewFeats.empty())
11941 break;
11942
11943 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11944 llvm::SmallVector<StringRef, 8> CurFeats;
11945 CurClones->getFeatures(Out&: CurFeats, Index: I);
11946 llvm::sort(C&: CurFeats);
11947
11948 if (CurFeats == NewFeats) {
11949 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11950 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11951 NewFD->setInvalidDecl();
11952 return true;
11953 }
11954 }
11955 }
11956 break;
11957 }
11958 case MultiVersionKind::TargetClones: {
11959 assert(NewClones && "MultiVersionKind does not match attribute type");
11960 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11961 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11962 !std::equal(first1: CurClones->featuresStrs_begin(),
11963 last1: CurClones->featuresStrs_end(),
11964 first2: NewClones->featuresStrs_begin())) {
11965 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_target_clone_doesnt_match);
11966 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11967 NewFD->setInvalidDecl();
11968 return true;
11969 }
11970 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11971 llvm::SmallVector<StringRef, 8> CurFeats;
11972 CurTVA->getFeatures(Out&: CurFeats);
11973 llvm::sort(C&: CurFeats);
11974
11975 // Default
11976 if (CurFeats.empty())
11977 break;
11978
11979 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11980 NewFeats.clear();
11981 NewClones->getFeatures(Out&: NewFeats, Index: I);
11982 llvm::sort(C&: NewFeats);
11983
11984 if (CurFeats == NewFeats) {
11985 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_duplicate);
11986 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
11987 NewFD->setInvalidDecl();
11988 return true;
11989 }
11990 }
11991 break;
11992 }
11993 Redeclaration = true;
11994 OldDecl = CurFD;
11995 NewFD->setIsMultiVersion();
11996 return false;
11997 }
11998 case MultiVersionKind::CPUSpecific:
11999 case MultiVersionKind::CPUDispatch: {
12000 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12001 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12002 // Handle CPUDispatch/CPUSpecific versions.
12003 // Only 1 CPUDispatch function is allowed, this will make it go through
12004 // the redeclaration errors.
12005 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12006 CurFD->hasAttr<CPUDispatchAttr>()) {
12007 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12008 std::equal(
12009 first1: CurCPUDisp->cpus_begin(), last1: CurCPUDisp->cpus_end(),
12010 first2: NewCPUDisp->cpus_begin(),
12011 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12012 return Cur->getName() == New->getName();
12013 })) {
12014 NewFD->setIsMultiVersion();
12015 Redeclaration = true;
12016 OldDecl = ND;
12017 return false;
12018 }
12019
12020 // If the declarations don't match, this is an error condition.
12021 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_dispatch_mismatch);
12022 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12023 NewFD->setInvalidDecl();
12024 return true;
12025 }
12026 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12027 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12028 std::equal(
12029 first1: CurCPUSpec->cpus_begin(), last1: CurCPUSpec->cpus_end(),
12030 first2: NewCPUSpec->cpus_begin(),
12031 binary_pred: [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12032 return Cur->getName() == New->getName();
12033 })) {
12034 NewFD->setIsMultiVersion();
12035 Redeclaration = true;
12036 OldDecl = ND;
12037 return false;
12038 }
12039
12040 // Only 1 version of CPUSpecific is allowed for each CPU.
12041 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12042 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12043 if (CurII == NewII) {
12044 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_cpu_specific_multiple_defs)
12045 << NewII;
12046 S.Diag(Loc: CurFD->getLocation(), DiagID: diag::note_previous_declaration);
12047 NewFD->setInvalidDecl();
12048 return true;
12049 }
12050 }
12051 }
12052 }
12053 break;
12054 }
12055 }
12056 }
12057
12058 // Redeclarations of a target_clones function may omit the attribute, in which
12059 // case it will be inherited during declaration merging.
12060 if (NewMVKind == MultiVersionKind::None &&
12061 OldMVKind == MultiVersionKind::TargetClones) {
12062 NewFD->setIsMultiVersion();
12063 Redeclaration = true;
12064 OldDecl = OldFD;
12065 return false;
12066 }
12067
12068 // Else, this is simply a non-redecl case. Checking the 'value' is only
12069 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12070 // handled in the attribute adding step.
12071 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, FD: NewFD)) {
12072 NewFD->setInvalidDecl();
12073 return true;
12074 }
12075
12076 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12077 CausesMV: !OldFD->isMultiVersion(), MVKind: NewMVKind)) {
12078 NewFD->setInvalidDecl();
12079 return true;
12080 }
12081
12082 // Permit forward declarations in the case where these two are compatible.
12083 if (!OldFD->isMultiVersion()) {
12084 OldFD->setIsMultiVersion();
12085 NewFD->setIsMultiVersion();
12086 Redeclaration = true;
12087 OldDecl = OldFD;
12088 return false;
12089 }
12090
12091 NewFD->setIsMultiVersion();
12092 Redeclaration = false;
12093 OldDecl = nullptr;
12094 Previous.clear();
12095 return false;
12096}
12097
12098/// Check the validity of a mulitversion function declaration.
12099/// Also sets the multiversion'ness' of the function itself.
12100///
12101/// This sets NewFD->isInvalidDecl() to true if there was an error.
12102///
12103/// Returns true if there was an error, false otherwise.
12104static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
12105 bool &Redeclaration, NamedDecl *&OldDecl,
12106 LookupResult &Previous) {
12107 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12108
12109 // Check if FMV is disabled.
12110 if (TI.getTriple().isAArch64() && !TI.hasFeature(Feature: "fmv"))
12111 return false;
12112
12113 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12114 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12115 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12116 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12117 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12118 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12119
12120 // Main isn't allowed to become a multiversion function, however it IS
12121 // permitted to have 'main' be marked with the 'target' optimization hint,
12122 // for 'target_version' only default is allowed.
12123 if (NewFD->isMain()) {
12124 if (MVKind != MultiVersionKind::None &&
12125 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12126 !(MVKind == MultiVersionKind::TargetVersion &&
12127 NewTVA->isDefaultVersion())) {
12128 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_not_allowed_on_main);
12129 NewFD->setInvalidDecl();
12130 return true;
12131 }
12132 return false;
12133 }
12134
12135 // Target attribute on AArch64 is not used for multiversioning
12136 if (NewTA && TI.getTriple().isAArch64())
12137 return false;
12138
12139 // Target attribute on RISCV is not used for multiversioning
12140 if (NewTA && TI.getTriple().isRISCV())
12141 return false;
12142
12143 if (!OldDecl || !OldDecl->getAsFunction() ||
12144 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12145 DC: NewFD->getDeclContext()->getRedeclContext())) {
12146 // If there's no previous declaration, AND this isn't attempting to cause
12147 // multiversioning, this isn't an error condition.
12148 if (MVKind == MultiVersionKind::None)
12149 return false;
12150 return CheckMultiVersionFirstFunction(S, FD: NewFD);
12151 }
12152
12153 FunctionDecl *OldFD = OldDecl->getAsFunction();
12154
12155 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12156 return false;
12157
12158 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12159 // for target_clones and target_version.
12160 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12161 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
12162 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
12163 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_required_in_redecl)
12164 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
12165 NewFD->setInvalidDecl();
12166 return true;
12167 }
12168
12169 if (!OldFD->isMultiVersion()) {
12170 switch (MVKind) {
12171 case MultiVersionKind::Target:
12172 case MultiVersionKind::TargetVersion:
12173 return CheckDeclarationCausesMultiVersioning(
12174 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12175 case MultiVersionKind::TargetClones:
12176 if (OldFD->isUsed(CheckUsedAttr: false)) {
12177 NewFD->setInvalidDecl();
12178 return S.Diag(Loc: NewFD->getLocation(), DiagID: diag::err_multiversion_after_used);
12179 }
12180 OldFD->setIsMultiVersion();
12181 break;
12182
12183 case MultiVersionKind::CPUDispatch:
12184 case MultiVersionKind::CPUSpecific:
12185 case MultiVersionKind::None:
12186 break;
12187 }
12188 }
12189
12190 // At this point, we have a multiversion function decl (in OldFD) AND an
12191 // appropriate attribute in the current function decl (unless it's allowed to
12192 // omit the attribute). Resolve that these are still compatible with previous
12193 // declarations.
12194 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12195 NewCPUSpec, NewClones, Redeclaration,
12196 OldDecl, Previous);
12197}
12198
12199static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) {
12200 bool IsPure = NewFD->hasAttr<PureAttr>();
12201 bool IsConst = NewFD->hasAttr<ConstAttr>();
12202
12203 // If there are no pure or const attributes, there's nothing to check.
12204 if (!IsPure && !IsConst)
12205 return;
12206
12207 // If the function is marked both pure and const, we retain the const
12208 // attribute because it makes stronger guarantees than the pure attribute, and
12209 // we drop the pure attribute explicitly to prevent later confusion about
12210 // semantics.
12211 if (IsPure && IsConst) {
12212 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_const_attr_with_pure_attr);
12213 NewFD->dropAttrs<PureAttr>();
12214 }
12215
12216 // Constructors and destructors are functions which return void, so are
12217 // handled here as well.
12218 if (NewFD->getReturnType()->isVoidType()) {
12219 S.Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_pure_function_returns_void)
12220 << IsConst;
12221 NewFD->dropAttrs<PureAttr, ConstAttr>();
12222 }
12223}
12224
12225bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
12226 LookupResult &Previous,
12227 bool IsMemberSpecialization,
12228 bool DeclIsDefn) {
12229 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12230 "Variably modified return types are not handled here");
12231
12232 // Determine whether the type of this function should be merged with
12233 // a previous visible declaration. This never happens for functions in C++,
12234 // and always happens in C if the previous declaration was visible.
12235 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12236 !Previous.isShadowed();
12237
12238 bool Redeclaration = false;
12239 NamedDecl *OldDecl = nullptr;
12240 bool MayNeedOverloadableChecks = false;
12241
12242 inferLifetimeCaptureByAttribute(FD: NewFD);
12243 // Merge or overload the declaration with an existing declaration of
12244 // the same name, if appropriate.
12245 if (!Previous.empty()) {
12246 // Determine whether NewFD is an overload of PrevDecl or
12247 // a declaration that requires merging. If it's an overload,
12248 // there's no more work to do here; we'll just add the new
12249 // function to the scope.
12250 if (!AllowOverloadingOfFunction(Previous, Context, New: NewFD)) {
12251 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12252 if (shouldLinkPossiblyHiddenDecl(Old: Candidate, New: NewFD)) {
12253 Redeclaration = true;
12254 OldDecl = Candidate;
12255 }
12256 } else {
12257 MayNeedOverloadableChecks = true;
12258 switch (CheckOverload(S, New: NewFD, OldDecls: Previous, OldDecl,
12259 /*NewIsUsingDecl*/ UseMemberUsingDeclRules: false)) {
12260 case OverloadKind::Match:
12261 Redeclaration = true;
12262 break;
12263
12264 case OverloadKind::NonFunction:
12265 Redeclaration = true;
12266 break;
12267
12268 case OverloadKind::Overload:
12269 Redeclaration = false;
12270 break;
12271 }
12272 }
12273 }
12274
12275 // Check for a previous extern "C" declaration with this name.
12276 if (!Redeclaration &&
12277 checkForConflictWithNonVisibleExternC(S&: *this, ND: NewFD, Previous)) {
12278 if (!Previous.empty()) {
12279 // This is an extern "C" declaration with the same name as a previous
12280 // declaration, and thus redeclares that entity...
12281 Redeclaration = true;
12282 OldDecl = Previous.getFoundDecl();
12283 MergeTypeWithPrevious = false;
12284
12285 // ... except in the presence of __attribute__((overloadable)).
12286 if (OldDecl->hasAttr<OverloadableAttr>() ||
12287 NewFD->hasAttr<OverloadableAttr>()) {
12288 if (IsOverload(New: NewFD, Old: cast<FunctionDecl>(Val: OldDecl), UseMemberUsingDeclRules: false)) {
12289 MayNeedOverloadableChecks = true;
12290 Redeclaration = false;
12291 OldDecl = nullptr;
12292 }
12293 }
12294 }
12295 }
12296
12297 if (CheckMultiVersionFunction(S&: *this, NewFD, Redeclaration, OldDecl, Previous))
12298 return Redeclaration;
12299
12300 // PPC MMA non-pointer types are not allowed as function return types.
12301 if (Context.getTargetInfo().getTriple().isPPC64() &&
12302 PPC().CheckPPCMMAType(Type: NewFD->getReturnType(), TypeLoc: NewFD->getLocation())) {
12303 NewFD->setInvalidDecl();
12304 }
12305
12306 CheckConstPureAttributesUsage(S&: *this, NewFD);
12307
12308 // C++ [dcl.spec.auto.general]p12:
12309 // Return type deduction for a templated function with a placeholder in its
12310 // declared type occurs when the definition is instantiated even if the
12311 // function body contains a return statement with a non-type-dependent
12312 // operand.
12313 //
12314 // C++ [temp.dep.expr]p3:
12315 // An id-expression is type-dependent if it is a template-id that is not a
12316 // concept-id and is dependent; or if its terminal name is:
12317 // - [...]
12318 // - associated by name lookup with one or more declarations of member
12319 // functions of a class that is the current instantiation declared with a
12320 // return type that contains a placeholder type,
12321 // - [...]
12322 //
12323 // If this is a templated function with a placeholder in its return type,
12324 // make the placeholder type dependent since it won't be deduced until the
12325 // definition is instantiated. We do this here because it needs to happen
12326 // for implicitly instantiated member functions/member function templates.
12327 if (getLangOpts().CPlusPlus14 &&
12328 (NewFD->isDependentContext() &&
12329 NewFD->getReturnType()->isUndeducedType())) {
12330 const FunctionProtoType *FPT =
12331 NewFD->getType()->castAs<FunctionProtoType>();
12332 QualType NewReturnType = SubstAutoTypeDependent(TypeWithAuto: FPT->getReturnType());
12333 NewFD->setType(Context.getFunctionType(ResultTy: NewReturnType, Args: FPT->getParamTypes(),
12334 EPI: FPT->getExtProtoInfo()));
12335 }
12336
12337 // C++11 [dcl.constexpr]p8:
12338 // A constexpr specifier for a non-static member function that is not
12339 // a constructor declares that member function to be const.
12340 //
12341 // This needs to be delayed until we know whether this is an out-of-line
12342 // definition of a static member function.
12343 //
12344 // This rule is not present in C++1y, so we produce a backwards
12345 // compatibility warning whenever it happens in C++11.
12346 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
12347 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12348 !MD->isStatic() && !isa<CXXConstructorDecl>(Val: MD) &&
12349 !isa<CXXDestructorDecl>(Val: MD) && !MD->getMethodQualifiers().hasConst()) {
12350 CXXMethodDecl *OldMD = nullptr;
12351 if (OldDecl)
12352 OldMD = dyn_cast_or_null<CXXMethodDecl>(Val: OldDecl->getAsFunction());
12353 if (!OldMD || !OldMD->isStatic()) {
12354 const FunctionProtoType *FPT =
12355 MD->getType()->castAs<FunctionProtoType>();
12356 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12357 EPI.TypeQuals.addConst();
12358 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
12359 Args: FPT->getParamTypes(), EPI));
12360
12361 // Warn that we did this, if we're not performing template instantiation.
12362 // In that case, we'll have warned already when the template was defined.
12363 if (!inTemplateInstantiation()) {
12364 SourceLocation AddConstLoc;
12365 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
12366 .IgnoreParens().getAs<FunctionTypeLoc>())
12367 AddConstLoc = getLocForEndOfToken(Loc: FTL.getRParenLoc());
12368
12369 Diag(Loc: MD->getLocation(), DiagID: diag::warn_cxx14_compat_constexpr_not_const)
12370 << FixItHint::CreateInsertion(InsertionLoc: AddConstLoc, Code: " const");
12371 }
12372 }
12373 }
12374
12375 if (Redeclaration) {
12376 // NewFD and OldDecl represent declarations that need to be
12377 // merged.
12378 if (MergeFunctionDecl(New: NewFD, OldD&: OldDecl, S, MergeTypeWithOld: MergeTypeWithPrevious,
12379 NewDeclIsDefn: DeclIsDefn)) {
12380 NewFD->setInvalidDecl();
12381 return Redeclaration;
12382 }
12383
12384 Previous.clear();
12385 Previous.addDecl(D: OldDecl);
12386
12387 if (FunctionTemplateDecl *OldTemplateDecl =
12388 dyn_cast<FunctionTemplateDecl>(Val: OldDecl)) {
12389 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12390 FunctionTemplateDecl *NewTemplateDecl
12391 = NewFD->getDescribedFunctionTemplate();
12392 assert(NewTemplateDecl && "Template/non-template mismatch");
12393
12394 // The call to MergeFunctionDecl above may have created some state in
12395 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12396 // can add it as a redeclaration.
12397 NewTemplateDecl->mergePrevDecl(Prev: OldTemplateDecl);
12398
12399 NewFD->setPreviousDeclaration(OldFD);
12400 if (NewFD->isCXXClassMember()) {
12401 NewFD->setAccess(OldTemplateDecl->getAccess());
12402 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12403 }
12404
12405 // If this is an explicit specialization of a member that is a function
12406 // template, mark it as a member specialization.
12407 if (IsMemberSpecialization &&
12408 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12409 NewTemplateDecl->setMemberSpecialization();
12410 assert(OldTemplateDecl->isMemberSpecialization());
12411 // Explicit specializations of a member template do not inherit deleted
12412 // status from the parent member template that they are specializing.
12413 if (OldFD->isDeleted()) {
12414 // FIXME: This assert will not hold in the presence of modules.
12415 assert(OldFD->getCanonicalDecl() == OldFD);
12416 // FIXME: We need an update record for this AST mutation.
12417 OldFD->setDeletedAsWritten(D: false);
12418 }
12419 }
12420
12421 } else {
12422 if (shouldLinkDependentDeclWithPrevious(D: NewFD, PrevDecl: OldDecl)) {
12423 auto *OldFD = cast<FunctionDecl>(Val: OldDecl);
12424 // This needs to happen first so that 'inline' propagates.
12425 NewFD->setPreviousDeclaration(OldFD);
12426 if (NewFD->isCXXClassMember())
12427 NewFD->setAccess(OldFD->getAccess());
12428 }
12429 }
12430 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12431 !NewFD->getAttr<OverloadableAttr>()) {
12432 assert((Previous.empty() ||
12433 llvm::any_of(Previous,
12434 [](const NamedDecl *ND) {
12435 return ND->hasAttr<OverloadableAttr>();
12436 })) &&
12437 "Non-redecls shouldn't happen without overloadable present");
12438
12439 auto OtherUnmarkedIter = llvm::find_if(Range&: Previous, P: [](const NamedDecl *ND) {
12440 const auto *FD = dyn_cast<FunctionDecl>(Val: ND);
12441 return FD && !FD->hasAttr<OverloadableAttr>();
12442 });
12443
12444 if (OtherUnmarkedIter != Previous.end()) {
12445 Diag(Loc: NewFD->getLocation(),
12446 DiagID: diag::err_attribute_overloadable_multiple_unmarked_overloads);
12447 Diag(Loc: (*OtherUnmarkedIter)->getLocation(),
12448 DiagID: diag::note_attribute_overloadable_prev_overload)
12449 << false;
12450
12451 NewFD->addAttr(A: OverloadableAttr::CreateImplicit(Ctx&: Context));
12452 }
12453 }
12454
12455 if (LangOpts.OpenMP)
12456 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: NewFD);
12457
12458 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12459 SYCL().CheckSYCLEntryPointFunctionDecl(FD: NewFD);
12460
12461 if (NewFD->hasAttr<SYCLExternalAttr>())
12462 SYCL().CheckSYCLExternalFunctionDecl(FD: NewFD);
12463
12464 // Semantic checking for this function declaration (in isolation).
12465
12466 if (getLangOpts().CPlusPlus) {
12467 // C++-specific checks.
12468 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: NewFD)) {
12469 CheckConstructor(Constructor);
12470 } else if (CXXDestructorDecl *Destructor =
12471 dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
12472 // We check here for invalid destructor names.
12473 // If we have a friend destructor declaration that is dependent, we can't
12474 // diagnose right away because cases like this are still valid:
12475 // template <class T> struct A { friend T::X::~Y(); };
12476 // struct B { struct Y { ~Y(); }; using X = Y; };
12477 // template struct A<B>;
12478 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12479 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12480 CanQualType ClassType =
12481 Context.getCanonicalTagType(TD: Destructor->getParent());
12482
12483 DeclarationName Name =
12484 Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
12485 if (NewFD->getDeclName() != Name) {
12486 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_destructor_name);
12487 NewFD->setInvalidDecl();
12488 return Redeclaration;
12489 }
12490 }
12491 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: NewFD)) {
12492 if (auto *TD = Guide->getDescribedFunctionTemplate())
12493 CheckDeductionGuideTemplate(TD);
12494
12495 // A deduction guide is not on the list of entities that can be
12496 // explicitly specialized.
12497 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12498 Diag(Loc: Guide->getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
12499 << /*explicit specialization*/ 1;
12500 }
12501
12502 // Find any virtual functions that this function overrides.
12503 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD)) {
12504 if (!Method->isFunctionTemplateSpecialization() &&
12505 !Method->getDescribedFunctionTemplate() &&
12506 Method->isCanonicalDecl()) {
12507 AddOverriddenMethods(DC: Method->getParent(), MD: Method);
12508 }
12509 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12510 // C++2a [class.virtual]p6
12511 // A virtual method shall not have a requires-clause.
12512 Diag(Loc: NewFD->getTrailingRequiresClause().ConstraintExpr->getBeginLoc(),
12513 DiagID: diag::err_constrained_virtual_method);
12514
12515 if (Method->isStatic())
12516 checkThisInStaticMemberFunctionType(Method);
12517 }
12518
12519 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: NewFD))
12520 ActOnConversionDeclarator(Conversion);
12521
12522 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12523 if (NewFD->isOverloadedOperator() &&
12524 CheckOverloadedOperatorDeclaration(FnDecl: NewFD)) {
12525 NewFD->setInvalidDecl();
12526 return Redeclaration;
12527 }
12528
12529 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12530 if (NewFD->getLiteralIdentifier() &&
12531 CheckLiteralOperatorDeclaration(FnDecl: NewFD)) {
12532 NewFD->setInvalidDecl();
12533 return Redeclaration;
12534 }
12535
12536 // In C++, check default arguments now that we have merged decls. Unless
12537 // the lexical context is the class, because in this case this is done
12538 // during delayed parsing anyway.
12539 if (!CurContext->isRecord())
12540 CheckCXXDefaultArguments(FD: NewFD);
12541
12542 // If this function is declared as being extern "C", then check to see if
12543 // the function returns a UDT (class, struct, or union type) that is not C
12544 // compatible, and if it does, warn the user.
12545 // But, issue any diagnostic on the first declaration only.
12546 if (Previous.empty() && NewFD->isExternC()) {
12547 QualType R = NewFD->getReturnType();
12548 if (R->isIncompleteType() && !R->isVoidType())
12549 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt_incomplete)
12550 << NewFD << R;
12551 else if (!R.isPODType(Context) && !R->isVoidType() &&
12552 !R->isObjCObjectPointerType())
12553 Diag(Loc: NewFD->getLocation(), DiagID: diag::warn_return_value_udt) << NewFD << R;
12554 }
12555
12556 // C++1z [dcl.fct]p6:
12557 // [...] whether the function has a non-throwing exception-specification
12558 // [is] part of the function type
12559 //
12560 // This results in an ABI break between C++14 and C++17 for functions whose
12561 // declared type includes an exception-specification in a parameter or
12562 // return type. (Exception specifications on the function itself are OK in
12563 // most cases, and exception specifications are not permitted in most other
12564 // contexts where they could make it into a mangling.)
12565 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12566 auto HasNoexcept = [&](QualType T) -> bool {
12567 // Strip off declarator chunks that could be between us and a function
12568 // type. We don't need to look far, exception specifications are very
12569 // restricted prior to C++17.
12570 if (auto *RT = T->getAs<ReferenceType>())
12571 T = RT->getPointeeType();
12572 else if (T->isAnyPointerType())
12573 T = T->getPointeeType();
12574 else if (auto *MPT = T->getAs<MemberPointerType>())
12575 T = MPT->getPointeeType();
12576 if (auto *FPT = T->getAs<FunctionProtoType>())
12577 if (FPT->isNothrow())
12578 return true;
12579 return false;
12580 };
12581
12582 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12583 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12584 for (QualType T : FPT->param_types())
12585 AnyNoexcept |= HasNoexcept(T);
12586 if (AnyNoexcept)
12587 Diag(Loc: NewFD->getLocation(),
12588 DiagID: diag::warn_cxx17_compat_exception_spec_in_signature)
12589 << NewFD;
12590 }
12591
12592 if (!Redeclaration && LangOpts.CUDA) {
12593 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12594 for (auto *Parm : NewFD->parameters()) {
12595 if (!Parm->getType()->isDependentType() &&
12596 Parm->hasAttr<CUDAGridConstantAttr>() &&
12597 !(IsKernel && Parm->getType().isConstQualified()))
12598 Diag(Loc: Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12599 DiagID: diag::err_cuda_grid_constant_not_allowed);
12600 }
12601 CUDA().checkTargetOverload(NewFD, Previous);
12602 }
12603 }
12604
12605 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12606 ARM().CheckSMEFunctionDefAttributes(FD: NewFD);
12607
12608 return Redeclaration;
12609}
12610
12611void Sema::CheckMain(FunctionDecl *FD, const DeclSpec &DS) {
12612 // [basic.start.main]p3
12613 // The main function shall not be declared with C linkage-specification.
12614 if (FD->isExternCContext())
12615 Diag(Loc: FD->getLocation(), DiagID: diag::ext_main_invalid_linkage_specification);
12616
12617 // C++11 [basic.start.main]p3:
12618 // A program that [...] declares main to be inline, static or
12619 // constexpr is ill-formed.
12620 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12621 // appear in a declaration of main.
12622 // static main is not an error under C99, but we should warn about it.
12623 // We accept _Noreturn main as an extension.
12624 if (FD->getStorageClass() == SC_Static)
12625 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus
12626 ? diag::err_static_main : diag::warn_static_main)
12627 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
12628 if (FD->isInlineSpecified())
12629 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_main)
12630 << FixItHint::CreateRemoval(RemoveRange: DS.getInlineSpecLoc());
12631 if (DS.isNoreturnSpecified()) {
12632 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12633 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(Loc: NoreturnLoc));
12634 Diag(Loc: NoreturnLoc, DiagID: diag::ext_noreturn_main);
12635 Diag(Loc: NoreturnLoc, DiagID: diag::note_main_remove_noreturn)
12636 << FixItHint::CreateRemoval(RemoveRange: NoreturnRange);
12637 }
12638 if (FD->isConstexpr()) {
12639 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_constexpr_main)
12640 << FD->isConsteval()
12641 << FixItHint::CreateRemoval(RemoveRange: DS.getConstexprSpecLoc());
12642 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12643 }
12644
12645 if (getLangOpts().OpenCL) {
12646 Diag(Loc: FD->getLocation(), DiagID: diag::err_opencl_no_main)
12647 << FD->hasAttr<DeviceKernelAttr>();
12648 FD->setInvalidDecl();
12649 return;
12650 }
12651
12652 if (FD->hasAttr<SYCLExternalAttr>()) {
12653 Diag(Loc: FD->getLocation(), DiagID: diag::err_sycl_external_invalid_main)
12654 << FD->getAttr<SYCLExternalAttr>();
12655 FD->setInvalidDecl();
12656 return;
12657 }
12658
12659 // Functions named main in hlsl are default entries, but don't have specific
12660 // signatures they are required to conform to.
12661 if (getLangOpts().HLSL)
12662 return;
12663
12664 QualType T = FD->getType();
12665 assert(T->isFunctionType() && "function decl is not of function type");
12666 const FunctionType* FT = T->castAs<FunctionType>();
12667
12668 // Set default calling convention for main()
12669 if (FT->getCallConv() != CC_C) {
12670 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12671 FD->setType(QualType(FT, 0));
12672 T = Context.getCanonicalType(T: FD->getType());
12673 }
12674
12675 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12676 // In C with GNU extensions we allow main() to have non-integer return
12677 // type, but we should warn about the extension, and we disable the
12678 // implicit-return-zero rule.
12679
12680 // GCC in C mode accepts qualified 'int'.
12681 if (Context.hasSameUnqualifiedType(T1: FT->getReturnType(), T2: Context.IntTy))
12682 FD->setHasImplicitReturnZero(true);
12683 else {
12684 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::ext_main_returns_nonint);
12685 SourceRange RTRange = FD->getReturnTypeSourceRange();
12686 if (RTRange.isValid())
12687 Diag(Loc: RTRange.getBegin(), DiagID: diag::note_main_change_return_type)
12688 << FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int");
12689 }
12690 } else {
12691 // In C and C++, main magically returns 0 if you fall off the end;
12692 // set the flag which tells us that.
12693 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12694
12695 // All the standards say that main() should return 'int'.
12696 if (Context.hasSameType(T1: FT->getReturnType(), T2: Context.IntTy))
12697 FD->setHasImplicitReturnZero(true);
12698 else {
12699 // Otherwise, this is just a flat-out error.
12700 SourceRange RTRange = FD->getReturnTypeSourceRange();
12701 Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_main_returns_nonint)
12702 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "int")
12703 : FixItHint());
12704 FD->setInvalidDecl(true);
12705 }
12706
12707 // [basic.start.main]p3:
12708 // A program that declares a function main that belongs to the global scope
12709 // and is attached to a named module is ill-formed.
12710 if (FD->isInNamedModule()) {
12711 const SourceLocation start = FD->getTypeSpecStartLoc();
12712 Diag(Loc: start, DiagID: diag::warn_main_in_named_module)
12713 << FixItHint::CreateInsertion(InsertionLoc: start, Code: "extern \"C++\" ", BeforePreviousInsertions: true);
12714 }
12715 }
12716
12717 // Treat protoless main() as nullary.
12718 if (isa<FunctionNoProtoType>(Val: FT)) return;
12719
12720 const FunctionProtoType* FTP = cast<const FunctionProtoType>(Val: FT);
12721 unsigned nparams = FTP->getNumParams();
12722 assert(FD->getNumParams() == nparams);
12723
12724 bool HasExtraParameters = (nparams > 3);
12725
12726 if (FTP->isVariadic()) {
12727 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variadic_main);
12728 // FIXME: if we had information about the location of the ellipsis, we
12729 // could add a FixIt hint to remove it as a parameter.
12730 }
12731
12732 // Darwin passes an undocumented fourth argument of type char**. If
12733 // other platforms start sprouting these, the logic below will start
12734 // getting shifty.
12735 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12736 HasExtraParameters = false;
12737
12738 if (HasExtraParameters) {
12739 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_surplus_args) << nparams;
12740 FD->setInvalidDecl(true);
12741 nparams = 3;
12742 }
12743
12744 // FIXME: a lot of the following diagnostics would be improved
12745 // if we had some location information about types.
12746
12747 QualType CharPP =
12748 Context.getPointerType(T: Context.getPointerType(T: Context.CharTy));
12749 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12750
12751 for (unsigned i = 0; i < nparams; ++i) {
12752 QualType AT = FTP->getParamType(i);
12753
12754 bool mismatch = true;
12755
12756 if (Context.hasSameUnqualifiedType(T1: AT, T2: Expected[i]))
12757 mismatch = false;
12758 else if (Expected[i] == CharPP) {
12759 // As an extension, the following forms are okay:
12760 // char const **
12761 // char const * const *
12762 // char * const *
12763
12764 QualifierCollector qs;
12765 const PointerType* PT;
12766 if ((PT = qs.strip(type: AT)->getAs<PointerType>()) &&
12767 (PT = qs.strip(type: PT->getPointeeType())->getAs<PointerType>()) &&
12768 Context.hasSameType(T1: QualType(qs.strip(type: PT->getPointeeType()), 0),
12769 T2: Context.CharTy)) {
12770 qs.removeConst();
12771 mismatch = !qs.empty();
12772 }
12773 }
12774
12775 if (mismatch) {
12776 Diag(Loc: FD->getLocation(), DiagID: diag::err_main_arg_wrong) << i << Expected[i];
12777 // TODO: suggest replacing given type with expected type
12778 FD->setInvalidDecl(true);
12779 }
12780 }
12781
12782 if (nparams == 1 && !FD->isInvalidDecl()) {
12783 Diag(Loc: FD->getLocation(), DiagID: diag::warn_main_one_arg);
12784 }
12785
12786 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12787 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12788 FD->setInvalidDecl();
12789 }
12790}
12791
12792static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12793
12794 // Default calling convention for main and wmain is __cdecl
12795 if (FD->getName() == "main" || FD->getName() == "wmain")
12796 return false;
12797
12798 // Default calling convention for MinGW and Cygwin is __cdecl
12799 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12800 if (T.isOSCygMing())
12801 return false;
12802
12803 // Default calling convention for WinMain, wWinMain and DllMain
12804 // is __stdcall on 32 bit Windows
12805 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12806 return true;
12807
12808 return false;
12809}
12810
12811void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12812 QualType T = FD->getType();
12813 assert(T->isFunctionType() && "function decl is not of function type");
12814 const FunctionType *FT = T->castAs<FunctionType>();
12815
12816 // Set an implicit return of 'zero' if the function can return some integral,
12817 // enumeration, pointer or nullptr type.
12818 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12819 FT->getReturnType()->isAnyPointerType() ||
12820 FT->getReturnType()->isNullPtrType())
12821 // DllMain is exempt because a return value of zero means it failed.
12822 if (FD->getName() != "DllMain")
12823 FD->setHasImplicitReturnZero(true);
12824
12825 // Explicitly specified calling conventions are applied to MSVC entry points
12826 if (!hasExplicitCallingConv(T)) {
12827 if (isDefaultStdCall(FD, S&: *this)) {
12828 if (FT->getCallConv() != CC_X86StdCall) {
12829 FT = Context.adjustFunctionType(
12830 Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: CC_X86StdCall));
12831 FD->setType(QualType(FT, 0));
12832 }
12833 } else if (FT->getCallConv() != CC_C) {
12834 FT = Context.adjustFunctionType(Fn: FT,
12835 EInfo: FT->getExtInfo().withCallingConv(cc: CC_C));
12836 FD->setType(QualType(FT, 0));
12837 }
12838 }
12839
12840 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12841 Diag(Loc: FD->getLocation(), DiagID: diag::err_mainlike_template_decl) << FD;
12842 FD->setInvalidDecl();
12843 }
12844}
12845
12846bool Sema::CheckForConstantInitializer(Expr *Init, unsigned DiagID) {
12847 // FIXME: Need strict checking. In C89, we need to check for
12848 // any assignment, increment, decrement, function-calls, or
12849 // commas outside of a sizeof. In C99, it's the same list,
12850 // except that the aforementioned are allowed in unevaluated
12851 // expressions. Everything else falls under the
12852 // "may accept other forms of constant expressions" exception.
12853 //
12854 // Regular C++ code will not end up here (exceptions: language extensions,
12855 // OpenCL C++ etc), so the constant expression rules there don't matter.
12856 if (Init->isValueDependent()) {
12857 assert(Init->containsErrors() &&
12858 "Dependent code should only occur in error-recovery path.");
12859 return true;
12860 }
12861 const Expr *Culprit;
12862 if (Init->isConstantInitializer(Ctx&: Context, ForRef: false, Culprit: &Culprit))
12863 return false;
12864 Diag(Loc: Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12865 return true;
12866}
12867
12868namespace {
12869 // Visits an initialization expression to see if OrigDecl is evaluated in
12870 // its own initialization and throws a warning if it does.
12871 class SelfReferenceChecker
12872 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12873 Sema &S;
12874 Decl *OrigDecl;
12875 bool isRecordType;
12876 bool isPODType;
12877 bool isReferenceType;
12878 bool isInCXXOperatorCall;
12879
12880 bool isInitList;
12881 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12882
12883 public:
12884 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12885
12886 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12887 S(S), OrigDecl(OrigDecl) {
12888 isPODType = false;
12889 isRecordType = false;
12890 isReferenceType = false;
12891 isInCXXOperatorCall = false;
12892 isInitList = false;
12893 if (ValueDecl *VD = dyn_cast<ValueDecl>(Val: OrigDecl)) {
12894 isPODType = VD->getType().isPODType(Context: S.Context);
12895 isRecordType = VD->getType()->isRecordType();
12896 isReferenceType = VD->getType()->isReferenceType();
12897 }
12898 }
12899
12900 // For most expressions, just call the visitor. For initializer lists,
12901 // track the index of the field being initialized since fields are
12902 // initialized in order allowing use of previously initialized fields.
12903 void CheckExpr(Expr *E) {
12904 InitListExpr *InitList = dyn_cast<InitListExpr>(Val: E);
12905 if (!InitList) {
12906 Visit(S: E);
12907 return;
12908 }
12909
12910 // Track and increment the index here.
12911 isInitList = true;
12912 InitFieldIndex.push_back(Elt: 0);
12913 for (auto *Child : InitList->children()) {
12914 CheckExpr(E: cast<Expr>(Val: Child));
12915 ++InitFieldIndex.back();
12916 }
12917 InitFieldIndex.pop_back();
12918 }
12919
12920 // Returns true if MemberExpr is checked and no further checking is needed.
12921 // Returns false if additional checking is required.
12922 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12923 llvm::SmallVector<FieldDecl*, 4> Fields;
12924 Expr *Base = E;
12925 bool ReferenceField = false;
12926
12927 // Get the field members used.
12928 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
12929 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
12930 if (!FD)
12931 return false;
12932 Fields.push_back(Elt: FD);
12933 if (FD->getType()->isReferenceType())
12934 ReferenceField = true;
12935 Base = ME->getBase()->IgnoreParenImpCasts();
12936 }
12937
12938 // Keep checking only if the base Decl is the same.
12939 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base);
12940 if (!DRE || DRE->getDecl() != OrigDecl)
12941 return false;
12942
12943 // A reference field can be bound to an unininitialized field.
12944 if (CheckReference && !ReferenceField)
12945 return true;
12946
12947 // Convert FieldDecls to their index number.
12948 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12949 for (const FieldDecl *I : llvm::reverse(C&: Fields))
12950 UsedFieldIndex.push_back(Elt: I->getFieldIndex());
12951
12952 // See if a warning is needed by checking the first difference in index
12953 // numbers. If field being used has index less than the field being
12954 // initialized, then the use is safe.
12955 for (auto UsedIter = UsedFieldIndex.begin(),
12956 UsedEnd = UsedFieldIndex.end(),
12957 OrigIter = InitFieldIndex.begin(),
12958 OrigEnd = InitFieldIndex.end();
12959 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12960 if (*UsedIter < *OrigIter)
12961 return true;
12962 if (*UsedIter > *OrigIter)
12963 break;
12964 }
12965
12966 // TODO: Add a different warning which will print the field names.
12967 HandleDeclRefExpr(DRE);
12968 return true;
12969 }
12970
12971 // For most expressions, the cast is directly above the DeclRefExpr.
12972 // For conditional operators, the cast can be outside the conditional
12973 // operator if both expressions are DeclRefExpr's.
12974 void HandleValue(Expr *E) {
12975 E = E->IgnoreParens();
12976 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(Val: E)) {
12977 HandleDeclRefExpr(DRE);
12978 return;
12979 }
12980
12981 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12982 Visit(S: CO->getCond());
12983 HandleValue(E: CO->getTrueExpr());
12984 HandleValue(E: CO->getFalseExpr());
12985 return;
12986 }
12987
12988 if (BinaryConditionalOperator *BCO =
12989 dyn_cast<BinaryConditionalOperator>(Val: E)) {
12990 Visit(S: BCO->getCond());
12991 HandleValue(E: BCO->getFalseExpr());
12992 return;
12993 }
12994
12995 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12996 if (Expr *SE = OVE->getSourceExpr())
12997 HandleValue(E: SE);
12998 return;
12999 }
13000
13001 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13002 if (BO->getOpcode() == BO_Comma) {
13003 Visit(S: BO->getLHS());
13004 HandleValue(E: BO->getRHS());
13005 return;
13006 }
13007 }
13008
13009 if (isa<MemberExpr>(Val: E)) {
13010 if (isInitList) {
13011 if (CheckInitListMemberExpr(E: cast<MemberExpr>(Val: E),
13012 CheckReference: false /*CheckReference*/))
13013 return;
13014 }
13015
13016 Expr *Base = E->IgnoreParenImpCasts();
13017 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13018 // Check for static member variables and don't warn on them.
13019 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13020 return;
13021 Base = ME->getBase()->IgnoreParenImpCasts();
13022 }
13023 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base))
13024 HandleDeclRefExpr(DRE);
13025 return;
13026 }
13027
13028 Visit(S: E);
13029 }
13030
13031 // Reference types not handled in HandleValue are handled here since all
13032 // uses of references are bad, not just r-value uses.
13033 void VisitDeclRefExpr(DeclRefExpr *E) {
13034 if (isReferenceType)
13035 HandleDeclRefExpr(DRE: E);
13036 }
13037
13038 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13039 if (E->getCastKind() == CK_LValueToRValue) {
13040 HandleValue(E: E->getSubExpr());
13041 return;
13042 }
13043
13044 Inherited::VisitImplicitCastExpr(S: E);
13045 }
13046
13047 void VisitMemberExpr(MemberExpr *E) {
13048 if (isInitList) {
13049 if (CheckInitListMemberExpr(E, CheckReference: true /*CheckReference*/))
13050 return;
13051 }
13052
13053 // Don't warn on arrays since they can be treated as pointers.
13054 if (E->getType()->canDecayToPointerType()) return;
13055
13056 // Warn when a non-static method call is followed by non-static member
13057 // field accesses, which is followed by a DeclRefExpr.
13058 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: E->getMemberDecl());
13059 bool Warn = (MD && !MD->isStatic());
13060 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13061 while (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Base)) {
13062 if (!isa<FieldDecl>(Val: ME->getMemberDecl()))
13063 Warn = false;
13064 Base = ME->getBase()->IgnoreParenImpCasts();
13065 }
13066
13067 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Base)) {
13068 if (Warn)
13069 HandleDeclRefExpr(DRE);
13070 return;
13071 }
13072
13073 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13074 // Visit that expression.
13075 Visit(S: Base);
13076 }
13077
13078 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13079 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13080 Expr *Callee = E->getCallee();
13081
13082 if (isa<UnresolvedLookupExpr>(Val: Callee))
13083 return Inherited::VisitCXXOperatorCallExpr(S: E);
13084
13085 Visit(S: Callee);
13086 for (auto Arg: E->arguments())
13087 HandleValue(E: Arg->IgnoreParenImpCasts());
13088 }
13089
13090 void VisitLambdaExpr(LambdaExpr *E) {
13091 if (!isInCXXOperatorCall) {
13092 Inherited::VisitLambdaExpr(LE: E);
13093 return;
13094 }
13095
13096 for (Expr *Init : E->capture_inits())
13097 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: Init))
13098 HandleDeclRefExpr(DRE);
13099 else if (Init)
13100 Visit(S: Init);
13101 }
13102
13103 void VisitUnaryOperator(UnaryOperator *E) {
13104 // For POD record types, addresses of its own members are well-defined.
13105 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13106 isa<MemberExpr>(Val: E->getSubExpr()->IgnoreParens())) {
13107 if (!isPODType)
13108 HandleValue(E: E->getSubExpr());
13109 return;
13110 }
13111
13112 if (E->isIncrementDecrementOp()) {
13113 HandleValue(E: E->getSubExpr());
13114 return;
13115 }
13116
13117 Inherited::VisitUnaryOperator(S: E);
13118 }
13119
13120 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13121
13122 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13123 if (E->getConstructor()->isCopyConstructor()) {
13124 Expr *ArgExpr = E->getArg(Arg: 0);
13125 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
13126 if (ILE->getNumInits() == 1)
13127 ArgExpr = ILE->getInit(Init: 0);
13128 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
13129 if (ICE->getCastKind() == CK_NoOp)
13130 ArgExpr = ICE->getSubExpr();
13131 HandleValue(E: ArgExpr);
13132 return;
13133 }
13134 Inherited::VisitCXXConstructExpr(S: E);
13135 }
13136
13137 void VisitCallExpr(CallExpr *E) {
13138 // Treat std::move as a use.
13139 if (E->isCallToStdMove()) {
13140 HandleValue(E: E->getArg(Arg: 0));
13141 return;
13142 }
13143
13144 Inherited::VisitCallExpr(CE: E);
13145 }
13146
13147 void VisitBinaryOperator(BinaryOperator *E) {
13148 if (E->isCompoundAssignmentOp()) {
13149 HandleValue(E: E->getLHS());
13150 Visit(S: E->getRHS());
13151 return;
13152 }
13153
13154 Inherited::VisitBinaryOperator(S: E);
13155 }
13156
13157 // A custom visitor for BinaryConditionalOperator is needed because the
13158 // regular visitor would check the condition and true expression separately
13159 // but both point to the same place giving duplicate diagnostics.
13160 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13161 Visit(S: E->getCond());
13162 Visit(S: E->getFalseExpr());
13163 }
13164
13165 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13166 Decl* ReferenceDecl = DRE->getDecl();
13167 if (OrigDecl != ReferenceDecl) return;
13168 unsigned diag;
13169 if (isReferenceType) {
13170 diag = diag::warn_uninit_self_reference_in_reference_init;
13171 } else if (cast<VarDecl>(Val: OrigDecl)->isStaticLocal()) {
13172 diag = diag::warn_static_self_reference_in_init;
13173 } else if (isa<TranslationUnitDecl>(Val: OrigDecl->getDeclContext()) ||
13174 isa<NamespaceDecl>(Val: OrigDecl->getDeclContext()) ||
13175 DRE->getDecl()->getType()->isRecordType()) {
13176 diag = diag::warn_uninit_self_reference_in_init;
13177 } else {
13178 // Local variables will be handled by the CFG analysis.
13179 return;
13180 }
13181
13182 S.DiagRuntimeBehavior(Loc: DRE->getBeginLoc(), Statement: DRE,
13183 PD: S.PDiag(DiagID: diag)
13184 << DRE->getDecl() << OrigDecl->getLocation()
13185 << DRE->getSourceRange());
13186 }
13187 };
13188
13189 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13190 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13191 bool DirectInit) {
13192 // Parameters arguments are occassionially constructed with itself,
13193 // for instance, in recursive functions. Skip them.
13194 if (isa<ParmVarDecl>(Val: OrigDecl))
13195 return;
13196
13197 // Skip checking for file-scope constexpr variables - constant evaluation
13198 // will produce appropriate errors without needing runtime diagnostics.
13199 // Local constexpr should still emit runtime warnings.
13200 if (auto *VD = dyn_cast<VarDecl>(Val: OrigDecl);
13201 VD && VD->isConstexpr() && VD->isFileVarDecl())
13202 return;
13203
13204 E = E->IgnoreParens();
13205
13206 // Skip checking T a = a where T is not a record or reference type.
13207 // Doing so is a way to silence uninitialized warnings.
13208 if (!DirectInit && !cast<VarDecl>(Val: OrigDecl)->getType()->isRecordType())
13209 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
13210 if (ICE->getCastKind() == CK_LValueToRValue)
13211 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ICE->getSubExpr()))
13212 if (DRE->getDecl() == OrigDecl)
13213 return;
13214
13215 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13216 }
13217} // end anonymous namespace
13218
13219namespace {
13220 // Simple wrapper to add the name of a variable or (if no variable is
13221 // available) a DeclarationName into a diagnostic.
13222 struct VarDeclOrName {
13223 VarDecl *VDecl;
13224 DeclarationName Name;
13225
13226 friend const Sema::SemaDiagnosticBuilder &
13227 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13228 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13229 }
13230 };
13231} // end anonymous namespace
13232
13233QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
13234 DeclarationName Name, QualType Type,
13235 TypeSourceInfo *TSI,
13236 SourceRange Range, bool DirectInit,
13237 Expr *Init) {
13238 bool IsInitCapture = !VDecl;
13239 assert((!VDecl || !VDecl->isInitCapture()) &&
13240 "init captures are expected to be deduced prior to initialization");
13241
13242 VarDeclOrName VN{.VDecl: VDecl, .Name: Name};
13243
13244 DeducedType *Deduced = Type->getContainedDeducedType();
13245 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13246
13247 // Diagnose auto array declarations in C23, unless it's a supported extension.
13248 if (getLangOpts().C23 && Type->isArrayType() &&
13249 !isa_and_present<StringLiteral, InitListExpr>(Val: Init)) {
13250 Diag(Loc: Range.getBegin(), DiagID: diag::err_auto_not_allowed)
13251 << (int)Deduced->getContainedAutoType()->getKeyword()
13252 << /*in array decl*/ 23 << Range;
13253 return QualType();
13254 }
13255
13256 // C++11 [dcl.spec.auto]p3
13257 if (!Init) {
13258 assert(VDecl && "no init for init capture deduction?");
13259
13260 // Except for class argument deduction, and then for an initializing
13261 // declaration only, i.e. no static at class scope or extern.
13262 if (!isa<DeducedTemplateSpecializationType>(Val: Deduced) ||
13263 VDecl->hasExternalStorage() ||
13264 VDecl->isStaticDataMember()) {
13265 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_auto_var_requires_init)
13266 << VDecl->getDeclName() << Type;
13267 return QualType();
13268 }
13269 }
13270
13271 ArrayRef<Expr*> DeduceInits;
13272 if (Init)
13273 DeduceInits = Init;
13274
13275 auto *PL = dyn_cast_if_present<ParenListExpr>(Val: Init);
13276 if (DirectInit && PL)
13277 DeduceInits = PL->exprs();
13278
13279 if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
13280 assert(VDecl && "non-auto type for init capture deduction?");
13281 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
13282 InitializationKind Kind = InitializationKind::CreateForInit(
13283 Loc: VDecl->getLocation(), DirectInit, Init);
13284 // FIXME: Initialization should not be taking a mutable list of inits.
13285 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13286 return DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind,
13287 Init: InitsCopy);
13288 }
13289
13290 if (DirectInit) {
13291 if (auto *IL = dyn_cast<InitListExpr>(Val: Init))
13292 DeduceInits = IL->inits();
13293 }
13294
13295 // Deduction only works if we have exactly one source expression.
13296 if (DeduceInits.empty()) {
13297 // It isn't possible to write this directly, but it is possible to
13298 // end up in this situation with "auto x(some_pack...);"
13299 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13300 ? diag::err_init_capture_no_expression
13301 : diag::err_auto_var_init_no_expression)
13302 << VN << Type << Range;
13303 return QualType();
13304 }
13305
13306 if (DeduceInits.size() > 1) {
13307 Diag(Loc: DeduceInits[1]->getBeginLoc(),
13308 DiagID: IsInitCapture ? diag::err_init_capture_multiple_expressions
13309 : diag::err_auto_var_init_multiple_expressions)
13310 << VN << Type << Range;
13311 return QualType();
13312 }
13313
13314 Expr *DeduceInit = DeduceInits[0];
13315 if (DirectInit && isa<InitListExpr>(Val: DeduceInit)) {
13316 Diag(Loc: Init->getBeginLoc(), DiagID: IsInitCapture
13317 ? diag::err_init_capture_paren_braces
13318 : diag::err_auto_var_init_paren_braces)
13319 << isa<InitListExpr>(Val: Init) << VN << Type << Range;
13320 return QualType();
13321 }
13322
13323 // Expressions default to 'id' when we're in a debugger.
13324 bool DefaultedAnyToId = false;
13325 if (getLangOpts().DebuggerCastResultToId &&
13326 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13327 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
13328 if (Result.isInvalid()) {
13329 return QualType();
13330 }
13331 Init = Result.get();
13332 DefaultedAnyToId = true;
13333 }
13334
13335 // C++ [dcl.decomp]p1:
13336 // If the assignment-expression [...] has array type A and no ref-qualifier
13337 // is present, e has type cv A
13338 if (VDecl && isa<DecompositionDecl>(Val: VDecl) &&
13339 Context.hasSameUnqualifiedType(T1: Type, T2: Context.getAutoDeductType()) &&
13340 DeduceInit->getType()->isConstantArrayType())
13341 return Context.getQualifiedType(T: DeduceInit->getType(),
13342 Qs: Type.getQualifiers());
13343
13344 QualType DeducedType;
13345 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13346 TemplateDeductionResult Result =
13347 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeduceInit, Result&: DeducedType, Info);
13348 if (Result != TemplateDeductionResult::Success &&
13349 Result != TemplateDeductionResult::AlreadyDiagnosed) {
13350 if (!IsInitCapture)
13351 DiagnoseAutoDeductionFailure(VDecl, Init: DeduceInit);
13352 else if (isa<InitListExpr>(Val: Init))
13353 Diag(Loc: Range.getBegin(),
13354 DiagID: diag::err_init_capture_deduction_failure_from_init_list)
13355 << VN
13356 << (DeduceInit->getType().isNull() ? TSI->getType()
13357 : DeduceInit->getType())
13358 << DeduceInit->getSourceRange();
13359 else
13360 Diag(Loc: Range.getBegin(), DiagID: diag::err_init_capture_deduction_failure)
13361 << VN << TSI->getType()
13362 << (DeduceInit->getType().isNull() ? TSI->getType()
13363 : DeduceInit->getType())
13364 << DeduceInit->getSourceRange();
13365 }
13366
13367 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13368 // 'id' instead of a specific object type prevents most of our usual
13369 // checks.
13370 // We only want to warn outside of template instantiations, though:
13371 // inside a template, the 'id' could have come from a parameter.
13372 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13373 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13374 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13375 Diag(Loc, DiagID: diag::warn_auto_var_is_id) << VN << Range;
13376 }
13377
13378 return DeducedType;
13379}
13380
13381bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13382 Expr *Init) {
13383 assert(!Init || !Init->containsErrors());
13384 QualType DeducedType = deduceVarTypeFromInitializer(
13385 VDecl, Name: VDecl->getDeclName(), Type: VDecl->getType(), TSI: VDecl->getTypeSourceInfo(),
13386 Range: VDecl->getSourceRange(), DirectInit, Init);
13387 if (DeducedType.isNull()) {
13388 VDecl->setInvalidDecl();
13389 return true;
13390 }
13391
13392 VDecl->setType(DeducedType);
13393 assert(VDecl->isLinkageValid());
13394
13395 // In ARC, infer lifetime.
13396 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: VDecl))
13397 VDecl->setInvalidDecl();
13398
13399 if (getLangOpts().OpenCL)
13400 deduceOpenCLAddressSpace(Var: VDecl);
13401
13402 if (getLangOpts().HLSL)
13403 HLSL().deduceAddressSpace(Decl: VDecl);
13404
13405 // If this is a redeclaration, check that the type we just deduced matches
13406 // the previously declared type.
13407 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13408 // We never need to merge the type, because we cannot form an incomplete
13409 // array of auto, nor deduce such a type.
13410 MergeVarDeclTypes(New: VDecl, Old, /*MergeTypeWithPrevious*/ MergeTypeWithOld: false);
13411 }
13412
13413 // Check the deduced type is valid for a variable declaration.
13414 CheckVariableDeclarationType(NewVD: VDecl);
13415 return VDecl->isInvalidDecl();
13416}
13417
13418void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13419 SourceLocation Loc) {
13420 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Init))
13421 Init = EWC->getSubExpr();
13422
13423 if (auto *CE = dyn_cast<ConstantExpr>(Val: Init))
13424 Init = CE->getSubExpr();
13425
13426 QualType InitType = Init->getType();
13427 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13428 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13429 "shouldn't be called if type doesn't have a non-trivial C struct");
13430 if (auto *ILE = dyn_cast<InitListExpr>(Val: Init)) {
13431 for (auto *I : ILE->inits()) {
13432 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13433 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13434 continue;
13435 SourceLocation SL = I->getExprLoc();
13436 checkNonTrivialCUnionInInitializer(Init: I, Loc: SL.isValid() ? SL : Loc);
13437 }
13438 return;
13439 }
13440
13441 if (isa<ImplicitValueInitExpr>(Val: Init)) {
13442 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13443 checkNonTrivialCUnion(QT: InitType, Loc,
13444 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
13445 NonTrivialKind: NTCUK_Init);
13446 } else {
13447 // Assume all other explicit initializers involving copying some existing
13448 // object.
13449 // TODO: ignore any explicit initializers where we can guarantee
13450 // copy-elision.
13451 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13452 checkNonTrivialCUnion(QT: InitType, Loc, UseContext: NonTrivialCUnionContext::CopyInit,
13453 NonTrivialKind: NTCUK_Copy);
13454 }
13455}
13456
13457namespace {
13458
13459bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13460 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13461 // in the source code or implicitly by the compiler if it is in a union
13462 // defined in a system header and has non-trivial ObjC ownership
13463 // qualifications. We don't want those fields to participate in determining
13464 // whether the containing union is non-trivial.
13465 return FD->hasAttr<UnavailableAttr>();
13466}
13467
13468struct DiagNonTrivalCUnionDefaultInitializeVisitor
13469 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13470 void> {
13471 using Super =
13472 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13473 void>;
13474
13475 DiagNonTrivalCUnionDefaultInitializeVisitor(
13476 QualType OrigTy, SourceLocation OrigLoc,
13477 NonTrivialCUnionContext UseContext, Sema &S)
13478 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13479
13480 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13481 const FieldDecl *FD, bool InNonTrivialUnion) {
13482 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13483 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13484 Args&: InNonTrivialUnion);
13485 return Super::visitWithKind(PDIK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13486 }
13487
13488 void visitARCStrong(QualType QT, const FieldDecl *FD,
13489 bool InNonTrivialUnion) {
13490 if (InNonTrivialUnion)
13491 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13492 << 1 << 0 << QT << FD->getName();
13493 }
13494
13495 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13496 if (InNonTrivialUnion)
13497 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13498 << 1 << 0 << QT << FD->getName();
13499 }
13500
13501 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13502 const auto *RD = QT->castAsRecordDecl();
13503 if (RD->isUnion()) {
13504 if (OrigLoc.isValid()) {
13505 bool IsUnion = false;
13506 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13507 IsUnion = OrigRD->isUnion();
13508 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13509 << 0 << OrigTy << IsUnion << UseContext;
13510 // Reset OrigLoc so that this diagnostic is emitted only once.
13511 OrigLoc = SourceLocation();
13512 }
13513 InNonTrivialUnion = true;
13514 }
13515
13516 if (InNonTrivialUnion)
13517 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13518 << 0 << 0 << QT.getUnqualifiedType() << "";
13519
13520 for (const FieldDecl *FD : RD->fields())
13521 if (!shouldIgnoreForRecordTriviality(FD))
13522 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13523 }
13524
13525 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13526
13527 // The non-trivial C union type or the struct/union type that contains a
13528 // non-trivial C union.
13529 QualType OrigTy;
13530 SourceLocation OrigLoc;
13531 NonTrivialCUnionContext UseContext;
13532 Sema &S;
13533};
13534
13535struct DiagNonTrivalCUnionDestructedTypeVisitor
13536 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13537 using Super =
13538 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13539
13540 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13541 SourceLocation OrigLoc,
13542 NonTrivialCUnionContext UseContext,
13543 Sema &S)
13544 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13545
13546 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13547 const FieldDecl *FD, bool InNonTrivialUnion) {
13548 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13549 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13550 Args&: InNonTrivialUnion);
13551 return Super::visitWithKind(DK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13552 }
13553
13554 void visitARCStrong(QualType QT, const FieldDecl *FD,
13555 bool InNonTrivialUnion) {
13556 if (InNonTrivialUnion)
13557 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13558 << 1 << 1 << QT << FD->getName();
13559 }
13560
13561 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13562 if (InNonTrivialUnion)
13563 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13564 << 1 << 1 << QT << FD->getName();
13565 }
13566
13567 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13568 const auto *RD = QT->castAsRecordDecl();
13569 if (RD->isUnion()) {
13570 if (OrigLoc.isValid()) {
13571 bool IsUnion = false;
13572 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13573 IsUnion = OrigRD->isUnion();
13574 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13575 << 1 << OrigTy << IsUnion << UseContext;
13576 // Reset OrigLoc so that this diagnostic is emitted only once.
13577 OrigLoc = SourceLocation();
13578 }
13579 InNonTrivialUnion = true;
13580 }
13581
13582 if (InNonTrivialUnion)
13583 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13584 << 0 << 1 << QT.getUnqualifiedType() << "";
13585
13586 for (const FieldDecl *FD : RD->fields())
13587 if (!shouldIgnoreForRecordTriviality(FD))
13588 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13589 }
13590
13591 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13592 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13593 bool InNonTrivialUnion) {}
13594
13595 // The non-trivial C union type or the struct/union type that contains a
13596 // non-trivial C union.
13597 QualType OrigTy;
13598 SourceLocation OrigLoc;
13599 NonTrivialCUnionContext UseContext;
13600 Sema &S;
13601};
13602
13603struct DiagNonTrivalCUnionCopyVisitor
13604 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13605 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13606
13607 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13608 NonTrivialCUnionContext UseContext, Sema &S)
13609 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13610
13611 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13612 const FieldDecl *FD, bool InNonTrivialUnion) {
13613 if (const auto *AT = S.Context.getAsArrayType(T: QT))
13614 return this->asDerived().visit(FT: S.Context.getBaseElementType(VAT: AT), Args&: FD,
13615 Args&: InNonTrivialUnion);
13616 return Super::visitWithKind(PCK, FT: QT, Args&: FD, Args&: InNonTrivialUnion);
13617 }
13618
13619 void visitARCStrong(QualType QT, const FieldDecl *FD,
13620 bool InNonTrivialUnion) {
13621 if (InNonTrivialUnion)
13622 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13623 << 1 << 2 << QT << FD->getName();
13624 }
13625
13626 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13627 if (InNonTrivialUnion)
13628 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13629 << 1 << 2 << QT << FD->getName();
13630 }
13631
13632 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13633 const auto *RD = QT->castAsRecordDecl();
13634 if (RD->isUnion()) {
13635 if (OrigLoc.isValid()) {
13636 bool IsUnion = false;
13637 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13638 IsUnion = OrigRD->isUnion();
13639 S.Diag(Loc: OrigLoc, DiagID: diag::err_non_trivial_c_union_in_invalid_context)
13640 << 2 << OrigTy << IsUnion << UseContext;
13641 // Reset OrigLoc so that this diagnostic is emitted only once.
13642 OrigLoc = SourceLocation();
13643 }
13644 InNonTrivialUnion = true;
13645 }
13646
13647 if (InNonTrivialUnion)
13648 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13649 << 0 << 2 << QT.getUnqualifiedType() << "";
13650
13651 for (const FieldDecl *FD : RD->fields())
13652 if (!shouldIgnoreForRecordTriviality(FD))
13653 asDerived().visit(FT: FD->getType(), Args&: FD, Args&: InNonTrivialUnion);
13654 }
13655
13656 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13657 if (InNonTrivialUnion)
13658 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_non_trivial_c_union)
13659 << 1 << 2 << QT << FD->getName();
13660 }
13661
13662 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13663 const FieldDecl *FD, bool InNonTrivialUnion) {}
13664 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13665 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13666 bool InNonTrivialUnion) {}
13667
13668 // The non-trivial C union type or the struct/union type that contains a
13669 // non-trivial C union.
13670 QualType OrigTy;
13671 SourceLocation OrigLoc;
13672 NonTrivialCUnionContext UseContext;
13673 Sema &S;
13674};
13675
13676} // namespace
13677
13678void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13679 NonTrivialCUnionContext UseContext,
13680 unsigned NonTrivialKind) {
13681 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13682 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13683 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13684 "shouldn't be called if type doesn't have a non-trivial C union");
13685
13686 if ((NonTrivialKind & NTCUK_Init) &&
13687 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13688 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13689 .visit(FT: QT, Args: nullptr, Args: false);
13690 if ((NonTrivialKind & NTCUK_Destruct) &&
13691 QT.hasNonTrivialToPrimitiveDestructCUnion())
13692 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13693 .visit(FT: QT, Args: nullptr, Args: false);
13694 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13695 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13696 .visit(FT: QT, Args: nullptr, Args: false);
13697}
13698
13699bool Sema::GloballyUniqueObjectMightBeAccidentallyDuplicated(
13700 const VarDecl *Dcl) {
13701 if (!getLangOpts().CPlusPlus)
13702 return false;
13703
13704 // We only need to warn if the definition is in a header file, so wait to
13705 // diagnose until we've seen the definition.
13706 if (!Dcl->isThisDeclarationADefinition())
13707 return false;
13708
13709 // If an object is defined in a source file, its definition can't get
13710 // duplicated since it will never appear in more than one TU.
13711 if (Dcl->getASTContext().getSourceManager().isInMainFile(Loc: Dcl->getLocation()))
13712 return false;
13713
13714 // If the variable we're looking at is a static local, then we actually care
13715 // about the properties of the function containing it.
13716 const ValueDecl *Target = Dcl;
13717 // VarDecls and FunctionDecls have different functions for checking
13718 // inline-ness, and whether they were originally templated, so we have to
13719 // call the appropriate functions manually.
13720 bool TargetIsInline = Dcl->isInline();
13721 bool TargetWasTemplated =
13722 Dcl->getTemplateSpecializationKind() != TSK_Undeclared;
13723
13724 // Update the Target and TargetIsInline property if necessary
13725 if (Dcl->isStaticLocal()) {
13726 const DeclContext *Ctx = Dcl->getDeclContext();
13727 if (!Ctx)
13728 return false;
13729
13730 const FunctionDecl *FunDcl =
13731 dyn_cast_if_present<FunctionDecl>(Val: Ctx->getNonClosureAncestor());
13732 if (!FunDcl)
13733 return false;
13734
13735 Target = FunDcl;
13736 // IsInlined() checks for the C++ inline property
13737 TargetIsInline = FunDcl->isInlined();
13738 TargetWasTemplated =
13739 FunDcl->getTemplateSpecializationKind() != TSK_Undeclared;
13740 }
13741
13742 // Non-inline functions/variables can only legally appear in one TU
13743 // unless they were part of a template. Unfortunately, making complex
13744 // template instantiations visible is infeasible in practice, since
13745 // everything the template depends on also has to be visible. To avoid
13746 // giving impractical-to-fix warnings, don't warn if we're inside
13747 // something that was templated, even on inline stuff.
13748 if (!TargetIsInline || TargetWasTemplated)
13749 return false;
13750
13751 // If the object isn't hidden, the dynamic linker will prevent duplication.
13752 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13753
13754 // The target is "hidden" (from the dynamic linker) if:
13755 // 1. On posix, it has hidden visibility, or
13756 // 2. On windows, it has no import/export annotation, and neither does the
13757 // class which directly contains it.
13758 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13759 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13760 return false;
13761
13762 // If the variable isn't directly annotated, check to see if it's a member
13763 // of an annotated class.
13764 const CXXRecordDecl *Ctx =
13765 dyn_cast<CXXRecordDecl>(Val: Target->getDeclContext());
13766 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13767 return false;
13768
13769 } else if (Lnk.getVisibility() != HiddenVisibility) {
13770 // Posix case
13771 return false;
13772 }
13773
13774 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13775 if (!isExternalFormalLinkage(L: Lnk.getLinkage()))
13776 return false;
13777
13778 return true;
13779}
13780
13781// Determine whether the object seems mutable for the purpose of diagnosing
13782// possible unique object duplication, i.e. non-const-qualified, and
13783// not an always-constant type like a function.
13784// Not perfect: doesn't account for mutable members, for example, or
13785// elements of container types.
13786// For nested pointers, any individual level being non-const is sufficient.
13787static bool looksMutable(QualType T, const ASTContext &Ctx) {
13788 T = T.getNonReferenceType();
13789 if (T->isFunctionType())
13790 return false;
13791 if (!T.isConstant(Ctx))
13792 return true;
13793 if (T->isPointerType())
13794 return looksMutable(T: T->getPointeeType(), Ctx);
13795 return false;
13796}
13797
13798void Sema::DiagnoseUniqueObjectDuplication(const VarDecl *VD) {
13799 // If this object has external linkage and hidden visibility, it might be
13800 // duplicated when built into a shared library, which causes problems if it's
13801 // mutable (since the copies won't be in sync) or its initialization has side
13802 // effects (since it will run once per copy instead of once globally).
13803
13804 // Don't diagnose if we're inside a template, because it's not practical to
13805 // fix the warning in most cases.
13806 if (!VD->isTemplated() &&
13807 GloballyUniqueObjectMightBeAccidentallyDuplicated(Dcl: VD)) {
13808
13809 QualType Type = VD->getType();
13810 if (looksMutable(T: Type, Ctx: VD->getASTContext())) {
13811 Diag(Loc: VD->getLocation(), DiagID: diag::warn_possible_object_duplication_mutable)
13812 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13813 }
13814
13815 // To keep false positives low, only warn if we're certain that the
13816 // initializer has side effects. Don't warn on operator new, since a mutable
13817 // pointer will trigger the previous warning, and an immutable pointer
13818 // getting duplicated just results in a little extra memory usage.
13819 const Expr *Init = VD->getAnyInitializer();
13820 if (Init &&
13821 Init->HasSideEffects(Ctx: VD->getASTContext(),
13822 /*IncludePossibleEffects=*/false) &&
13823 !isa<CXXNewExpr>(Val: Init->IgnoreParenImpCasts())) {
13824 Diag(Loc: Init->getExprLoc(), DiagID: diag::warn_possible_object_duplication_init)
13825 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13826 }
13827 }
13828}
13829
13830void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13831 llvm::scope_exit ResetDeclForInitializer([this]() {
13832 if (!this->ExprEvalContexts.empty())
13833 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13834 });
13835
13836 // If there is no declaration, there was an error parsing it. Just ignore
13837 // the initializer.
13838 if (!RealDecl) {
13839 return;
13840 }
13841
13842 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: RealDecl)) {
13843 if (!Method->isInvalidDecl()) {
13844 // Pure-specifiers are handled in ActOnPureSpecifier.
13845 Diag(Loc: Method->getLocation(), DiagID: diag::err_member_function_initialization)
13846 << Method->getDeclName() << Init->getSourceRange();
13847 Method->setInvalidDecl();
13848 }
13849 return;
13850 }
13851
13852 VarDecl *VDecl = dyn_cast<VarDecl>(Val: RealDecl);
13853 if (!VDecl) {
13854 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13855 Diag(Loc: RealDecl->getLocation(), DiagID: diag::err_illegal_initializer);
13856 RealDecl->setInvalidDecl();
13857 return;
13858 }
13859
13860 if (VDecl->isInvalidDecl()) {
13861 ExprResult Recovery =
13862 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init});
13863 if (Expr *E = Recovery.get())
13864 VDecl->setInit(E);
13865 return;
13866 }
13867
13868 // WebAssembly tables can't be used to initialise a variable.
13869 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13870 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_wasm_table_art) << 0;
13871 VDecl->setInvalidDecl();
13872 return;
13873 }
13874
13875 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13876 if (VDecl->getType()->isUndeducedType()) {
13877 if (Init->containsErrors()) {
13878 // Invalidate the decl as we don't know the type for recovery-expr yet.
13879 RealDecl->setInvalidDecl();
13880 VDecl->setInit(Init);
13881 return;
13882 }
13883
13884 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
13885 assert(VDecl->isInvalidDecl() &&
13886 "decl should be invalidated when deduce fails");
13887 if (auto *RecoveryExpr =
13888 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: {Init})
13889 .get())
13890 VDecl->setInit(RecoveryExpr);
13891 return;
13892 }
13893 }
13894
13895 this->CheckAttributesOnDeducedType(D: RealDecl);
13896
13897 // dllimport cannot be used on variable definitions.
13898 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13899 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_attribute_dllimport_data_definition);
13900 VDecl->setInvalidDecl();
13901 return;
13902 }
13903
13904 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13905 // the identifier has external or internal linkage, the declaration shall
13906 // have no initializer for the identifier.
13907 // C++14 [dcl.init]p5 is the same restriction for C++.
13908 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13909 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_block_extern_cant_init);
13910 VDecl->setInvalidDecl();
13911 return;
13912 }
13913
13914 if (!VDecl->getType()->isDependentType()) {
13915 // A definition must end up with a complete type, which means it must be
13916 // complete with the restriction that an array type might be completed by
13917 // the initializer; note that later code assumes this restriction.
13918 QualType BaseDeclType = VDecl->getType();
13919 if (const ArrayType *Array = Context.getAsIncompleteArrayType(T: BaseDeclType))
13920 BaseDeclType = Array->getElementType();
13921 if (RequireCompleteType(Loc: VDecl->getLocation(), T: BaseDeclType,
13922 DiagID: diag::err_typecheck_decl_incomplete_type)) {
13923 RealDecl->setInvalidDecl();
13924 return;
13925 }
13926
13927 // The variable can not have an abstract class type.
13928 if (RequireNonAbstractType(Loc: VDecl->getLocation(), T: VDecl->getType(),
13929 DiagID: diag::err_abstract_type_in_decl,
13930 Args: AbstractVariableType))
13931 VDecl->setInvalidDecl();
13932 }
13933
13934 // C++ [module.import/6]
13935 // ...
13936 // A header unit shall not contain a definition of a non-inline function or
13937 // variable whose name has external linkage.
13938 //
13939 // We choose to allow weak & selectany definitions, as they are common in
13940 // headers, and have semantics similar to inline definitions which are allowed
13941 // in header units.
13942 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13943 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13944 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13945 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(Val: VDecl) &&
13946 !VDecl->getInstantiatedFromStaticDataMember() &&
13947 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
13948 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
13949 VDecl->setInvalidDecl();
13950 }
13951
13952 // If adding the initializer will turn this declaration into a definition,
13953 // and we already have a definition for this variable, diagnose or otherwise
13954 // handle the situation.
13955 if (VarDecl *Def = VDecl->getDefinition())
13956 if (Def != VDecl &&
13957 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13958 !VDecl->isThisDeclarationADemotedDefinition() &&
13959 checkVarDeclRedefinition(Old: Def, New: VDecl))
13960 return;
13961
13962 if (getLangOpts().CPlusPlus) {
13963 // C++ [class.static.data]p4
13964 // If a static data member is of const integral or const
13965 // enumeration type, its declaration in the class definition can
13966 // specify a constant-initializer which shall be an integral
13967 // constant expression (5.19). In that case, the member can appear
13968 // in integral constant expressions. The member shall still be
13969 // defined in a namespace scope if it is used in the program and the
13970 // namespace scope definition shall not contain an initializer.
13971 //
13972 // We already performed a redefinition check above, but for static
13973 // data members we also need to check whether there was an in-class
13974 // declaration with an initializer.
13975 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13976 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_static_data_member_reinitialization)
13977 << VDecl->getDeclName();
13978 Diag(Loc: VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13979 DiagID: diag::note_previous_initializer)
13980 << 0;
13981 return;
13982 }
13983
13984 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) {
13985 VDecl->setInvalidDecl();
13986 return;
13987 }
13988 }
13989
13990 // If the variable has an initializer and local storage, check whether
13991 // anything jumps over the initialization.
13992 if (VDecl->hasLocalStorage())
13993 setFunctionHasBranchProtectedScope();
13994
13995 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13996 // a kernel function cannot be initialized."
13997 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13998 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_local_cant_init);
13999 VDecl->setInvalidDecl();
14000 return;
14001 }
14002
14003 // The LoaderUninitialized attribute acts as a definition (of undef).
14004 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14005 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_loader_uninitialized_cant_init);
14006 VDecl->setInvalidDecl();
14007 return;
14008 }
14009
14010 if (getLangOpts().HLSL)
14011 if (!HLSL().handleInitialization(VDecl, Init))
14012 return;
14013
14014 // Get the decls type and save a reference for later, since
14015 // CheckInitializerTypes may change it.
14016 QualType DclT = VDecl->getType(), SavT = DclT;
14017
14018 // Expressions default to 'id' when we're in a debugger
14019 // and we are assigning it to a variable of Objective-C pointer type.
14020 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14021 Init->getType() == Context.UnknownAnyTy) {
14022 ExprResult Result = forceUnknownAnyToType(E: Init, ToType: Context.getObjCIdType());
14023 if (!Result.isUsable()) {
14024 VDecl->setInvalidDecl();
14025 return;
14026 }
14027 Init = Result.get();
14028 }
14029
14030 // Perform the initialization.
14031 bool InitializedFromParenListExpr = false;
14032 bool IsParenListInit = false;
14033 if (!VDecl->isInvalidDecl()) {
14034 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VDecl);
14035 InitializationKind Kind = InitializationKind::CreateForInit(
14036 Loc: VDecl->getLocation(), DirectInit, Init);
14037
14038 MultiExprArg Args = Init;
14039 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init)) {
14040 Args =
14041 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14042 InitializedFromParenListExpr = true;
14043 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
14044 Args = CXXDirectInit->getInitExprs();
14045 InitializedFromParenListExpr = true;
14046 }
14047
14048 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14049 /*TopLevelOfInitList=*/false,
14050 /*TreatUnavailableAsInvalid=*/false);
14051 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
14052 if (!Result.isUsable()) {
14053 // If the provided initializer fails to initialize the var decl,
14054 // we attach a recovery expr for better recovery.
14055 auto RecoveryExpr =
14056 CreateRecoveryExpr(Begin: Init->getBeginLoc(), End: Init->getEndLoc(), SubExprs: Args);
14057 if (RecoveryExpr.get())
14058 VDecl->setInit(RecoveryExpr.get());
14059 // In general, for error recovery purposes, the initializer doesn't play
14060 // part in the valid bit of the declaration. There are a few exceptions:
14061 // 1) if the var decl has a deduced auto type, and the type cannot be
14062 // deduced by an invalid initializer;
14063 // 2) if the var decl is a decomposition decl with a non-deduced type,
14064 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14065 // Case 1) was already handled elsewhere.
14066 if (isa<DecompositionDecl>(Val: VDecl)) // Case 2)
14067 VDecl->setInvalidDecl();
14068 return;
14069 }
14070
14071 Init = Result.getAs<Expr>();
14072 IsParenListInit = !InitSeq.steps().empty() &&
14073 InitSeq.step_begin()->Kind ==
14074 InitializationSequence::SK_ParenthesizedListInit;
14075 QualType VDeclType = VDecl->getType();
14076 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14077 !VDeclType->isDependentType() &&
14078 Context.getAsIncompleteArrayType(T: VDeclType) &&
14079 Context.getAsIncompleteArrayType(T: Init->getType())) {
14080 // Bail out if it is not possible to deduce array size from the
14081 // initializer.
14082 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_typecheck_decl_incomplete_type)
14083 << VDeclType;
14084 VDecl->setInvalidDecl();
14085 return;
14086 }
14087 }
14088
14089 // Check for self-references within variable initializers.
14090 // Variables declared within a function/method body (except for references)
14091 // are handled by a dataflow analysis.
14092 // This is undefined behavior in C++, but valid in C.
14093 if (getLangOpts().CPlusPlus)
14094 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14095 VDecl->getType()->isReferenceType())
14096 CheckSelfReference(S&: *this, OrigDecl: RealDecl, E: Init, DirectInit);
14097
14098 // If the type changed, it means we had an incomplete type that was
14099 // completed by the initializer. For example:
14100 // int ary[] = { 1, 3, 5 };
14101 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14102 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14103 VDecl->setType(DclT);
14104
14105 if (!VDecl->isInvalidDecl()) {
14106 checkUnsafeAssigns(Loc: VDecl->getLocation(), LHS: VDecl->getType(), RHS: Init);
14107
14108 if (VDecl->hasAttr<BlocksAttr>())
14109 ObjC().checkRetainCycles(Var: VDecl, Init);
14110
14111 // It is safe to assign a weak reference into a strong variable.
14112 // Although this code can still have problems:
14113 // id x = self.weakProp;
14114 // id y = self.weakProp;
14115 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14116 // paths through the function. This should be revisited if
14117 // -Wrepeated-use-of-weak is made flow-sensitive.
14118 if (FunctionScopeInfo *FSI = getCurFunction())
14119 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14120 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
14121 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak,
14122 Loc: Init->getBeginLoc()))
14123 FSI->markSafeWeakUse(E: Init);
14124 }
14125
14126 // The initialization is usually a full-expression.
14127 //
14128 // FIXME: If this is a braced initialization of an aggregate, it is not
14129 // an expression, and each individual field initializer is a separate
14130 // full-expression. For instance, in:
14131 //
14132 // struct Temp { ~Temp(); };
14133 // struct S { S(Temp); };
14134 // struct T { S a, b; } t = { Temp(), Temp() }
14135 //
14136 // we should destroy the first Temp before constructing the second.
14137
14138 // Set context flag for OverflowBehaviorType initialization analysis
14139 llvm::SaveAndRestore OBTAssignmentContext(InOverflowBehaviorAssignmentContext,
14140 true);
14141 ExprResult Result =
14142 ActOnFinishFullExpr(Expr: Init, CC: VDecl->getLocation(),
14143 /*DiscardedValue*/ false, IsConstexpr: VDecl->isConstexpr());
14144 if (!Result.isUsable()) {
14145 VDecl->setInvalidDecl();
14146 return;
14147 }
14148 Init = Result.get();
14149
14150 // Attach the initializer to the decl.
14151 VDecl->setInit(Init);
14152
14153 if (VDecl->isLocalVarDecl()) {
14154 // Don't check the initializer if the declaration is malformed.
14155 if (VDecl->isInvalidDecl()) {
14156 // do nothing
14157
14158 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14159 // This is true even in C++ for OpenCL.
14160 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14161 CheckForConstantInitializer(Init);
14162
14163 // Otherwise, C++ does not restrict the initializer.
14164 } else if (getLangOpts().CPlusPlus) {
14165 // do nothing
14166
14167 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14168 // static storage duration shall be constant expressions or string literals.
14169 } else if (VDecl->getStorageClass() == SC_Static) {
14170 // Avoid evaluating the initializer twice for constexpr variables. It will
14171 // be evaluated later.
14172 if (!VDecl->isConstexpr())
14173 CheckForConstantInitializer(Init);
14174
14175 // C89 is stricter than C99 for aggregate initializers.
14176 // C89 6.5.7p3: All the expressions [...] in an initializer list
14177 // for an object that has aggregate or union type shall be
14178 // constant expressions.
14179 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14180 isa<InitListExpr>(Val: Init)) {
14181 CheckForConstantInitializer(Init, DiagID: diag::ext_aggregate_init_not_constant);
14182 }
14183
14184 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
14185 if (auto *BE = dyn_cast<BlockExpr>(Val: E->getSubExpr()->IgnoreParens()))
14186 if (VDecl->hasLocalStorage())
14187 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14188 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14189 VDecl->getLexicalDeclContext()->isRecord()) {
14190 // This is an in-class initialization for a static data member, e.g.,
14191 //
14192 // struct S {
14193 // static const int value = 17;
14194 // };
14195
14196 // C++ [class.mem]p4:
14197 // A member-declarator can contain a constant-initializer only
14198 // if it declares a static member (9.4) of const integral or
14199 // const enumeration type, see 9.4.2.
14200 //
14201 // C++11 [class.static.data]p3:
14202 // If a non-volatile non-inline const static data member is of integral
14203 // or enumeration type, its declaration in the class definition can
14204 // specify a brace-or-equal-initializer in which every initializer-clause
14205 // that is an assignment-expression is a constant expression. A static
14206 // data member of literal type can be declared in the class definition
14207 // with the constexpr specifier; if so, its declaration shall specify a
14208 // brace-or-equal-initializer in which every initializer-clause that is
14209 // an assignment-expression is a constant expression.
14210
14211 // Do nothing on dependent types.
14212 if (DclT->isDependentType()) {
14213
14214 // Allow any 'static constexpr' members, whether or not they are of literal
14215 // type. We separately check that every constexpr variable is of literal
14216 // type.
14217 } else if (VDecl->isConstexpr()) {
14218
14219 // Require constness.
14220 } else if (!DclT.isConstQualified()) {
14221 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_non_const)
14222 << Init->getSourceRange();
14223 VDecl->setInvalidDecl();
14224
14225 // We allow integer constant expressions in all cases.
14226 } else if (DclT->isIntegralOrEnumerationType()) {
14227 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
14228 // In C++11, a non-constexpr const static data member with an
14229 // in-class initializer cannot be volatile.
14230 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_volatile);
14231
14232 // We allow foldable floating-point constants as an extension.
14233 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14234 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14235 // it anyway and provide a fixit to add the 'constexpr'.
14236 if (getLangOpts().CPlusPlus11) {
14237 Diag(Loc: VDecl->getLocation(),
14238 DiagID: diag::ext_in_class_initializer_float_type_cxx11)
14239 << DclT << Init->getSourceRange();
14240 Diag(Loc: VDecl->getBeginLoc(),
14241 DiagID: diag::note_in_class_initializer_float_type_cxx11)
14242 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14243 } else {
14244 Diag(Loc: VDecl->getLocation(), DiagID: diag::ext_in_class_initializer_float_type)
14245 << DclT << Init->getSourceRange();
14246
14247 if (!Init->isValueDependent() && !Init->isEvaluatable(Ctx: Context)) {
14248 Diag(Loc: Init->getExprLoc(), DiagID: diag::err_in_class_initializer_non_constant)
14249 << Init->getSourceRange();
14250 VDecl->setInvalidDecl();
14251 }
14252 }
14253
14254 // Suggest adding 'constexpr' in C++11 for literal types.
14255 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Ctx: Context)) {
14256 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_literal_type)
14257 << DclT << Init->getSourceRange()
14258 << FixItHint::CreateInsertion(InsertionLoc: VDecl->getBeginLoc(), Code: "constexpr ");
14259 VDecl->setConstexpr(true);
14260
14261 } else {
14262 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_in_class_initializer_bad_type)
14263 << DclT << Init->getSourceRange();
14264 VDecl->setInvalidDecl();
14265 }
14266 } else if (VDecl->isFileVarDecl()) {
14267 // In C, extern is typically used to avoid tentative definitions when
14268 // declaring variables in headers, but adding an initializer makes it a
14269 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14270 // In C++, extern is often used to give implicitly static const variables
14271 // external linkage, so don't warn in that case. If selectany is present,
14272 // this might be header code intended for C and C++ inclusion, so apply the
14273 // C++ rules.
14274 if (VDecl->getStorageClass() == SC_Extern &&
14275 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14276 !Context.getBaseElementType(QT: VDecl->getType()).isConstQualified()) &&
14277 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14278 !isTemplateInstantiation(Kind: VDecl->getTemplateSpecializationKind()))
14279 Diag(Loc: VDecl->getLocation(), DiagID: diag::warn_extern_init);
14280
14281 // In Microsoft C++ mode, a const variable defined in namespace scope has
14282 // external linkage by default if the variable is declared with
14283 // __declspec(dllexport).
14284 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14285 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
14286 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14287 VDecl->setStorageClass(SC_Extern);
14288
14289 // C99 6.7.8p4. All file scoped initializers need to be constant.
14290 // Avoid duplicate diagnostics for constexpr variables.
14291 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14292 !VDecl->isConstexpr())
14293 CheckForConstantInitializer(Init);
14294 }
14295
14296 QualType InitType = Init->getType();
14297 if (!InitType.isNull() &&
14298 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
14299 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
14300 checkNonTrivialCUnionInInitializer(Init, Loc: Init->getExprLoc());
14301
14302 // We will represent direct-initialization similarly to copy-initialization:
14303 // int x(1); -as-> int x = 1;
14304 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14305 //
14306 // Clients that want to distinguish between the two forms, can check for
14307 // direct initializer using VarDecl::getInitStyle().
14308 // A major benefit is that clients that don't particularly care about which
14309 // exactly form was it (like the CodeGen) can handle both cases without
14310 // special case code.
14311
14312 // C++ 8.5p11:
14313 // The form of initialization (using parentheses or '=') matters
14314 // when the entity being initialized has class type.
14315 if (InitializedFromParenListExpr) {
14316 assert(DirectInit && "Call-style initializer must be direct init.");
14317 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14318 : VarDecl::CallInit);
14319 } else if (DirectInit) {
14320 // This must be list-initialization. No other way is direct-initialization.
14321 VDecl->setInitStyle(VarDecl::ListInit);
14322 }
14323
14324 if (LangOpts.OpenMP &&
14325 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14326 VDecl->isFileVarDecl())
14327 DeclsToCheckForDeferredDiags.insert(X: VDecl);
14328 CheckCompleteVariableDeclaration(VD: VDecl);
14329
14330 if (LangOpts.OpenACC && !InitType.isNull())
14331 OpenACC().ActOnVariableInit(VD: VDecl, InitType);
14332}
14333
14334void Sema::ActOnInitializerError(Decl *D) {
14335 // Our main concern here is re-establishing invariants like "a
14336 // variable's type is either dependent or complete".
14337 if (!D || D->isInvalidDecl()) return;
14338
14339 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14340 if (!VD) return;
14341
14342 // Bindings are not usable if we can't make sense of the initializer.
14343 if (auto *DD = dyn_cast<DecompositionDecl>(Val: D))
14344 for (auto *BD : DD->bindings())
14345 BD->setInvalidDecl();
14346
14347 // Auto types are meaningless if we can't make sense of the initializer.
14348 if (VD->getType()->isUndeducedType()) {
14349 D->setInvalidDecl();
14350 return;
14351 }
14352
14353 QualType Ty = VD->getType();
14354 if (Ty->isDependentType()) return;
14355
14356 // Require a complete type.
14357 if (RequireCompleteType(Loc: VD->getLocation(),
14358 T: Context.getBaseElementType(QT: Ty),
14359 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14360 VD->setInvalidDecl();
14361 return;
14362 }
14363
14364 // Require a non-abstract type.
14365 if (RequireNonAbstractType(Loc: VD->getLocation(), T: Ty,
14366 DiagID: diag::err_abstract_type_in_decl,
14367 Args: AbstractVariableType)) {
14368 VD->setInvalidDecl();
14369 return;
14370 }
14371
14372 // Don't bother complaining about constructors or destructors,
14373 // though.
14374}
14375
14376void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
14377 // If there is no declaration, there was an error parsing it. Just ignore it.
14378 if (!RealDecl)
14379 return;
14380
14381 if (VarDecl *Var = dyn_cast<VarDecl>(Val: RealDecl)) {
14382 QualType Type = Var->getType();
14383
14384 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14385 if (isa<DecompositionDecl>(Val: RealDecl)) {
14386 Diag(Loc: Var->getLocation(), DiagID: diag::err_decomp_decl_requires_init) << Var;
14387 Var->setInvalidDecl();
14388 return;
14389 }
14390
14391 if (Type->isUndeducedType() &&
14392 DeduceVariableDeclarationType(VDecl: Var, DirectInit: false, Init: nullptr))
14393 return;
14394
14395 this->CheckAttributesOnDeducedType(D: RealDecl);
14396
14397 // C++11 [class.static.data]p3: A static data member can be declared with
14398 // the constexpr specifier; if so, its declaration shall specify
14399 // a brace-or-equal-initializer.
14400 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14401 // the definition of a variable [...] or the declaration of a static data
14402 // member.
14403 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14404 !Var->isThisDeclarationADemotedDefinition()) {
14405 if (Var->isStaticDataMember()) {
14406 // C++1z removes the relevant rule; the in-class declaration is always
14407 // a definition there.
14408 if (!getLangOpts().CPlusPlus17 &&
14409 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14410 Diag(Loc: Var->getLocation(),
14411 DiagID: diag::err_constexpr_static_mem_var_requires_init)
14412 << Var;
14413 Var->setInvalidDecl();
14414 return;
14415 }
14416 } else {
14417 Diag(Loc: Var->getLocation(), DiagID: diag::err_invalid_constexpr_var_decl);
14418 Var->setInvalidDecl();
14419 return;
14420 }
14421 }
14422
14423 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14424 // be initialized.
14425 if (!Var->isInvalidDecl() &&
14426 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14427 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14428 bool HasConstExprDefaultConstructor = false;
14429 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14430 for (auto *Ctor : RD->ctors()) {
14431 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14432 Ctor->getMethodQualifiers().getAddressSpace() ==
14433 LangAS::opencl_constant) {
14434 HasConstExprDefaultConstructor = true;
14435 }
14436 }
14437 }
14438 if (!HasConstExprDefaultConstructor) {
14439 Diag(Loc: Var->getLocation(), DiagID: diag::err_opencl_constant_no_init);
14440 Var->setInvalidDecl();
14441 return;
14442 }
14443 }
14444
14445 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14446 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14447 Diag(Loc: Var->getLocation(), DiagID: diag::err_specialization_const);
14448 Var->setInvalidDecl();
14449 return;
14450 }
14451
14452 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14453 if (Var->getStorageClass() == SC_Extern) {
14454 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_extern_decl)
14455 << Var;
14456 Var->setInvalidDecl();
14457 return;
14458 }
14459 if (RequireCompleteType(Loc: Var->getLocation(), T: Var->getType(),
14460 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14461 Var->setInvalidDecl();
14462 return;
14463 }
14464 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14465 if (!RD->hasTrivialDefaultConstructor()) {
14466 Diag(Loc: Var->getLocation(), DiagID: diag::err_loader_uninitialized_trivial_ctor);
14467 Var->setInvalidDecl();
14468 return;
14469 }
14470 }
14471 // The declaration is uninitialized, no need for further checks.
14472 return;
14473 }
14474
14475 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14476 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14477 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14478 checkNonTrivialCUnion(QT: Var->getType(), Loc: Var->getLocation(),
14479 UseContext: NonTrivialCUnionContext::DefaultInitializedObject,
14480 NonTrivialKind: NTCUK_Init);
14481
14482 switch (DefKind) {
14483 case VarDecl::Definition:
14484 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14485 break;
14486
14487 // We have an out-of-line definition of a static data member
14488 // that has an in-class initializer, so we type-check this like
14489 // a declaration.
14490 //
14491 [[fallthrough]];
14492
14493 case VarDecl::DeclarationOnly:
14494 // It's only a declaration.
14495
14496 // Block scope. C99 6.7p7: If an identifier for an object is
14497 // declared with no linkage (C99 6.2.2p6), the type for the
14498 // object shall be complete.
14499 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14500 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14501 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14502 DiagID: diag::err_typecheck_decl_incomplete_type))
14503 Var->setInvalidDecl();
14504
14505 // Make sure that the type is not abstract.
14506 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14507 RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14508 DiagID: diag::err_abstract_type_in_decl,
14509 Args: AbstractVariableType))
14510 Var->setInvalidDecl();
14511 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14512 Var->getStorageClass() == SC_PrivateExtern) {
14513 Diag(Loc: Var->getLocation(), DiagID: diag::warn_private_extern);
14514 Diag(Loc: Var->getLocation(), DiagID: diag::note_private_extern);
14515 }
14516
14517 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14518 !Var->isInvalidDecl())
14519 ExternalDeclarations.push_back(Elt: Var);
14520
14521 return;
14522
14523 case VarDecl::TentativeDefinition:
14524 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14525 // object that has file scope without an initializer, and without a
14526 // storage-class specifier or with the storage-class specifier "static",
14527 // constitutes a tentative definition. Note: A tentative definition with
14528 // external linkage is valid (C99 6.2.2p5).
14529 if (!Var->isInvalidDecl()) {
14530 if (const IncompleteArrayType *ArrayT
14531 = Context.getAsIncompleteArrayType(T: Type)) {
14532 if (RequireCompleteSizedType(
14533 Loc: Var->getLocation(), T: ArrayT->getElementType(),
14534 DiagID: diag::err_array_incomplete_or_sizeless_type))
14535 Var->setInvalidDecl();
14536 }
14537 if (Var->getStorageClass() == SC_Static) {
14538 // C99 6.9.2p3: If the declaration of an identifier for an object is
14539 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14540 // declared type shall not be an incomplete type.
14541 // NOTE: code such as the following
14542 // static struct s;
14543 // struct s { int a; };
14544 // is accepted by gcc. Hence here we issue a warning instead of
14545 // an error and we do not invalidate the static declaration.
14546 // NOTE: to avoid multiple warnings, only check the first declaration.
14547 if (Var->isFirstDecl())
14548 RequireCompleteType(Loc: Var->getLocation(), T: Type,
14549 DiagID: diag::ext_typecheck_decl_incomplete_type,
14550 Args: Type->isArrayType());
14551 }
14552 }
14553
14554 // Record the tentative definition; we're done.
14555 if (!Var->isInvalidDecl())
14556 TentativeDefinitions.push_back(LocalValue: Var);
14557 return;
14558 }
14559
14560 // Provide a specific diagnostic for uninitialized variable definitions
14561 // with incomplete array type, unless it is a global unbounded HLSL resource
14562 // array.
14563 if (Type->isIncompleteArrayType() &&
14564 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14565 Type->isHLSLResourceRecordArray())) {
14566 if (Var->isConstexpr())
14567 Diag(Loc: Var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14568 << Var;
14569 else
14570 Diag(Loc: Var->getLocation(),
14571 DiagID: diag::err_typecheck_incomplete_array_needs_initializer);
14572 Var->setInvalidDecl();
14573 return;
14574 }
14575
14576 // Provide a specific diagnostic for uninitialized variable
14577 // definitions with reference type.
14578 if (Type->isReferenceType()) {
14579 Diag(Loc: Var->getLocation(), DiagID: diag::err_reference_var_requires_init)
14580 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14581 return;
14582 }
14583
14584 // Do not attempt to type-check the default initializer for a
14585 // variable with dependent type.
14586 if (Type->isDependentType())
14587 return;
14588
14589 if (Var->isInvalidDecl())
14590 return;
14591
14592 if (!Var->hasAttr<AliasAttr>()) {
14593 if (RequireCompleteType(Loc: Var->getLocation(),
14594 T: Context.getBaseElementType(QT: Type),
14595 DiagID: diag::err_typecheck_decl_incomplete_type)) {
14596 Var->setInvalidDecl();
14597 return;
14598 }
14599 } else {
14600 return;
14601 }
14602
14603 // The variable can not have an abstract class type.
14604 if (RequireNonAbstractType(Loc: Var->getLocation(), T: Type,
14605 DiagID: diag::err_abstract_type_in_decl,
14606 Args: AbstractVariableType)) {
14607 Var->setInvalidDecl();
14608 return;
14609 }
14610
14611 // In C, if the definition is const-qualified and has no initializer, it
14612 // is left uninitialized unless it has static or thread storage duration.
14613 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14614 unsigned DiagID = diag::warn_default_init_const_unsafe;
14615 if (Var->getStorageDuration() == SD_Static ||
14616 Var->getStorageDuration() == SD_Thread)
14617 DiagID = diag::warn_default_init_const;
14618
14619 bool EmitCppCompat = !Diags.isIgnored(
14620 DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14621 Loc: Var->getLocation());
14622
14623 Diag(Loc: Var->getLocation(), DiagID) << Type << EmitCppCompat;
14624 }
14625
14626 // Check for jumps past the implicit initializer. C++0x
14627 // clarifies that this applies to a "variable with automatic
14628 // storage duration", not a "local variable".
14629 // C++11 [stmt.dcl]p3
14630 // A program that jumps from a point where a variable with automatic
14631 // storage duration is not in scope to a point where it is in scope is
14632 // ill-formed unless the variable has scalar type, class type with a
14633 // trivial default constructor and a trivial destructor, a cv-qualified
14634 // version of one of these types, or an array of one of the preceding
14635 // types and is declared without an initializer.
14636 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14637 if (const auto *CXXRecord =
14638 Context.getBaseElementType(QT: Type)->getAsCXXRecordDecl()) {
14639 // Mark the function (if we're in one) for further checking even if the
14640 // looser rules of C++11 do not require such checks, so that we can
14641 // diagnose incompatibilities with C++98.
14642 if (!CXXRecord->isPOD())
14643 setFunctionHasBranchProtectedScope();
14644 }
14645 }
14646 // In OpenCL, we can't initialize objects in the __local address space,
14647 // even implicitly, so don't synthesize an implicit initializer.
14648 if (getLangOpts().OpenCL &&
14649 Var->getType().getAddressSpace() == LangAS::opencl_local)
14650 return;
14651
14652 // Handle HLSL uninitialized decls
14653 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(D: Var))
14654 return;
14655
14656 // HLSL input & push-constant variables are expected to be externally
14657 // initialized, even when marked `static`.
14658 if (getLangOpts().HLSL &&
14659 hlsl::isInitializedByPipeline(AS: Var->getType().getAddressSpace()))
14660 return;
14661
14662 // C++03 [dcl.init]p9:
14663 // If no initializer is specified for an object, and the
14664 // object is of (possibly cv-qualified) non-POD class type (or
14665 // array thereof), the object shall be default-initialized; if
14666 // the object is of const-qualified type, the underlying class
14667 // type shall have a user-declared default
14668 // constructor. Otherwise, if no initializer is specified for
14669 // a non- static object, the object and its subobjects, if
14670 // any, have an indeterminate initial value); if the object
14671 // or any of its subobjects are of const-qualified type, the
14672 // program is ill-formed.
14673 // C++0x [dcl.init]p11:
14674 // If no initializer is specified for an object, the object is
14675 // default-initialized; [...].
14676 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14677 InitializationKind Kind
14678 = InitializationKind::CreateDefault(InitLoc: Var->getLocation());
14679
14680 InitializationSequence InitSeq(*this, Entity, Kind, {});
14681 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: {});
14682
14683 if (Init.get()) {
14684 Var->setInit(MaybeCreateExprWithCleanups(SubExpr: Init.get()));
14685 // This is important for template substitution.
14686 Var->setInitStyle(VarDecl::CallInit);
14687 } else if (Init.isInvalid()) {
14688 // If default-init fails, attach a recovery-expr initializer to track
14689 // that initialization was attempted and failed.
14690 auto RecoveryExpr =
14691 CreateRecoveryExpr(Begin: Var->getLocation(), End: Var->getLocation(), SubExprs: {});
14692 if (RecoveryExpr.get())
14693 Var->setInit(RecoveryExpr.get());
14694 }
14695
14696 CheckCompleteVariableDeclaration(VD: Var);
14697 }
14698}
14699
14700void Sema::ActOnCXXForRangeDecl(Decl *D) {
14701 // If there is no declaration, there was an error parsing it. Ignore it.
14702 if (!D)
14703 return;
14704
14705 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
14706 if (!VD) {
14707 Diag(Loc: D->getLocation(), DiagID: diag::err_for_range_decl_must_be_var);
14708 D->setInvalidDecl();
14709 return;
14710 }
14711
14712 VD->setCXXForRangeDecl(true);
14713
14714 // for-range-declaration cannot be given a storage class specifier.
14715 int Error = -1;
14716 switch (VD->getStorageClass()) {
14717 case SC_None:
14718 break;
14719 case SC_Extern:
14720 Error = 0;
14721 break;
14722 case SC_Static:
14723 Error = 1;
14724 break;
14725 case SC_PrivateExtern:
14726 Error = 2;
14727 break;
14728 case SC_Auto:
14729 Error = 3;
14730 break;
14731 case SC_Register:
14732 Error = 4;
14733 break;
14734 }
14735
14736 // for-range-declaration cannot be given a storage class specifier con't.
14737 switch (VD->getTSCSpec()) {
14738 case TSCS_thread_local:
14739 Error = 6;
14740 break;
14741 case TSCS___thread:
14742 case TSCS__Thread_local:
14743 case TSCS_unspecified:
14744 break;
14745 }
14746
14747 if (Error != -1) {
14748 Diag(Loc: VD->getOuterLocStart(), DiagID: diag::err_for_range_storage_class)
14749 << VD << Error;
14750 D->setInvalidDecl();
14751 }
14752}
14753
14754StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14755 IdentifierInfo *Ident,
14756 ParsedAttributes &Attrs) {
14757 // C++1y [stmt.iter]p1:
14758 // A range-based for statement of the form
14759 // for ( for-range-identifier : for-range-initializer ) statement
14760 // is equivalent to
14761 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14762 DeclSpec DS(Attrs.getPool().getFactory());
14763
14764 const char *PrevSpec;
14765 unsigned DiagID;
14766 DS.SetTypeSpecType(T: DeclSpec::TST_auto, Loc: IdentLoc, PrevSpec, DiagID,
14767 Policy: getPrintingPolicy());
14768
14769 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14770 D.SetIdentifier(Id: Ident, IdLoc: IdentLoc);
14771 D.takeAttributesAppending(attrs&: Attrs);
14772
14773 D.AddTypeInfo(TI: DeclaratorChunk::getReference(TypeQuals: 0, Loc: IdentLoc, /*lvalue*/ false),
14774 EndLoc: IdentLoc);
14775 Decl *Var = ActOnDeclarator(S, D);
14776 cast<VarDecl>(Val: Var)->setCXXForRangeDecl(true);
14777 FinalizeDeclaration(D: Var);
14778 return ActOnDeclStmt(Decl: FinalizeDeclaratorGroup(S, DS, Group: Var), StartLoc: IdentLoc,
14779 EndLoc: Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14780 : IdentLoc);
14781}
14782
14783void Sema::addLifetimeBoundToImplicitThis(CXXMethodDecl *MD) {
14784 if (!MD || lifetimes::implicitObjectParamIsLifetimeBound(FD: MD))
14785 return;
14786 auto *Attr = LifetimeBoundAttr::CreateImplicit(Ctx&: Context, Range: MD->getLocation());
14787 QualType MethodType = MD->getType();
14788 QualType AttributedType =
14789 Context.getAttributedType(attr: Attr, modifiedType: MethodType, equivalentType: MethodType);
14790 TypeLocBuilder TLB;
14791 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14792 TLB.pushFullCopy(L: TSI->getTypeLoc());
14793 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
14794 TyLoc.setAttr(Attr);
14795 MD->setType(AttributedType);
14796 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, T: AttributedType));
14797}
14798
14799void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14800 if (var->isInvalidDecl()) return;
14801
14802 CUDA().MaybeAddConstantAttr(VD: var);
14803
14804 if (getLangOpts().OpenCL) {
14805 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14806 // initialiser
14807 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14808 !var->hasInit()) {
14809 Diag(Loc: var->getLocation(), DiagID: diag::err_opencl_invalid_block_declaration)
14810 << 1 /*Init*/;
14811 var->setInvalidDecl();
14812 return;
14813 }
14814 }
14815
14816 // In Objective-C, don't allow jumps past the implicit initialization of a
14817 // local retaining variable.
14818 if (getLangOpts().ObjC &&
14819 var->hasLocalStorage()) {
14820 switch (var->getType().getObjCLifetime()) {
14821 case Qualifiers::OCL_None:
14822 case Qualifiers::OCL_ExplicitNone:
14823 case Qualifiers::OCL_Autoreleasing:
14824 break;
14825
14826 case Qualifiers::OCL_Weak:
14827 case Qualifiers::OCL_Strong:
14828 setFunctionHasBranchProtectedScope();
14829 break;
14830 }
14831 }
14832
14833 if (var->hasLocalStorage() &&
14834 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14835 setFunctionHasBranchProtectedScope();
14836
14837 // Warn about externally-visible variables being defined without a
14838 // prior declaration. We only want to do this for global
14839 // declarations, but we also specifically need to avoid doing it for
14840 // class members because the linkage of an anonymous class can
14841 // change if it's later given a typedef name.
14842 if (var->isThisDeclarationADefinition() &&
14843 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14844 var->isExternallyVisible() && var->hasLinkage() &&
14845 !var->isInline() && !var->getDescribedVarTemplate() &&
14846 var->getStorageClass() != SC_Register &&
14847 !isa<VarTemplatePartialSpecializationDecl>(Val: var) &&
14848 !isTemplateInstantiation(Kind: var->getTemplateSpecializationKind()) &&
14849 !getDiagnostics().isIgnored(DiagID: diag::warn_missing_variable_declarations,
14850 Loc: var->getLocation())) {
14851 // Find a previous declaration that's not a definition.
14852 VarDecl *prev = var->getPreviousDecl();
14853 while (prev && prev->isThisDeclarationADefinition())
14854 prev = prev->getPreviousDecl();
14855
14856 if (!prev) {
14857 Diag(Loc: var->getLocation(), DiagID: diag::warn_missing_variable_declarations) << var;
14858 Diag(Loc: var->getTypeSpecStartLoc(), DiagID: diag::note_static_for_internal_linkage)
14859 << /* variable */ 0;
14860 }
14861 }
14862
14863 // Cache the result of checking for constant initialization.
14864 std::optional<bool> CacheHasConstInit;
14865 const Expr *CacheCulprit = nullptr;
14866 auto checkConstInit = [&]() mutable {
14867 const Expr *Init = var->getInit();
14868 if (Init->isInstantiationDependent())
14869 return true;
14870
14871 if (!CacheHasConstInit)
14872 CacheHasConstInit = var->getInit()->isConstantInitializer(
14873 Ctx&: Context, ForRef: var->getType()->isReferenceType(), Culprit: &CacheCulprit);
14874 return *CacheHasConstInit;
14875 };
14876
14877 if (var->getTLSKind() == VarDecl::TLS_Static) {
14878 if (var->getType().isDestructedType()) {
14879 // GNU C++98 edits for __thread, [basic.start.term]p3:
14880 // The type of an object with thread storage duration shall not
14881 // have a non-trivial destructor.
14882 Diag(Loc: var->getLocation(), DiagID: diag::err_thread_nontrivial_dtor);
14883 if (getLangOpts().CPlusPlus11)
14884 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14885 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14886 if (!checkConstInit()) {
14887 // GNU C++98 edits for __thread, [basic.start.init]p4:
14888 // An object of thread storage duration shall not require dynamic
14889 // initialization.
14890 // FIXME: Need strict checking here.
14891 Diag(Loc: CacheCulprit->getExprLoc(), DiagID: diag::err_thread_dynamic_init)
14892 << CacheCulprit->getSourceRange();
14893 if (getLangOpts().CPlusPlus11)
14894 Diag(Loc: var->getLocation(), DiagID: diag::note_use_thread_local);
14895 }
14896 }
14897 }
14898
14899
14900 if (!var->getType()->isStructureType() && var->hasInit() &&
14901 isa<InitListExpr>(Val: var->getInit())) {
14902 const auto *ILE = cast<InitListExpr>(Val: var->getInit());
14903 unsigned NumInits = ILE->getNumInits();
14904 if (NumInits > 2)
14905 for (unsigned I = 0; I < NumInits; ++I) {
14906 const auto *Init = ILE->getInit(Init: I);
14907 if (!Init)
14908 break;
14909 const auto *SL = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14910 if (!SL)
14911 break;
14912
14913 unsigned NumConcat = SL->getNumConcatenated();
14914 // Diagnose missing comma in string array initialization.
14915 // Do not warn when all the elements in the initializer are concatenated
14916 // together. Do not warn for macros too.
14917 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14918 bool OnlyOneMissingComma = true;
14919 for (unsigned J = I + 1; J < NumInits; ++J) {
14920 const auto *Init = ILE->getInit(Init: J);
14921 if (!Init)
14922 break;
14923 const auto *SLJ = dyn_cast<StringLiteral>(Val: Init->IgnoreImpCasts());
14924 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14925 OnlyOneMissingComma = false;
14926 break;
14927 }
14928 }
14929
14930 if (OnlyOneMissingComma) {
14931 SmallVector<FixItHint, 1> Hints;
14932 for (unsigned i = 0; i < NumConcat - 1; ++i)
14933 Hints.push_back(Elt: FixItHint::CreateInsertion(
14934 InsertionLoc: PP.getLocForEndOfToken(Loc: SL->getStrTokenLoc(TokNum: i)), Code: ","));
14935
14936 Diag(Loc: SL->getStrTokenLoc(TokNum: 1),
14937 DiagID: diag::warn_concatenated_literal_array_init)
14938 << Hints;
14939 Diag(Loc: SL->getBeginLoc(),
14940 DiagID: diag::note_concatenated_string_literal_silence);
14941 }
14942 // In any case, stop now.
14943 break;
14944 }
14945 }
14946 }
14947
14948
14949 QualType type = var->getType();
14950
14951 if (var->hasAttr<BlocksAttr>())
14952 getCurFunction()->addByrefBlockVar(VD: var);
14953
14954 Expr *Init = var->getInit();
14955 bool GlobalStorage = var->hasGlobalStorage();
14956 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14957 QualType baseType = Context.getBaseElementType(QT: type);
14958 bool HasConstInit = true;
14959
14960 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14961 Diag(Loc: var->getLocation(), DiagID: diag::err_constexpr_var_requires_const_init)
14962 << var;
14963
14964 // Check whether the initializer is sufficiently constant.
14965 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14966 !type->isDependentType() && Init && !Init->isValueDependent() &&
14967 (GlobalStorage || var->isConstexpr() ||
14968 var->mightBeUsableInConstantExpressions(C: Context))) {
14969 // If this variable might have a constant initializer or might be usable in
14970 // constant expressions, check whether or not it actually is now. We can't
14971 // do this lazily, because the result might depend on things that change
14972 // later, such as which constexpr functions happen to be defined.
14973 SmallVector<PartialDiagnosticAt, 8> Notes;
14974 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14975 // Prior to C++11, in contexts where a constant initializer is required,
14976 // the set of valid constant initializers is described by syntactic rules
14977 // in [expr.const]p2-6.
14978 // FIXME: Stricter checking for these rules would be useful for constinit /
14979 // -Wglobal-constructors.
14980 HasConstInit = checkConstInit();
14981
14982 // Compute and cache the constant value, and remember that we have a
14983 // constant initializer.
14984 if (HasConstInit) {
14985 if (var->isStaticDataMember() && !var->isInline() &&
14986 var->getLexicalDeclContext()->isRecord() &&
14987 type->isIntegralOrEnumerationType()) {
14988 // In C++98, in-class initialization for a static data member must
14989 // be an integer constant expression.
14990 if (!Init->isIntegerConstantExpr(Ctx: Context)) {
14991 Diag(Loc: Init->getExprLoc(),
14992 DiagID: diag::ext_in_class_initializer_non_constant)
14993 << Init->getSourceRange();
14994 }
14995 }
14996 (void)var->checkForConstantInitialization(Notes);
14997 Notes.clear();
14998 } else if (CacheCulprit) {
14999 Notes.emplace_back(Args: CacheCulprit->getExprLoc(),
15000 Args: PDiag(DiagID: diag::note_invalid_subexpr_in_const_expr));
15001 Notes.back().second << CacheCulprit->getSourceRange();
15002 }
15003 } else {
15004 // Evaluate the initializer to see if it's a constant initializer.
15005 HasConstInit = var->checkForConstantInitialization(Notes);
15006 }
15007
15008 if (HasConstInit) {
15009 // FIXME: Consider replacing the initializer with a ConstantExpr.
15010 } else if (var->isConstexpr()) {
15011 SourceLocation DiagLoc = var->getLocation();
15012 // If the note doesn't add any useful information other than a source
15013 // location, fold it into the primary diagnostic.
15014 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15015 diag::note_invalid_subexpr_in_const_expr) {
15016 DiagLoc = Notes[0].first;
15017 Notes.clear();
15018 }
15019 Diag(Loc: DiagLoc, DiagID: diag::err_constexpr_var_requires_const_init)
15020 << var << Init->getSourceRange();
15021 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15022 Diag(Loc: Notes[I].first, PD: Notes[I].second);
15023 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15024 auto *Attr = var->getAttr<ConstInitAttr>();
15025 Diag(Loc: var->getLocation(), DiagID: diag::err_require_constant_init_failed)
15026 << Init->getSourceRange();
15027 Diag(Loc: Attr->getLocation(), DiagID: diag::note_declared_required_constant_init_here)
15028 << Attr->getRange() << Attr->isConstinit();
15029 for (auto &it : Notes)
15030 Diag(Loc: it.first, PD: it.second);
15031 } else if (var->isStaticDataMember() && !var->isInline() &&
15032 var->getLexicalDeclContext()->isRecord()) {
15033 Diag(Loc: var->getLocation(), DiagID: diag::err_in_class_initializer_non_constant)
15034 << Init->getSourceRange();
15035 for (auto &it : Notes)
15036 Diag(Loc: it.first, PD: it.second);
15037 var->setInvalidDecl();
15038 } else if (IsGlobal &&
15039 !getDiagnostics().isIgnored(DiagID: diag::warn_global_constructor,
15040 Loc: var->getLocation())) {
15041 // Warn about globals which don't have a constant initializer. Don't
15042 // warn about globals with a non-trivial destructor because we already
15043 // warned about them.
15044 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15045 if (!(RD && !RD->hasTrivialDestructor())) {
15046 // checkConstInit() here permits trivial default initialization even in
15047 // C++11 onwards, where such an initializer is not a constant initializer
15048 // but nonetheless doesn't require a global constructor.
15049 if (!checkConstInit())
15050 Diag(Loc: var->getLocation(), DiagID: diag::warn_global_constructor)
15051 << Init->getSourceRange();
15052 }
15053 }
15054 }
15055
15056 // Apply section attributes and pragmas to global variables.
15057 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15058 !inTemplateInstantiation()) {
15059 PragmaStack<StringLiteral *> *Stack = nullptr;
15060 int SectionFlags = ASTContext::PSF_Read;
15061 bool MSVCEnv =
15062 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15063 std::optional<QualType::NonConstantStorageReason> Reason;
15064 if (HasConstInit &&
15065 !(Reason = var->getType().isNonConstantStorage(Ctx: Context, ExcludeCtor: true, ExcludeDtor: false))) {
15066 Stack = &ConstSegStack;
15067 } else {
15068 SectionFlags |= ASTContext::PSF_Write;
15069 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15070 }
15071 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15072 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15073 SectionFlags |= ASTContext::PSF_Implicit;
15074 UnifySection(SectionName: SA->getName(), SectionFlags, TheDecl: var);
15075 } else if (Stack->CurrentValue) {
15076 if (Stack != &ConstSegStack && MSVCEnv &&
15077 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15078 var->getType().isConstQualified()) {
15079 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15080 NonConstNonReferenceType) &&
15081 "This case should've already been handled elsewhere");
15082 Diag(Loc: var->getLocation(), DiagID: diag::warn_section_msvc_compat)
15083 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15084 ? QualType::NonConstantStorageReason::NonTrivialCtor
15085 : *Reason);
15086 }
15087 SectionFlags |= ASTContext::PSF_Implicit;
15088 auto SectionName = Stack->CurrentValue->getString();
15089 var->addAttr(A: SectionAttr::CreateImplicit(Ctx&: Context, Name: SectionName,
15090 Range: Stack->CurrentPragmaLocation,
15091 S: SectionAttr::Declspec_allocate));
15092 if (UnifySection(SectionName, SectionFlags, TheDecl: var))
15093 var->dropAttr<SectionAttr>();
15094 }
15095
15096 // Apply the init_seg attribute if this has an initializer. If the
15097 // initializer turns out to not be dynamic, we'll end up ignoring this
15098 // attribute.
15099 if (CurInitSeg && var->getInit())
15100 var->addAttr(A: InitSegAttr::CreateImplicit(Ctx&: Context, Section: CurInitSeg->getString(),
15101 Range: CurInitSegLoc));
15102 }
15103
15104 // All the following checks are C++ only.
15105 if (!getLangOpts().CPlusPlus) {
15106 // If this variable must be emitted, add it as an initializer for the
15107 // current module.
15108 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15109 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15110 return;
15111 }
15112
15113 DiagnoseUniqueObjectDuplication(VD: var);
15114
15115 // Require the destructor.
15116 if (!type->isDependentType())
15117 if (auto *RD = baseType->getAsCXXRecordDecl())
15118 FinalizeVarWithDestructor(VD: var, DeclInit: RD);
15119
15120 // If this variable must be emitted, add it as an initializer for the current
15121 // module.
15122 if (Context.DeclMustBeEmitted(D: var) && !ModuleScopes.empty())
15123 Context.addModuleInitializer(M: ModuleScopes.back().Module, Init: var);
15124
15125 // Build the bindings if this is a structured binding declaration.
15126 if (auto *DD = dyn_cast<DecompositionDecl>(Val: var))
15127 CheckCompleteDecompositionDeclaration(DD);
15128}
15129
15130void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
15131 assert(VD->isStaticLocal());
15132
15133 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15134
15135 // Find outermost function when VD is in lambda function.
15136 while (FD && !getDLLAttr(D: FD) &&
15137 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15138 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15139 FD = dyn_cast_or_null<FunctionDecl>(Val: FD->getParentFunctionOrMethod());
15140 }
15141
15142 if (!FD)
15143 return;
15144
15145 // Static locals inherit dll attributes from their function.
15146 if (Attr *A = getDLLAttr(D: FD)) {
15147 auto *NewAttr = cast<InheritableAttr>(Val: A->clone(C&: getASTContext()));
15148 NewAttr->setInherited(true);
15149 VD->addAttr(A: NewAttr);
15150 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15151 auto *NewAttr = DLLExportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15152 NewAttr->setInherited(true);
15153 VD->addAttr(A: NewAttr);
15154
15155 // Export this function to enforce exporting this static variable even
15156 // if it is not used in this compilation unit.
15157 if (!FD->hasAttr<DLLExportAttr>())
15158 FD->addAttr(A: NewAttr);
15159
15160 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15161 auto *NewAttr = DLLImportAttr::CreateImplicit(Ctx&: getASTContext(), CommonInfo: *A);
15162 NewAttr->setInherited(true);
15163 VD->addAttr(A: NewAttr);
15164 }
15165}
15166
15167void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
15168 assert(VD->getTLSKind());
15169
15170 // Perform TLS alignment check here after attributes attached to the variable
15171 // which may affect the alignment have been processed. Only perform the check
15172 // if the target has a maximum TLS alignment (zero means no constraints).
15173 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15174 // Protect the check so that it's not performed on dependent types and
15175 // dependent alignments (we can't determine the alignment in that case).
15176 if (!VD->hasDependentAlignment()) {
15177 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(BitSize: MaxAlign);
15178 if (Context.getDeclAlign(D: VD) > MaxAlignChars) {
15179 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
15180 << (unsigned)Context.getDeclAlign(D: VD).getQuantity() << VD
15181 << (unsigned)MaxAlignChars.getQuantity();
15182 }
15183 }
15184 }
15185}
15186
15187void Sema::FinalizeDeclaration(Decl *ThisDecl) {
15188 // Note that we are no longer parsing the initializer for this declaration.
15189 ParsingInitForAutoVars.erase(Ptr: ThisDecl);
15190
15191 VarDecl *VD = dyn_cast_or_null<VarDecl>(Val: ThisDecl);
15192 if (!VD)
15193 return;
15194
15195 // Emit any deferred warnings for the variable's initializer, even if the
15196 // variable is invalid
15197 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15198
15199 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15200 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
15201 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15202 if (PragmaClangBSSSection.Valid)
15203 VD->addAttr(A: PragmaClangBSSSectionAttr::CreateImplicit(
15204 Ctx&: Context, Name: PragmaClangBSSSection.SectionName,
15205 Range: PragmaClangBSSSection.PragmaLocation));
15206 if (PragmaClangDataSection.Valid)
15207 VD->addAttr(A: PragmaClangDataSectionAttr::CreateImplicit(
15208 Ctx&: Context, Name: PragmaClangDataSection.SectionName,
15209 Range: PragmaClangDataSection.PragmaLocation));
15210 if (PragmaClangRodataSection.Valid)
15211 VD->addAttr(A: PragmaClangRodataSectionAttr::CreateImplicit(
15212 Ctx&: Context, Name: PragmaClangRodataSection.SectionName,
15213 Range: PragmaClangRodataSection.PragmaLocation));
15214 if (PragmaClangRelroSection.Valid)
15215 VD->addAttr(A: PragmaClangRelroSectionAttr::CreateImplicit(
15216 Ctx&: Context, Name: PragmaClangRelroSection.SectionName,
15217 Range: PragmaClangRelroSection.PragmaLocation));
15218 }
15219
15220 if (auto *DD = dyn_cast<DecompositionDecl>(Val: ThisDecl)) {
15221 for (auto *BD : DD->bindings()) {
15222 FinalizeDeclaration(ThisDecl: BD);
15223 }
15224 }
15225
15226 CheckInvalidBuiltinCountedByRef(E: VD->getInit(),
15227 K: BuiltinCountedByRefKind::Initializer);
15228
15229 checkAttributesAfterMerging(S&: *this, ND&: *VD);
15230
15231 if (VD->isStaticLocal())
15232 CheckStaticLocalForDllExport(VD);
15233
15234 if (VD->getTLSKind())
15235 CheckThreadLocalForLargeAlignment(VD);
15236
15237 // Perform check for initializers of device-side global variables.
15238 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15239 // 7.5). We must also apply the same checks to all __shared__
15240 // variables whether they are local or not. CUDA also allows
15241 // constant initializers for __constant__ and __device__ variables.
15242 if (getLangOpts().CUDA)
15243 CUDA().checkAllowedInitializer(VD);
15244
15245 // Grab the dllimport or dllexport attribute off of the VarDecl.
15246 const InheritableAttr *DLLAttr = getDLLAttr(D: VD);
15247
15248 // Imported static data members cannot be defined out-of-line.
15249 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(Val: DLLAttr)) {
15250 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15251 VD->isThisDeclarationADefinition()) {
15252 // We allow definitions of dllimport class template static data members
15253 // with a warning.
15254 CXXRecordDecl *Context =
15255 cast<CXXRecordDecl>(Val: VD->getFirstDecl()->getDeclContext());
15256 bool IsClassTemplateMember =
15257 isa<ClassTemplatePartialSpecializationDecl>(Val: Context) ||
15258 Context->getDescribedClassTemplate();
15259
15260 Diag(Loc: VD->getLocation(),
15261 DiagID: IsClassTemplateMember
15262 ? diag::warn_attribute_dllimport_static_field_definition
15263 : diag::err_attribute_dllimport_static_field_definition);
15264 Diag(Loc: IA->getLocation(), DiagID: diag::note_attribute);
15265 if (!IsClassTemplateMember)
15266 VD->setInvalidDecl();
15267 }
15268 }
15269
15270 // dllimport/dllexport variables cannot be thread local, their TLS index
15271 // isn't exported with the variable.
15272 if (DLLAttr && VD->getTLSKind()) {
15273 auto *F = dyn_cast_or_null<FunctionDecl>(Val: VD->getParentFunctionOrMethod());
15274 if (F && getDLLAttr(D: F)) {
15275 assert(VD->isStaticLocal());
15276 // But if this is a static local in a dlimport/dllexport function, the
15277 // function will never be inlined, which means the var would never be
15278 // imported, so having it marked import/export is safe.
15279 } else {
15280 Diag(Loc: VD->getLocation(), DiagID: diag::err_attribute_dll_thread_local) << VD
15281 << DLLAttr;
15282 VD->setInvalidDecl();
15283 }
15284 }
15285
15286 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15287 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15288 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15289 << Attr;
15290 VD->dropAttr<UsedAttr>();
15291 }
15292 }
15293 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15294 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15295 Diag(Loc: Attr->getLocation(), DiagID: diag::warn_attribute_ignored_on_non_definition)
15296 << Attr;
15297 VD->dropAttr<RetainAttr>();
15298 }
15299 }
15300
15301 const DeclContext *DC = VD->getDeclContext();
15302 // If there's a #pragma GCC visibility in scope, and this isn't a class
15303 // member, set the visibility of this variable.
15304 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
15305 AddPushedVisibilityAttribute(RD: VD);
15306
15307 // FIXME: Warn on unused var template partial specializations.
15308 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(Val: VD))
15309 MarkUnusedFileScopedDecl(D: VD);
15310
15311 // Now we have parsed the initializer and can update the table of magic
15312 // tag values.
15313 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15314 !VD->getType()->isIntegralOrEnumerationType())
15315 return;
15316
15317 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15318 const Expr *MagicValueExpr = VD->getInit();
15319 if (!MagicValueExpr) {
15320 continue;
15321 }
15322 std::optional<llvm::APSInt> MagicValueInt;
15323 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Ctx: Context))) {
15324 Diag(Loc: I->getRange().getBegin(),
15325 DiagID: diag::err_type_tag_for_datatype_not_ice)
15326 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15327 continue;
15328 }
15329 if (MagicValueInt->getActiveBits() > 64) {
15330 Diag(Loc: I->getRange().getBegin(),
15331 DiagID: diag::err_type_tag_for_datatype_too_large)
15332 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15333 continue;
15334 }
15335 uint64_t MagicValue = MagicValueInt->getZExtValue();
15336 RegisterTypeTagForDatatype(ArgumentKind: I->getArgumentKind(),
15337 MagicValue,
15338 Type: I->getMatchingCType(),
15339 LayoutCompatible: I->getLayoutCompatible(),
15340 MustBeNull: I->getMustBeNull());
15341 }
15342}
15343
15344static bool hasDeducedAuto(DeclaratorDecl *DD) {
15345 auto *VD = dyn_cast<VarDecl>(Val: DD);
15346 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15347}
15348
15349Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
15350 ArrayRef<Decl *> Group) {
15351 SmallVector<Decl*, 8> Decls;
15352
15353 if (DS.isTypeSpecOwned())
15354 Decls.push_back(Elt: DS.getRepAsDecl());
15355
15356 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15357 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15358 bool DiagnosedMultipleDecomps = false;
15359 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15360 bool DiagnosedNonDeducedAuto = false;
15361
15362 for (Decl *D : Group) {
15363 if (!D)
15364 continue;
15365 // Check if the Decl has been declared in '#pragma omp declare target'
15366 // directive and has static storage duration.
15367 if (auto *VD = dyn_cast<VarDecl>(Val: D);
15368 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15369 VD->hasGlobalStorage())
15370 OpenMP().ActOnOpenMPDeclareTargetInitializer(D);
15371 // For declarators, there are some additional syntactic-ish checks we need
15372 // to perform.
15373 if (auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
15374 if (!FirstDeclaratorInGroup)
15375 FirstDeclaratorInGroup = DD;
15376 if (!FirstDecompDeclaratorInGroup)
15377 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(Val: D);
15378 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15379 !hasDeducedAuto(DD))
15380 FirstNonDeducedAutoInGroup = DD;
15381
15382 if (FirstDeclaratorInGroup != DD) {
15383 // A decomposition declaration cannot be combined with any other
15384 // declaration in the same group.
15385 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15386 Diag(Loc: FirstDecompDeclaratorInGroup->getLocation(),
15387 DiagID: diag::err_decomp_decl_not_alone)
15388 << FirstDeclaratorInGroup->getSourceRange()
15389 << DD->getSourceRange();
15390 DiagnosedMultipleDecomps = true;
15391 }
15392
15393 // A declarator that uses 'auto' in any way other than to declare a
15394 // variable with a deduced type cannot be combined with any other
15395 // declarator in the same group.
15396 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15397 Diag(Loc: FirstNonDeducedAutoInGroup->getLocation(),
15398 DiagID: diag::err_auto_non_deduced_not_alone)
15399 << FirstNonDeducedAutoInGroup->getType()
15400 ->hasAutoForTrailingReturnType()
15401 << FirstDeclaratorInGroup->getSourceRange()
15402 << DD->getSourceRange();
15403 DiagnosedNonDeducedAuto = true;
15404 }
15405 }
15406 }
15407
15408 Decls.push_back(Elt: D);
15409 }
15410
15411 if (DeclSpec::isDeclRep(T: DS.getTypeSpecType())) {
15412 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl())) {
15413 handleTagNumbering(Tag, TagScope: S);
15414 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15415 getLangOpts().CPlusPlus)
15416 Context.addDeclaratorForUnnamedTagDecl(TD: Tag, DD: FirstDeclaratorInGroup);
15417 }
15418 }
15419
15420 return BuildDeclaratorGroup(Group: Decls);
15421}
15422
15423Sema::DeclGroupPtrTy
15424Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
15425 // C++14 [dcl.spec.auto]p7: (DR1347)
15426 // If the type that replaces the placeholder type is not the same in each
15427 // deduction, the program is ill-formed.
15428 if (Group.size() > 1) {
15429 QualType Deduced;
15430 VarDecl *DeducedDecl = nullptr;
15431 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15432 VarDecl *D = dyn_cast<VarDecl>(Val: Group[i]);
15433 if (!D || D->isInvalidDecl())
15434 break;
15435 DeducedType *DT = D->getType()->getContainedDeducedType();
15436 if (!DT || DT->getDeducedType().isNull())
15437 continue;
15438 if (Deduced.isNull()) {
15439 Deduced = DT->getDeducedType();
15440 DeducedDecl = D;
15441 } else if (!Context.hasSameType(T1: DT->getDeducedType(), T2: Deduced)) {
15442 auto *AT = dyn_cast<AutoType>(Val: DT);
15443 auto Dia = Diag(Loc: D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15444 DiagID: diag::err_auto_different_deductions)
15445 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15446 << DeducedDecl->getDeclName() << DT->getDeducedType()
15447 << D->getDeclName();
15448 if (DeducedDecl->hasInit())
15449 Dia << DeducedDecl->getInit()->getSourceRange();
15450 if (D->getInit())
15451 Dia << D->getInit()->getSourceRange();
15452 D->setInvalidDecl();
15453 break;
15454 }
15455 }
15456 }
15457
15458 ActOnDocumentableDecls(Group);
15459
15460 return DeclGroupPtrTy::make(
15461 P: DeclGroupRef::Create(C&: Context, Decls: Group.data(), NumDecls: Group.size()));
15462}
15463
15464void Sema::ActOnDocumentableDecl(Decl *D) {
15465 ActOnDocumentableDecls(Group: D);
15466}
15467
15468void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
15469 // Don't parse the comment if Doxygen diagnostics are ignored.
15470 if (Group.empty() || !Group[0])
15471 return;
15472
15473 if (Diags.isIgnored(DiagID: diag::warn_doc_param_not_found,
15474 Loc: Group[0]->getLocation()) &&
15475 Diags.isIgnored(DiagID: diag::warn_unknown_comment_command_name,
15476 Loc: Group[0]->getLocation()))
15477 return;
15478
15479 if (Group.size() >= 2) {
15480 // This is a decl group. Normally it will contain only declarations
15481 // produced from declarator list. But in case we have any definitions or
15482 // additional declaration references:
15483 // 'typedef struct S {} S;'
15484 // 'typedef struct S *S;'
15485 // 'struct S *pS;'
15486 // FinalizeDeclaratorGroup adds these as separate declarations.
15487 Decl *MaybeTagDecl = Group[0];
15488 if (MaybeTagDecl && isa<TagDecl>(Val: MaybeTagDecl)) {
15489 Group = Group.slice(N: 1);
15490 }
15491 }
15492
15493 // FIXME: We assume every Decl in the group is in the same file.
15494 // This is false when preprocessor constructs the group from decls in
15495 // different files (e. g. macros or #include).
15496 Context.attachCommentsToJustParsedDecls(Decls: Group, PP: &getPreprocessor());
15497}
15498
15499void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
15500 // Check that there are no default arguments inside the type of this
15501 // parameter.
15502 if (getLangOpts().CPlusPlus)
15503 CheckExtraCXXDefaultArguments(D);
15504
15505 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15506 if (D.getCXXScopeSpec().isSet()) {
15507 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_param_declarator)
15508 << D.getCXXScopeSpec().getRange();
15509 }
15510
15511 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15512 // simple identifier except [...irrelevant cases...].
15513 switch (D.getName().getKind()) {
15514 case UnqualifiedIdKind::IK_Identifier:
15515 break;
15516
15517 case UnqualifiedIdKind::IK_OperatorFunctionId:
15518 case UnqualifiedIdKind::IK_ConversionFunctionId:
15519 case UnqualifiedIdKind::IK_LiteralOperatorId:
15520 case UnqualifiedIdKind::IK_ConstructorName:
15521 case UnqualifiedIdKind::IK_DestructorName:
15522 case UnqualifiedIdKind::IK_ImplicitSelfParam:
15523 case UnqualifiedIdKind::IK_DeductionGuideName:
15524 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name)
15525 << GetNameForDeclarator(D).getName();
15526 break;
15527
15528 case UnqualifiedIdKind::IK_TemplateId:
15529 case UnqualifiedIdKind::IK_ConstructorTemplateId:
15530 // GetNameForDeclarator would not produce a useful name in this case.
15531 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_bad_parameter_name_template_id);
15532 break;
15533 }
15534}
15535
15536void Sema::warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D) {
15537 // This only matters in C.
15538 if (getLangOpts().CPlusPlus)
15539 return;
15540
15541 // This only matters if the declaration has a type.
15542 const auto *VD = dyn_cast<ValueDecl>(Val: D);
15543 if (!VD)
15544 return;
15545
15546 // Get the type, this only matters for tag types.
15547 QualType QT = VD->getType();
15548 const auto *TD = QT->getAsTagDecl();
15549 if (!TD)
15550 return;
15551
15552 // Check if the tag declaration is lexically declared somewhere different
15553 // from the lexical declaration of the given object, then it will be hidden
15554 // in C++ and we should warn on it.
15555 if (!TD->getLexicalParent()->LexicallyEncloses(DC: D->getLexicalDeclContext())) {
15556 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15557 Diag(Loc: D->getLocation(), DiagID: diag::warn_decl_hidden_in_cpp) << Kind;
15558 Diag(Loc: TD->getLocation(), DiagID: diag::note_declared_at);
15559 }
15560}
15561
15562static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
15563 SourceLocation ExplicitThisLoc) {
15564 if (!ExplicitThisLoc.isValid())
15565 return;
15566 assert(S.getLangOpts().CPlusPlus &&
15567 "explicit parameter in non-cplusplus mode");
15568 if (!S.getLangOpts().CPlusPlus23)
15569 S.Diag(Loc: ExplicitThisLoc, DiagID: diag::err_cxx20_deducing_this)
15570 << P->getSourceRange();
15571
15572 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15573 // parameter pack.
15574 if (P->isParameterPack()) {
15575 S.Diag(Loc: P->getBeginLoc(), DiagID: diag::err_explicit_object_parameter_pack)
15576 << P->getSourceRange();
15577 return;
15578 }
15579 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15580 if (LambdaScopeInfo *LSI = S.getCurLambda())
15581 LSI->ExplicitObjectParameter = P;
15582}
15583
15584Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15585 SourceLocation ExplicitThisLoc) {
15586 const DeclSpec &DS = D.getDeclSpec();
15587
15588 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15589 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15590 // except for the special case of a single unnamed parameter of type void
15591 // with no storage class specifier, no type qualifier, and no following
15592 // ellipsis terminator.
15593 // Clang applies the C2y rules for 'register void' in all C language modes,
15594 // same as GCC, because it's questionable what that could possibly mean.
15595
15596 // C++03 [dcl.stc]p2 also permits 'auto'.
15597 StorageClass SC = SC_None;
15598 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15599 SC = SC_Register;
15600 // In C++11, the 'register' storage class specifier is deprecated.
15601 // In C++17, it is not allowed, but we tolerate it as an extension.
15602 if (getLangOpts().CPlusPlus11) {
15603 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: getLangOpts().CPlusPlus17
15604 ? diag::ext_register_storage_class
15605 : diag::warn_deprecated_register)
15606 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15607 } else if (!getLangOpts().CPlusPlus &&
15608 DS.getTypeSpecType() == DeclSpec::TST_void &&
15609 D.getNumTypeObjects() == 0) {
15610 Diag(Loc: DS.getStorageClassSpecLoc(),
15611 DiagID: diag::err_invalid_storage_class_in_func_decl)
15612 << FixItHint::CreateRemoval(RemoveRange: DS.getStorageClassSpecLoc());
15613 D.getMutableDeclSpec().ClearStorageClassSpecs();
15614 }
15615 } else if (getLangOpts().CPlusPlus &&
15616 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15617 SC = SC_Auto;
15618 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15619 Diag(Loc: DS.getStorageClassSpecLoc(),
15620 DiagID: diag::err_invalid_storage_class_in_func_decl);
15621 D.getMutableDeclSpec().ClearStorageClassSpecs();
15622 }
15623
15624 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15625 Diag(Loc: DS.getThreadStorageClassSpecLoc(), DiagID: diag::err_invalid_thread)
15626 << DeclSpec::getSpecifierName(S: TSCS);
15627 if (DS.isInlineSpecified())
15628 Diag(Loc: DS.getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
15629 << getLangOpts().CPlusPlus17;
15630 if (DS.hasConstexprSpecifier())
15631 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr)
15632 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15633
15634 DiagnoseFunctionSpecifiers(DS);
15635
15636 CheckFunctionOrTemplateParamDeclarator(S, D);
15637
15638 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
15639 QualType parmDeclType = TInfo->getType();
15640
15641 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15642 const IdentifierInfo *II = D.getIdentifier();
15643 if (II) {
15644 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15645 RedeclarationKind::ForVisibleRedeclaration);
15646 LookupName(R, S);
15647 if (!R.empty()) {
15648 NamedDecl *PrevDecl = *R.begin();
15649 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15650 // Maybe we will complain about the shadowed template parameter.
15651 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
15652 // Just pretend that we didn't see the previous declaration.
15653 PrevDecl = nullptr;
15654 }
15655 if (PrevDecl && S->isDeclScope(D: PrevDecl)) {
15656 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_param_redefinition) << II;
15657 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
15658 // Recover by removing the name
15659 II = nullptr;
15660 D.SetIdentifier(Id: nullptr, IdLoc: D.getIdentifierLoc());
15661 D.setInvalidType(true);
15662 }
15663 }
15664 }
15665
15666 // Incomplete resource arrays are not allowed as function parameters in HLSL
15667 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15668 parmDeclType->isHLSLResourceRecordArray()) {
15669 Diag(Loc: D.getIdentifierLoc(),
15670 DiagID: diag::err_hlsl_incomplete_resource_array_in_function_param);
15671 D.setInvalidType(true);
15672 }
15673
15674 // Temporarily put parameter variables in the translation unit, not
15675 // the enclosing context. This prevents them from accidentally
15676 // looking like class members in C++.
15677 ParmVarDecl *New =
15678 CheckParameter(DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
15679 NameLoc: D.getIdentifierLoc(), Name: II, T: parmDeclType, TSInfo: TInfo, SC);
15680
15681 if (D.isInvalidType())
15682 New->setInvalidDecl();
15683
15684 CheckExplicitObjectParameter(S&: *this, P: New, ExplicitThisLoc);
15685
15686 assert(S->isFunctionPrototypeScope());
15687 assert(S->getFunctionPrototypeDepth() >= 1);
15688 New->setScopeInfo(scopeDepth: S->getFunctionPrototypeDepth() - 1,
15689 parameterIndex: S->getNextFunctionPrototypeIndex());
15690
15691 warnOnCTypeHiddenInCPlusPlus(D: New);
15692
15693 // Add the parameter declaration into this scope.
15694 S->AddDecl(D: New);
15695 if (II)
15696 IdResolver.AddDecl(D: New);
15697
15698 ProcessDeclAttributes(S, D: New, PD: D);
15699
15700 if (D.getDeclSpec().isModulePrivateSpecified())
15701 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_local)
15702 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15703 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
15704
15705 if (New->hasAttr<BlocksAttr>()) {
15706 Diag(Loc: New->getLocation(), DiagID: diag::err_block_on_nonlocal);
15707 }
15708
15709 if (getLangOpts().OpenCL)
15710 deduceOpenCLAddressSpace(Var: New);
15711
15712 return New;
15713}
15714
15715ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15716 SourceLocation Loc,
15717 QualType T) {
15718 /* FIXME: setting StartLoc == Loc.
15719 Would it be worth to modify callers so as to provide proper source
15720 location for the unnamed parameters, embedding the parameter's type? */
15721 ParmVarDecl *Param = ParmVarDecl::Create(C&: Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
15722 T, TInfo: Context.getTrivialTypeSourceInfo(T, Loc),
15723 S: SC_None, DefArg: nullptr);
15724 Param->setImplicit();
15725 return Param;
15726}
15727
15728void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15729 // Don't diagnose unused-parameter errors in template instantiations; we
15730 // will already have done so in the template itself.
15731 if (inTemplateInstantiation())
15732 return;
15733
15734 for (const ParmVarDecl *Parameter : Parameters) {
15735 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15736 !Parameter->hasAttr<UnusedAttr>() &&
15737 !Parameter->getIdentifier()->isPlaceholder()) {
15738 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_unused_parameter)
15739 << Parameter->getDeclName();
15740 }
15741 }
15742}
15743
15744void Sema::DiagnoseSizeOfParametersAndReturnValue(
15745 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15746 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15747 return;
15748
15749 // Warn if the return value is pass-by-value and larger than the specified
15750 // threshold.
15751 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15752 unsigned Size = Context.getTypeSizeInChars(T: ReturnTy).getQuantity();
15753 if (Size > LangOpts.NumLargeByValueCopy)
15754 Diag(Loc: D->getLocation(), DiagID: diag::warn_return_value_size) << D << Size;
15755 }
15756
15757 // Warn if any parameter is pass-by-value and larger than the specified
15758 // threshold.
15759 for (const ParmVarDecl *Parameter : Parameters) {
15760 QualType T = Parameter->getType();
15761 if (T->isDependentType() || !T.isPODType(Context))
15762 continue;
15763 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15764 if (Size > LangOpts.NumLargeByValueCopy)
15765 Diag(Loc: Parameter->getLocation(), DiagID: diag::warn_parameter_size)
15766 << Parameter << Size;
15767 }
15768}
15769
15770ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15771 SourceLocation NameLoc,
15772 const IdentifierInfo *Name, QualType T,
15773 TypeSourceInfo *TSInfo, StorageClass SC) {
15774 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15775 if (getLangOpts().ObjCAutoRefCount &&
15776 T.getObjCLifetime() == Qualifiers::OCL_None &&
15777 T->isObjCLifetimeType()) {
15778
15779 Qualifiers::ObjCLifetime lifetime;
15780
15781 // Special cases for arrays:
15782 // - if it's const, use __unsafe_unretained
15783 // - otherwise, it's an error
15784 if (T->isArrayType()) {
15785 if (!T.isConstQualified()) {
15786 if (DelayedDiagnostics.shouldDelayDiagnostics())
15787 DelayedDiagnostics.add(
15788 diag: sema::DelayedDiagnostic::makeForbiddenType(
15789 loc: NameLoc, diagnostic: diag::err_arc_array_param_no_ownership, type: T, argument: false));
15790 else
15791 Diag(Loc: NameLoc, DiagID: diag::err_arc_array_param_no_ownership)
15792 << TSInfo->getTypeLoc().getSourceRange();
15793 }
15794 lifetime = Qualifiers::OCL_ExplicitNone;
15795 } else {
15796 lifetime = T->getObjCARCImplicitLifetime();
15797 }
15798 T = Context.getLifetimeQualifiedType(type: T, lifetime);
15799 }
15800
15801 ParmVarDecl *New = ParmVarDecl::Create(C&: Context, DC, StartLoc, IdLoc: NameLoc, Id: Name,
15802 T: Context.getAdjustedParameterType(T),
15803 TInfo: TSInfo, S: SC, DefArg: nullptr);
15804
15805 // Make a note if we created a new pack in the scope of a lambda, so that
15806 // we know that references to that pack must also be expanded within the
15807 // lambda scope.
15808 if (New->isParameterPack())
15809 if (auto *CSI = getEnclosingLambdaOrBlock())
15810 CSI->LocalPacks.push_back(Elt: New);
15811
15812 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15813 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15814 checkNonTrivialCUnion(QT: New->getType(), Loc: New->getLocation(),
15815 UseContext: NonTrivialCUnionContext::FunctionParam,
15816 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
15817
15818 // Parameter declarators cannot be interface types. All ObjC objects are
15819 // passed by reference.
15820 if (T->isObjCObjectType()) {
15821 SourceLocation TypeEndLoc =
15822 getLocForEndOfToken(Loc: TSInfo->getTypeLoc().getEndLoc());
15823 Diag(Loc: NameLoc,
15824 DiagID: diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15825 << FixItHint::CreateInsertion(InsertionLoc: TypeEndLoc, Code: "*");
15826 T = Context.getObjCObjectPointerType(OIT: T);
15827 New->setType(T);
15828 }
15829
15830 // __ptrauth is forbidden on parameters.
15831 if (T.getPointerAuth()) {
15832 Diag(Loc: NameLoc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
15833 New->setInvalidDecl();
15834 }
15835
15836 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15837 // duration shall not be qualified by an address-space qualifier."
15838 // Since all parameters have automatic store duration, they can not have
15839 // an address space.
15840 if (T.getAddressSpace() != LangAS::Default &&
15841 // OpenCL allows function arguments declared to be an array of a type
15842 // to be qualified with an address space.
15843 !(getLangOpts().OpenCL &&
15844 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15845 // WebAssembly allows reference types as parameters. Funcref in particular
15846 // lives in a different address space.
15847 !(T->isFunctionPointerType() &&
15848 T.getAddressSpace() == LangAS::wasm_funcref)) {
15849 Diag(Loc: NameLoc, DiagID: diag::err_arg_with_address_space);
15850 New->setInvalidDecl();
15851 }
15852
15853 // PPC MMA non-pointer types are not allowed as function argument types.
15854 if (Context.getTargetInfo().getTriple().isPPC64() &&
15855 PPC().CheckPPCMMAType(Type: New->getOriginalType(), TypeLoc: New->getLocation())) {
15856 New->setInvalidDecl();
15857 }
15858
15859 return New;
15860}
15861
15862void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15863 SourceLocation LocAfterDecls) {
15864 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15865
15866 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15867 // in the declaration list shall have at least one declarator, those
15868 // declarators shall only declare identifiers from the identifier list, and
15869 // every identifier in the identifier list shall be declared.
15870 //
15871 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15872 // identifiers it names shall be declared in the declaration list."
15873 //
15874 // This is why we only diagnose in C99 and later. Note, the other conditions
15875 // listed are checked elsewhere.
15876 if (!FTI.hasPrototype) {
15877 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15878 --i;
15879 if (FTI.Params[i].Param == nullptr) {
15880 if (getLangOpts().C99) {
15881 SmallString<256> Code;
15882 llvm::raw_svector_ostream(Code)
15883 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15884 Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::ext_param_not_declared)
15885 << FTI.Params[i].Ident
15886 << FixItHint::CreateInsertion(InsertionLoc: LocAfterDecls, Code);
15887 }
15888
15889 // Implicitly declare the argument as type 'int' for lack of a better
15890 // type.
15891 AttributeFactory attrs;
15892 DeclSpec DS(attrs);
15893 const char* PrevSpec; // unused
15894 unsigned DiagID; // unused
15895 DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc: FTI.Params[i].IdentLoc, PrevSpec,
15896 DiagID, Policy: Context.getPrintingPolicy());
15897 // Use the identifier location for the type source range.
15898 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15899 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15900 Declarator ParamD(DS, ParsedAttributesView::none(),
15901 DeclaratorContext::KNRTypeList);
15902 ParamD.SetIdentifier(Id: FTI.Params[i].Ident, IdLoc: FTI.Params[i].IdentLoc);
15903 FTI.Params[i].Param = ActOnParamDeclarator(S, D&: ParamD);
15904 }
15905 }
15906 }
15907}
15908
15909Decl *
15910Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15911 MultiTemplateParamsArg TemplateParameterLists,
15912 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15913 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15914 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15915 Scope *ParentScope = FnBodyScope->getParent();
15916
15917 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15918 // we define a non-templated function definition, we will create a declaration
15919 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15920 // The base function declaration will have the equivalent of an `omp declare
15921 // variant` annotation which specifies the mangled definition as a
15922 // specialization function under the OpenMP context defined as part of the
15923 // `omp begin declare variant`.
15924 SmallVector<FunctionDecl *, 4> Bases;
15925 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15926 OpenMP().ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15927 S: ParentScope, D, TemplateParameterLists, Bases);
15928
15929 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15930 Decl *DP = HandleDeclarator(S: ParentScope, D, TemplateParamLists: TemplateParameterLists);
15931 Decl *Dcl = ActOnStartOfFunctionDef(S: FnBodyScope, D: DP, SkipBody, BodyKind);
15932
15933 if (!Bases.empty())
15934 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(D: Dcl,
15935 Bases);
15936
15937 return Dcl;
15938}
15939
15940void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15941 Consumer.HandleInlineFunctionDefinition(D);
15942}
15943
15944static bool FindPossiblePrototype(const FunctionDecl *FD,
15945 const FunctionDecl *&PossiblePrototype) {
15946 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15947 Prev = Prev->getPreviousDecl()) {
15948 // Ignore any declarations that occur in function or method
15949 // scope, because they aren't visible from the header.
15950 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15951 continue;
15952
15953 PossiblePrototype = Prev;
15954 return Prev->getType()->isFunctionProtoType();
15955 }
15956 return false;
15957}
15958
15959static bool
15960ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15961 const FunctionDecl *&PossiblePrototype) {
15962 // Don't warn about invalid declarations.
15963 if (FD->isInvalidDecl())
15964 return false;
15965
15966 // Or declarations that aren't global.
15967 if (!FD->isGlobal())
15968 return false;
15969
15970 // Don't warn about C++ member functions.
15971 if (isa<CXXMethodDecl>(Val: FD))
15972 return false;
15973
15974 // Don't warn about 'main'.
15975 if (isa<TranslationUnitDecl>(Val: FD->getDeclContext()->getRedeclContext()))
15976 if (IdentifierInfo *II = FD->getIdentifier())
15977 if (II->isStr(Str: "main") || II->isStr(Str: "efi_main"))
15978 return false;
15979
15980 if (FD->isMSVCRTEntryPoint())
15981 return false;
15982
15983 // Don't warn about inline functions.
15984 if (FD->isInlined())
15985 return false;
15986
15987 // Don't warn about function templates.
15988 if (FD->getDescribedFunctionTemplate())
15989 return false;
15990
15991 // Don't warn about function template specializations.
15992 if (FD->isFunctionTemplateSpecialization())
15993 return false;
15994
15995 // Don't warn for OpenCL kernels.
15996 if (FD->hasAttr<DeviceKernelAttr>())
15997 return false;
15998
15999 // Don't warn on explicitly deleted functions.
16000 if (FD->isDeleted())
16001 return false;
16002
16003 // Don't warn on implicitly local functions (such as having local-typed
16004 // parameters).
16005 if (!FD->isExternallyVisible())
16006 return false;
16007
16008 // If we were able to find a potential prototype, don't warn.
16009 if (FindPossiblePrototype(FD, PossiblePrototype))
16010 return false;
16011
16012 return true;
16013}
16014
16015void
16016Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
16017 const FunctionDecl *EffectiveDefinition,
16018 SkipBodyInfo *SkipBody) {
16019 const FunctionDecl *Definition = EffectiveDefinition;
16020 if (!Definition &&
16021 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16022 return;
16023
16024 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16025 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16026 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16027 // A merged copy of the same function, instantiated as a member of
16028 // the same class, is OK.
16029 if (declaresSameEntity(D1: OrigFD, D2: OrigDef) &&
16030 declaresSameEntity(D1: cast<Decl>(Val: Definition->getLexicalDeclContext()),
16031 D2: cast<Decl>(Val: FD->getLexicalDeclContext())))
16032 return;
16033 }
16034 }
16035 }
16036
16037 if (canRedefineFunction(FD: Definition, LangOpts: getLangOpts()))
16038 return;
16039
16040 // Don't emit an error when this is redefinition of a typo-corrected
16041 // definition.
16042 if (TypoCorrectedFunctionDefinitions.count(Ptr: Definition))
16043 return;
16044
16045 bool DefinitionVisible = false;
16046 if (SkipBody && isRedefinitionAllowedFor(D: Definition, Visible&: DefinitionVisible) &&
16047 (Definition->getFormalLinkage() == Linkage::Internal ||
16048 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16049 Definition->getNumTemplateParameterLists())) {
16050 SkipBody->ShouldSkip = true;
16051 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16052 if (!DefinitionVisible) {
16053 if (auto *TD = Definition->getDescribedFunctionTemplate())
16054 makeMergedDefinitionVisible(ND: TD);
16055 makeMergedDefinitionVisible(ND: const_cast<FunctionDecl *>(Definition));
16056 }
16057 return;
16058 }
16059
16060 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16061 Definition->getStorageClass() == SC_Extern)
16062 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition_extern_inline)
16063 << FD << getLangOpts().CPlusPlus;
16064 else
16065 Diag(Loc: FD->getLocation(), DiagID: diag::err_redefinition) << FD;
16066
16067 Diag(Loc: Definition->getLocation(), DiagID: diag::note_previous_definition);
16068 FD->setInvalidDecl();
16069}
16070
16071LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
16072 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16073
16074 LambdaScopeInfo *LSI = PushLambdaScope();
16075 LSI->CallOperator = CallOperator;
16076 LSI->Lambda = LambdaClass;
16077 LSI->ReturnType = CallOperator->getReturnType();
16078 // When this function is called in situation where the context of the call
16079 // operator is not entered, we set AfterParameterList to false, so that
16080 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16081 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16082 // where we would set the CurContext to the lambda operator before
16083 // substituting into it. In this case the flag needs to be true such that
16084 // tryCaptureVariable can correctly handle potential captures thereof.
16085 LSI->AfterParameterList = CurContext == CallOperator;
16086
16087 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16088 // used at the point of dealing with potential captures.
16089 //
16090 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16091 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16092 // associated. (Technically, we could recover that list from their
16093 // instantiation patterns, but for now, the GLTemplateParameterList seems
16094 // unnecessary in these cases.)
16095 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16096 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16097 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16098
16099 if (LCD == LCD_None)
16100 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
16101 else if (LCD == LCD_ByCopy)
16102 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
16103 else if (LCD == LCD_ByRef)
16104 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
16105 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16106
16107 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
16108 LSI->Mutable = !CallOperator->isConst();
16109 if (CallOperator->isExplicitObjectMemberFunction())
16110 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(i: 0);
16111
16112 // Add the captures to the LSI so they can be noted as already
16113 // captured within tryCaptureVar.
16114 auto I = LambdaClass->field_begin();
16115 for (const auto &C : LambdaClass->captures()) {
16116 if (C.capturesVariable()) {
16117 ValueDecl *VD = C.getCapturedVar();
16118 if (VD->isInitCapture())
16119 CurrentInstantiationScope->InstantiatedLocal(D: VD, Inst: VD);
16120 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16121 LSI->addCapture(Var: VD, /*IsBlock*/isBlock: false, isByref: ByRef,
16122 /*RefersToEnclosingVariableOrCapture*/isNested: true, Loc: C.getLocation(),
16123 /*EllipsisLoc*/C.isPackExpansion()
16124 ? C.getEllipsisLoc() : SourceLocation(),
16125 CaptureType: I->getType(), /*Invalid*/false);
16126
16127 } else if (C.capturesThis()) {
16128 LSI->addThisCapture(/*Nested*/ isNested: false, Loc: C.getLocation(), CaptureType: I->getType(),
16129 ByCopy: C.getCaptureKind() == LCK_StarThis);
16130 } else {
16131 LSI->addVLATypeCapture(Loc: C.getLocation(), VLAType: I->getCapturedVLAType(),
16132 CaptureType: I->getType());
16133 }
16134 ++I;
16135 }
16136 return LSI;
16137}
16138
16139Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
16140 SkipBodyInfo *SkipBody,
16141 FnBodyKind BodyKind) {
16142 if (!D) {
16143 // Parsing the function declaration failed in some way. Push on a fake scope
16144 // anyway so we can try to parse the function body.
16145 PushFunctionScope();
16146 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16147 return D;
16148 }
16149
16150 FunctionDecl *FD = nullptr;
16151
16152 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D))
16153 FD = FunTmpl->getTemplatedDecl();
16154 else
16155 FD = cast<FunctionDecl>(Val: D);
16156
16157 // Do not push if it is a lambda because one is already pushed when building
16158 // the lambda in ActOnStartOfLambdaDefinition().
16159 if (!isLambdaCallOperator(DC: FD))
16160 PushExpressionEvaluationContextForFunction(NewContext: ExprEvalContexts.back().Context,
16161 FD);
16162
16163 // Check for defining attributes before the check for redefinition.
16164 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16165 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 0;
16166 FD->dropAttr<AliasAttr>();
16167 FD->setInvalidDecl();
16168 }
16169 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16170 Diag(Loc: Attr->getLocation(), DiagID: diag::err_alias_is_definition) << FD << 1;
16171 FD->dropAttr<IFuncAttr>();
16172 FD->setInvalidDecl();
16173 }
16174 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16175 if (Context.getTargetInfo().getTriple().isAArch64() &&
16176 !Context.getTargetInfo().hasFeature(Feature: "fmv") &&
16177 !Attr->isDefaultVersion()) {
16178 // If function multi versioning disabled skip parsing function body
16179 // defined with non-default target_version attribute
16180 if (SkipBody)
16181 SkipBody->ShouldSkip = true;
16182 return nullptr;
16183 }
16184 }
16185
16186 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
16187 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16188 Ctor->isDefaultConstructor() &&
16189 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16190 // If this is an MS ABI dllexport default constructor, instantiate any
16191 // default arguments.
16192 InstantiateDefaultCtorDefaultArgs(Ctor);
16193 }
16194 }
16195
16196 // See if this is a redefinition. If 'will have body' (or similar) is already
16197 // set, then these checks were already performed when it was set.
16198 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16199 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
16200 CheckForFunctionRedefinition(FD, EffectiveDefinition: nullptr, SkipBody);
16201
16202 // If we're skipping the body, we're done. Don't enter the scope.
16203 if (SkipBody && SkipBody->ShouldSkip)
16204 return D;
16205 }
16206
16207 // Mark this function as "will have a body eventually". This lets users to
16208 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16209 // this function.
16210 FD->setWillHaveBody();
16211
16212 // If we are instantiating a generic lambda call operator, push
16213 // a LambdaScopeInfo onto the function stack. But use the information
16214 // that's already been calculated (ActOnLambdaExpr) to prime the current
16215 // LambdaScopeInfo.
16216 // When the template operator is being specialized, the LambdaScopeInfo,
16217 // has to be properly restored so that tryCaptureVariable doesn't try
16218 // and capture any new variables. In addition when calculating potential
16219 // captures during transformation of nested lambdas, it is necessary to
16220 // have the LSI properly restored.
16221 if (isGenericLambdaCallOperatorSpecialization(DC: FD)) {
16222 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16223 // instantiated, explicitly specialized.
16224 if (FD->getTemplateSpecializationInfo()
16225 ->isExplicitInstantiationOrSpecialization()) {
16226 Diag(Loc: FD->getLocation(), DiagID: diag::err_lambda_explicit_spec);
16227 FD->setInvalidDecl();
16228 PushFunctionScope();
16229 } else {
16230 assert(inTemplateInstantiation() &&
16231 "There should be an active template instantiation on the stack "
16232 "when instantiating a generic lambda!");
16233 RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: D));
16234 }
16235 } else {
16236 // Enter a new function scope
16237 PushFunctionScope();
16238 }
16239
16240 // Builtin functions cannot be defined.
16241 if (unsigned BuiltinID = FD->getBuiltinID()) {
16242 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
16243 !Context.BuiltinInfo.isPredefinedRuntimeFunction(ID: BuiltinID)) {
16244 Diag(Loc: FD->getLocation(), DiagID: diag::err_builtin_definition) << FD;
16245 FD->setInvalidDecl();
16246 }
16247 }
16248
16249 // The return type of a function definition must be complete (C99 6.9.1p3).
16250 // C++23 [dcl.fct.def.general]/p2
16251 // The type of [...] the return for a function definition
16252 // shall not be a (possibly cv-qualified) class type that is incomplete
16253 // or abstract within the function body unless the function is deleted.
16254 QualType ResultType = FD->getReturnType();
16255 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16256 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16257 (RequireCompleteType(Loc: FD->getLocation(), T: ResultType,
16258 DiagID: diag::err_func_def_incomplete_result) ||
16259 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getReturnType(),
16260 DiagID: diag::err_abstract_type_in_decl,
16261 Args: AbstractReturnType)))
16262 FD->setInvalidDecl();
16263
16264 if (FnBodyScope)
16265 PushDeclContext(S: FnBodyScope, DC: FD);
16266
16267 // Check the validity of our function parameters
16268 if (BodyKind != FnBodyKind::Delete)
16269 CheckParmsForFunctionDef(Parameters: FD->parameters(),
16270 /*CheckParameterNames=*/true);
16271
16272 // Add non-parameter declarations already in the function to the current
16273 // scope.
16274 if (FnBodyScope) {
16275 for (Decl *NPD : FD->decls()) {
16276 auto *NonParmDecl = dyn_cast<NamedDecl>(Val: NPD);
16277 if (!NonParmDecl)
16278 continue;
16279 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16280 "parameters should not be in newly created FD yet");
16281
16282 // If the decl has a name, make it accessible in the current scope.
16283 if (NonParmDecl->getDeclName())
16284 PushOnScopeChains(D: NonParmDecl, S: FnBodyScope, /*AddToContext=*/false);
16285
16286 // Similarly, dive into enums and fish their constants out, making them
16287 // accessible in this scope.
16288 if (auto *ED = dyn_cast<EnumDecl>(Val: NonParmDecl)) {
16289 for (auto *EI : ED->enumerators())
16290 PushOnScopeChains(D: EI, S: FnBodyScope, /*AddToContext=*/false);
16291 }
16292 }
16293 }
16294
16295 // Introduce our parameters into the function scope
16296 for (auto *Param : FD->parameters()) {
16297 Param->setOwningFunction(FD);
16298
16299 // If this has an identifier, add it to the scope stack.
16300 if (Param->getIdentifier() && FnBodyScope) {
16301 CheckShadow(S: FnBodyScope, D: Param);
16302
16303 PushOnScopeChains(D: Param, S: FnBodyScope);
16304 }
16305 }
16306
16307 // C++ [module.import/6]
16308 // ...
16309 // A header unit shall not contain a definition of a non-inline function or
16310 // variable whose name has external linkage.
16311 //
16312 // Deleted and Defaulted functions are implicitly inline (but the
16313 // inline state is not set at this point, so check the BodyKind explicitly).
16314 // We choose to allow weak & selectany definitions, as they are common in
16315 // headers, and have semantics similar to inline definitions which are allowed
16316 // in header units.
16317 // FIXME: Consider an alternate location for the test where the inlined()
16318 // state is complete.
16319 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16320 !FD->isInvalidDecl() && !FD->isInlined() &&
16321 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16322 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16323 !FD->isTemplateInstantiation() &&
16324 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16325 assert(FD->isThisDeclarationADefinition());
16326 Diag(Loc: FD->getLocation(), DiagID: diag::err_extern_def_in_header_unit);
16327 FD->setInvalidDecl();
16328 }
16329
16330 // Ensure that the function's exception specification is instantiated.
16331 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16332 ResolveExceptionSpec(Loc: D->getLocation(), FPT);
16333
16334 // dllimport cannot be applied to non-inline function definitions.
16335 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16336 !FD->isTemplateInstantiation()) {
16337 assert(!FD->hasAttr<DLLExportAttr>());
16338 Diag(Loc: FD->getLocation(), DiagID: diag::err_attribute_dllimport_function_definition);
16339 FD->setInvalidDecl();
16340 return D;
16341 }
16342
16343 // Some function attributes (like OptimizeNoneAttr) need actions before
16344 // parsing body started.
16345 applyFunctionAttributesBeforeParsingBody(FD: D);
16346
16347 // We want to attach documentation to original Decl (which might be
16348 // a function template).
16349 ActOnDocumentableDecl(D);
16350 if (getCurLexicalContext()->isObjCContainer() &&
16351 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16352 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16353 Diag(Loc: FD->getLocation(), DiagID: diag::warn_function_def_in_objc_container);
16354
16355 maybeAddDeclWithEffects(D: FD);
16356
16357 return D;
16358}
16359
16360void Sema::applyFunctionAttributesBeforeParsingBody(Decl *FD) {
16361 if (!FD || FD->isInvalidDecl())
16362 return;
16363 if (auto *TD = dyn_cast<FunctionTemplateDecl>(Val: FD))
16364 FD = TD->getTemplatedDecl();
16365 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16366 FPOptionsOverride FPO;
16367 FPO.setDisallowOptimizations();
16368 CurFPFeatures.applyChanges(FPO);
16369 FpPragmaStack.CurrentValue =
16370 CurFPFeatures.getChangesFrom(Base: FPOptions(LangOpts));
16371 }
16372}
16373
16374void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
16375 ReturnStmt **Returns = Scope->Returns.data();
16376
16377 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16378 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16379 if (!NRVOCandidate->isNRVOVariable()) {
16380 Diag(Loc: Returns[I]->getRetValue()->getExprLoc(),
16381 DiagID: diag::warn_not_eliding_copy_on_return);
16382 Returns[I]->setNRVOCandidate(nullptr);
16383 }
16384 }
16385 }
16386}
16387
16388bool Sema::canDelayFunctionBody(const Declarator &D) {
16389 // We can't delay parsing the body of a constexpr function template (yet).
16390 if (D.getDeclSpec().hasConstexprSpecifier())
16391 return false;
16392
16393 // We can't delay parsing the body of a function template with a deduced
16394 // return type (yet).
16395 if (D.getDeclSpec().hasAutoTypeSpec()) {
16396 // If the placeholder introduces a non-deduced trailing return type,
16397 // we can still delay parsing it.
16398 if (D.getNumTypeObjects()) {
16399 const auto &Outer = D.getTypeObject(i: D.getNumTypeObjects() - 1);
16400 if (Outer.Kind == DeclaratorChunk::Function &&
16401 Outer.Fun.hasTrailingReturnType()) {
16402 QualType Ty = GetTypeFromParser(Ty: Outer.Fun.getTrailingReturnType());
16403 return Ty.isNull() || !Ty->isUndeducedType();
16404 }
16405 }
16406 return false;
16407 }
16408
16409 return true;
16410}
16411
16412bool Sema::canSkipFunctionBody(Decl *D) {
16413 // We cannot skip the body of a function (or function template) which is
16414 // constexpr, since we may need to evaluate its body in order to parse the
16415 // rest of the file.
16416 // We cannot skip the body of a function with an undeduced return type,
16417 // because any callers of that function need to know the type.
16418 if (const FunctionDecl *FD = D->getAsFunction()) {
16419 if (FD->isConstexpr())
16420 return false;
16421 // We can't simply call Type::isUndeducedType here, because inside template
16422 // auto can be deduced to a dependent type, which is not considered
16423 // "undeduced".
16424 if (FD->getReturnType()->getContainedDeducedType())
16425 return false;
16426 }
16427 return Consumer.shouldSkipFunctionBody(D);
16428}
16429
16430Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
16431 if (!Decl)
16432 return nullptr;
16433 if (FunctionDecl *FD = Decl->getAsFunction())
16434 FD->setHasSkippedBody();
16435 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: Decl))
16436 MD->setHasSkippedBody();
16437 return Decl;
16438}
16439
16440/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16441/// body.
16442class ExitFunctionBodyRAII {
16443public:
16444 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16445 ~ExitFunctionBodyRAII() {
16446 if (!IsLambda)
16447 S.PopExpressionEvaluationContext();
16448 }
16449
16450private:
16451 Sema &S;
16452 bool IsLambda = false;
16453};
16454
16455static void diagnoseImplicitlyRetainedSelf(Sema &S) {
16456 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16457
16458 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16459 auto [It, Inserted] = EscapeInfo.try_emplace(Key: BD);
16460 if (!Inserted)
16461 return It->second;
16462
16463 bool R = false;
16464 const BlockDecl *CurBD = BD;
16465
16466 do {
16467 R = !CurBD->doesNotEscape();
16468 if (R)
16469 break;
16470 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16471 } while (CurBD);
16472
16473 return It->second = R;
16474 };
16475
16476 // If the location where 'self' is implicitly retained is inside a escaping
16477 // block, emit a diagnostic.
16478 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16479 S.ImplicitlyRetainedSelfLocs)
16480 if (IsOrNestedInEscapingBlock(P.second))
16481 S.Diag(Loc: P.first, DiagID: diag::warn_implicitly_retains_self)
16482 << FixItHint::CreateInsertion(InsertionLoc: P.first, Code: "self->");
16483}
16484
16485static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16486 return isa<CXXMethodDecl>(Val: FD) && FD->param_empty() &&
16487 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16488}
16489
16490bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) {
16491 return methodHasName(FD, Name: "get_return_object");
16492}
16493
16494bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) {
16495 return FD->isStatic() &&
16496 methodHasName(FD, Name: "get_return_object_on_allocation_failure");
16497}
16498
16499void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
16500 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
16501 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16502 return;
16503 // Allow some_promise_type::get_return_object().
16504 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD))
16505 return;
16506 if (!FD->hasAttr<CoroWrapperAttr>())
16507 Diag(Loc: FD->getLocation(), DiagID: diag::err_coroutine_return_type) << RD;
16508}
16509
16510Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16511 bool RetainFunctionScopeInfo) {
16512 FunctionScopeInfo *FSI = getCurFunction();
16513 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16514
16515 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16516 FD->addAttr(A: StrictFPAttr::CreateImplicit(Ctx&: Context));
16517
16518 SourceLocation AnalysisLoc;
16519 if (Body)
16520 AnalysisLoc = Body->getEndLoc();
16521 else if (FD)
16522 AnalysisLoc = FD->getEndLoc();
16523 sema::AnalysisBasedWarnings::Policy WP =
16524 AnalysisWarnings.getPolicyInEffectAt(Loc: AnalysisLoc);
16525 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16526
16527 // If we skip function body, we can't tell if a function is a coroutine.
16528 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16529 if (FSI->isCoroutine())
16530 CheckCompletedCoroutineBody(FD, Body);
16531 else
16532 CheckCoroutineWrapper(FD);
16533 }
16534
16535 // Diagnose invalid SYCL kernel entry point function declarations
16536 // and build SYCLKernelCallStmts for valid ones.
16537 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16538 SYCLKernelEntryPointAttr *SKEPAttr =
16539 FD->getAttr<SYCLKernelEntryPointAttr>();
16540 if (FD->isDefaulted()) {
16541 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16542 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16543 SKEPAttr->setInvalidAttr();
16544 } else if (FD->isDeleted()) {
16545 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16546 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16547 SKEPAttr->setInvalidAttr();
16548 } else if (FSI->isCoroutine()) {
16549 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16550 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16551 SKEPAttr->setInvalidAttr();
16552 } else if (Body && isa<CXXTryStmt>(Val: Body)) {
16553 Diag(Loc: SKEPAttr->getLocation(), DiagID: diag::err_sycl_entry_point_invalid)
16554 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16555 SKEPAttr->setInvalidAttr();
16556 }
16557
16558 if (Body && !FD->isTemplated() && !SKEPAttr->isInvalidAttr()) {
16559 StmtResult SR =
16560 SYCL().BuildSYCLKernelCallStmt(FD, Body: cast<CompoundStmt>(Val: Body));
16561 if (SR.isInvalid())
16562 return nullptr;
16563 Body = SR.get();
16564 }
16565 }
16566
16567 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16568 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16569 if (FD->isDeletedAsWritten())
16570 Diag(Loc: SEAttr->getLocation(),
16571 DiagID: diag::err_sycl_external_invalid_deleted_function)
16572 << SEAttr;
16573 }
16574
16575 {
16576 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16577 // one is already popped when finishing the lambda in BuildLambdaExpr().
16578 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16579 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(DC: FD));
16580 if (FD) {
16581 // The function body and the DefaultedOrDeletedInfo, if present, use
16582 // the same storage; don't overwrite the latter if the former is null
16583 // (the body is initialised to null anyway, so even if the latter isn't
16584 // present, this would still be a no-op).
16585 if (Body)
16586 FD->setBody(Body);
16587 FD->setWillHaveBody(false);
16588
16589 if (getLangOpts().CPlusPlus14) {
16590 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16591 FD->getReturnType()->isUndeducedType()) {
16592 // For a function with a deduced result type to return void,
16593 // the result type as written must be 'auto' or 'decltype(auto)',
16594 // possibly cv-qualified or constrained, but not ref-qualified.
16595 if (!FD->getReturnType()->getAs<AutoType>()) {
16596 Diag(Loc: dcl->getLocation(), DiagID: diag::err_auto_fn_no_return_but_not_auto)
16597 << FD->getReturnType();
16598 FD->setInvalidDecl();
16599 } else {
16600 // Falling off the end of the function is the same as 'return;'.
16601 Expr *Dummy = nullptr;
16602 if (DeduceFunctionTypeFromReturnExpr(
16603 FD, ReturnLoc: dcl->getLocation(), RetExpr: Dummy,
16604 AT: FD->getReturnType()->getAs<AutoType>()))
16605 FD->setInvalidDecl();
16606 }
16607 }
16608 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(DC: FD)) {
16609 // In C++11, we don't use 'auto' deduction rules for lambda call
16610 // operators because we don't support return type deduction.
16611 auto *LSI = getCurLambda();
16612 if (LSI->HasImplicitReturnType) {
16613 deduceClosureReturnType(CSI&: *LSI);
16614
16615 // C++11 [expr.prim.lambda]p4:
16616 // [...] if there are no return statements in the compound-statement
16617 // [the deduced type is] the type void
16618 QualType RetType =
16619 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16620
16621 // Update the return type to the deduced type.
16622 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16623 FD->setType(Context.getFunctionType(ResultTy: RetType, Args: Proto->getParamTypes(),
16624 EPI: Proto->getExtProtoInfo()));
16625 }
16626 }
16627
16628 // If the function implicitly returns zero (like 'main') or is naked,
16629 // don't complain about missing return statements.
16630 // Clang implicitly returns 0 in C89 mode, but that's considered an
16631 // extension. The check is necessary to ensure the expected extension
16632 // warning is emitted in C89 mode.
16633 if ((FD->hasImplicitReturnZero() &&
16634 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16635 FD->hasAttr<NakedAttr>())
16636 WP.disableCheckFallThrough();
16637
16638 // MSVC permits the use of pure specifier (=0) on function definition,
16639 // defined at class scope, warn about this non-standard construct.
16640 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16641 !FD->isOutOfLine())
16642 Diag(Loc: FD->getLocation(), DiagID: diag::ext_pure_function_definition);
16643
16644 if (!FD->isInvalidDecl()) {
16645 // Don't diagnose unused parameters of defaulted, deleted or naked
16646 // functions.
16647 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16648 !FD->hasAttr<NakedAttr>())
16649 DiagnoseUnusedParameters(Parameters: FD->parameters());
16650 DiagnoseSizeOfParametersAndReturnValue(Parameters: FD->parameters(),
16651 ReturnTy: FD->getReturnType(), D: FD);
16652
16653 // If this is a structor, we need a vtable.
16654 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: FD))
16655 MarkVTableUsed(Loc: FD->getLocation(), Class: Constructor->getParent());
16656 else if (CXXDestructorDecl *Destructor =
16657 dyn_cast<CXXDestructorDecl>(Val: FD))
16658 MarkVTableUsed(Loc: FD->getLocation(), Class: Destructor->getParent());
16659
16660 // Try to apply the named return value optimization. We have to check
16661 // if we can do this here because lambdas keep return statements around
16662 // to deduce an implicit return type.
16663 if (FD->getReturnType()->isRecordType() &&
16664 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
16665 computeNRVO(Body, Scope: FSI);
16666 }
16667
16668 // GNU warning -Wmissing-prototypes:
16669 // Warn if a global function is defined without a previous
16670 // prototype declaration. This warning is issued even if the
16671 // definition itself provides a prototype. The aim is to detect
16672 // global functions that fail to be declared in header files.
16673 const FunctionDecl *PossiblePrototype = nullptr;
16674 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16675 Diag(Loc: FD->getLocation(), DiagID: diag::warn_missing_prototype) << FD;
16676
16677 if (PossiblePrototype) {
16678 // We found a declaration that is not a prototype,
16679 // but that could be a zero-parameter prototype
16680 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16681 TypeLoc TL = TI->getTypeLoc();
16682 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
16683 Diag(Loc: PossiblePrototype->getLocation(),
16684 DiagID: diag::note_declaration_not_a_prototype)
16685 << (FD->getNumParams() != 0)
16686 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
16687 InsertionLoc: FTL.getRParenLoc(), Code: "void")
16688 : FixItHint{});
16689 }
16690 } else {
16691 // Returns true if the token beginning at this Loc is `const`.
16692 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16693 const LangOptions &LangOpts) {
16694 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16695 if (LocInfo.first.isInvalid())
16696 return false;
16697
16698 bool Invalid = false;
16699 StringRef Buffer = SM.getBufferData(FID: LocInfo.first, Invalid: &Invalid);
16700 if (Invalid)
16701 return false;
16702
16703 if (LocInfo.second > Buffer.size())
16704 return false;
16705
16706 const char *LexStart = Buffer.data() + LocInfo.second;
16707 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16708
16709 return StartTok.consume_front(Prefix: "const") &&
16710 (StartTok.empty() || isWhitespace(c: StartTok[0]) ||
16711 StartTok.starts_with(Prefix: "/*") || StartTok.starts_with(Prefix: "//"));
16712 };
16713
16714 auto findBeginLoc = [&]() {
16715 // If the return type has `const` qualifier, we want to insert
16716 // `static` before `const` (and not before the typename).
16717 if ((FD->getReturnType()->isAnyPointerType() &&
16718 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16719 FD->getReturnType().isConstQualified()) {
16720 // But only do this if we can determine where the `const` is.
16721
16722 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16723 getLangOpts()))
16724
16725 return FD->getBeginLoc();
16726 }
16727 return FD->getTypeSpecStartLoc();
16728 };
16729 Diag(Loc: FD->getTypeSpecStartLoc(),
16730 DiagID: diag::note_static_for_internal_linkage)
16731 << /* function */ 1
16732 << (FD->getStorageClass() == SC_None
16733 ? FixItHint::CreateInsertion(InsertionLoc: findBeginLoc(), Code: "static ")
16734 : FixItHint{});
16735 }
16736 }
16737
16738 // We might not have found a prototype because we didn't wish to warn on
16739 // the lack of a missing prototype. Try again without the checks for
16740 // whether we want to warn on the missing prototype.
16741 if (!PossiblePrototype)
16742 (void)FindPossiblePrototype(FD, PossiblePrototype);
16743
16744 // If the function being defined does not have a prototype, then we may
16745 // need to diagnose it as changing behavior in C23 because we now know
16746 // whether the function accepts arguments or not. This only handles the
16747 // case where the definition has no prototype but does have parameters
16748 // and either there is no previous potential prototype, or the previous
16749 // potential prototype also has no actual prototype. This handles cases
16750 // like:
16751 // void f(); void f(a) int a; {}
16752 // void g(a) int a; {}
16753 // See MergeFunctionDecl() for other cases of the behavior change
16754 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16755 // type without a prototype.
16756 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16757 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16758 !PossiblePrototype->isImplicit()))) {
16759 // The function definition has parameters, so this will change behavior
16760 // in C23. If there is a possible prototype, it comes before the
16761 // function definition.
16762 // FIXME: The declaration may have already been diagnosed as being
16763 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16764 // there's no way to test for the "changes behavior" condition in
16765 // SemaType.cpp when forming the declaration's function type. So, we do
16766 // this awkward dance instead.
16767 //
16768 // If we have a possible prototype and it declares a function with a
16769 // prototype, we don't want to diagnose it; if we have a possible
16770 // prototype and it has no prototype, it may have already been
16771 // diagnosed in SemaType.cpp as deprecated depending on whether
16772 // -Wstrict-prototypes is enabled. If we already warned about it being
16773 // deprecated, add a note that it also changes behavior. If we didn't
16774 // warn about it being deprecated (because the diagnostic is not
16775 // enabled), warn now that it is deprecated and changes behavior.
16776
16777 // This K&R C function definition definitely changes behavior in C23,
16778 // so diagnose it.
16779 Diag(Loc: FD->getLocation(), DiagID: diag::warn_non_prototype_changes_behavior)
16780 << /*definition*/ 1 << /* not supported in C23 */ 0;
16781
16782 // If we have a possible prototype for the function which is a user-
16783 // visible declaration, we already tested that it has no prototype.
16784 // This will change behavior in C23. This gets a warning rather than a
16785 // note because it's the same behavior-changing problem as with the
16786 // definition.
16787 if (PossiblePrototype)
16788 Diag(Loc: PossiblePrototype->getLocation(),
16789 DiagID: diag::warn_non_prototype_changes_behavior)
16790 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16791 << /*definition*/ 1;
16792 }
16793
16794 // Warn on CPUDispatch with an actual body.
16795 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16796 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Val: Body))
16797 if (!CmpndBody->body_empty())
16798 Diag(Loc: CmpndBody->body_front()->getBeginLoc(),
16799 DiagID: diag::warn_dispatch_body_ignored);
16800
16801 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
16802 const CXXMethodDecl *KeyFunction;
16803 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16804 MD->isVirtual() &&
16805 (KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent())) &&
16806 MD == KeyFunction->getCanonicalDecl()) {
16807 // Update the key-function state if necessary for this ABI.
16808 if (FD->isInlined() &&
16809 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16810 Context.setNonKeyFunction(MD);
16811
16812 // If the newly-chosen key function is already defined, then we
16813 // need to mark the vtable as used retroactively.
16814 KeyFunction = Context.getCurrentKeyFunction(RD: MD->getParent());
16815 const FunctionDecl *Definition;
16816 if (KeyFunction && KeyFunction->isDefined(Definition))
16817 MarkVTableUsed(Loc: Definition->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16818 } else {
16819 // We just defined they key function; mark the vtable as used.
16820 MarkVTableUsed(Loc: FD->getLocation(), Class: MD->getParent(), DefinitionRequired: true);
16821 }
16822 }
16823 }
16824
16825 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16826 "Function parsing confused");
16827 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Val: dcl)) {
16828 assert(MD == getCurMethodDecl() && "Method parsing confused");
16829 MD->setBody(Body);
16830 if (!MD->isInvalidDecl()) {
16831 DiagnoseSizeOfParametersAndReturnValue(Parameters: MD->parameters(),
16832 ReturnTy: MD->getReturnType(), D: MD);
16833
16834 if (Body)
16835 computeNRVO(Body, Scope: FSI);
16836 }
16837 if (FSI->ObjCShouldCallSuper) {
16838 Diag(Loc: MD->getEndLoc(), DiagID: diag::warn_objc_missing_super_call)
16839 << MD->getSelector().getAsString();
16840 FSI->ObjCShouldCallSuper = false;
16841 }
16842 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16843 const ObjCMethodDecl *InitMethod = nullptr;
16844 bool isDesignated =
16845 MD->isDesignatedInitializerForTheInterface(InitMethod: &InitMethod);
16846 assert(isDesignated && InitMethod);
16847 (void)isDesignated;
16848
16849 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16850 auto IFace = MD->getClassInterface();
16851 if (!IFace)
16852 return false;
16853 auto SuperD = IFace->getSuperClass();
16854 if (!SuperD)
16855 return false;
16856 return SuperD->getIdentifier() ==
16857 ObjC().NSAPIObj->getNSClassId(K: NSAPI::ClassId_NSObject);
16858 };
16859 // Don't issue this warning for unavailable inits or direct subclasses
16860 // of NSObject.
16861 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16862 Diag(Loc: MD->getLocation(),
16863 DiagID: diag::warn_objc_designated_init_missing_super_call);
16864 Diag(Loc: InitMethod->getLocation(),
16865 DiagID: diag::note_objc_designated_init_marked_here);
16866 }
16867 FSI->ObjCWarnForNoDesignatedInitChain = false;
16868 }
16869 if (FSI->ObjCWarnForNoInitDelegation) {
16870 // Don't issue this warning for unavailable inits.
16871 if (!MD->isUnavailable())
16872 Diag(Loc: MD->getLocation(),
16873 DiagID: diag::warn_objc_secondary_init_missing_init_call);
16874 FSI->ObjCWarnForNoInitDelegation = false;
16875 }
16876
16877 diagnoseImplicitlyRetainedSelf(S&: *this);
16878 } else {
16879 // Parsing the function declaration failed in some way. Pop the fake scope
16880 // we pushed on.
16881 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16882 return nullptr;
16883 }
16884
16885 if (Body && FSI->HasPotentialAvailabilityViolations)
16886 DiagnoseUnguardedAvailabilityViolations(FD: dcl);
16887
16888 assert(!FSI->ObjCShouldCallSuper &&
16889 "This should only be set for ObjC methods, which should have been "
16890 "handled in the block above.");
16891
16892 // Verify and clean out per-function state.
16893 if (Body && (!FD || !FD->isDefaulted())) {
16894 // C++ constructors that have function-try-blocks can't have return
16895 // statements in the handlers of that block. (C++ [except.handle]p14)
16896 // Verify this.
16897 if (FD && isa<CXXConstructorDecl>(Val: FD) && isa<CXXTryStmt>(Val: Body))
16898 DiagnoseReturnInConstructorExceptionHandler(TryBlock: cast<CXXTryStmt>(Val: Body));
16899
16900 // Verify that gotos and switch cases don't jump into scopes illegally.
16901 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16902 DiagnoseInvalidJumps(Body);
16903
16904 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: dcl)) {
16905 if (!Destructor->getParent()->isDependentType())
16906 CheckDestructor(Destructor);
16907
16908 MarkBaseAndMemberDestructorsReferenced(Loc: Destructor->getLocation(),
16909 Record: Destructor->getParent());
16910 }
16911
16912 // If any errors have occurred, clear out any temporaries that may have
16913 // been leftover. This ensures that these temporaries won't be picked up
16914 // for deletion in some later function.
16915 if (hasUncompilableErrorOccurred() ||
16916 hasAnyUnrecoverableErrorsInThisFunction() ||
16917 getDiagnostics().getSuppressAllDiagnostics()) {
16918 DiscardCleanupsInEvaluationContext();
16919 }
16920 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(Val: dcl)) {
16921 // Since the body is valid, issue any analysis-based warnings that are
16922 // enabled.
16923 ActivePolicy = &WP;
16924 }
16925
16926 if (!IsInstantiation && FD &&
16927 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16928 !FD->isInvalidDecl() &&
16929 !CheckConstexprFunctionDefinition(FD, Kind: CheckConstexprKind::Diagnose))
16930 FD->setInvalidDecl();
16931
16932 if (FD && FD->hasAttr<NakedAttr>()) {
16933 for (const Stmt *S : Body->children()) {
16934 // Allow local register variables without initializer as they don't
16935 // require prologue.
16936 bool RegisterVariables = false;
16937 if (auto *DS = dyn_cast<DeclStmt>(Val: S)) {
16938 for (const auto *Decl : DS->decls()) {
16939 if (const auto *Var = dyn_cast<VarDecl>(Val: Decl)) {
16940 RegisterVariables =
16941 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16942 if (!RegisterVariables)
16943 break;
16944 }
16945 }
16946 }
16947 if (RegisterVariables)
16948 continue;
16949 if (!isa<AsmStmt>(Val: S) && !isa<NullStmt>(Val: S)) {
16950 Diag(Loc: S->getBeginLoc(), DiagID: diag::err_non_asm_stmt_in_naked_function);
16951 Diag(Loc: FD->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
16952 FD->setInvalidDecl();
16953 break;
16954 }
16955 }
16956 }
16957
16958 assert(ExprCleanupObjects.size() ==
16959 ExprEvalContexts.back().NumCleanupObjects &&
16960 "Leftover temporaries in function");
16961 assert(!Cleanup.exprNeedsCleanups() &&
16962 "Unaccounted cleanups in function");
16963 assert(MaybeODRUseExprs.empty() &&
16964 "Leftover expressions for odr-use checking");
16965 }
16966 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16967 // the declaration context below. Otherwise, we're unable to transform
16968 // 'this' expressions when transforming immediate context functions.
16969
16970 if (FD)
16971 CheckImmediateEscalatingFunctionDefinition(FD, FSI: getCurFunction());
16972
16973 if (!IsInstantiation)
16974 PopDeclContext();
16975
16976 if (!RetainFunctionScopeInfo)
16977 PopFunctionScopeInfo(WP: ActivePolicy, D: dcl);
16978 // If any errors have occurred, clear out any temporaries that may have
16979 // been leftover. This ensures that these temporaries won't be picked up for
16980 // deletion in some later function.
16981 if (hasUncompilableErrorOccurred()) {
16982 DiscardCleanupsInEvaluationContext();
16983 }
16984
16985 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
16986 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
16987 auto ES = getEmissionStatus(Decl: FD);
16988 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16989 ES == Sema::FunctionEmissionStatus::Unknown)
16990 DeclsToCheckForDeferredDiags.insert(X: FD);
16991 }
16992
16993 if (FD && !FD->isDeleted())
16994 checkTypeSupport(Ty: FD->getType(), Loc: FD->getLocation(), D: FD);
16995
16996 return dcl;
16997}
16998
16999/// When we finish delayed parsing of an attribute, we must attach it to the
17000/// relevant Decl.
17001void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
17002 ParsedAttributes &Attrs) {
17003 // Always attach attributes to the underlying decl.
17004 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(Val: D))
17005 D = TD->getTemplatedDecl();
17006 ProcessDeclAttributeList(S, D, AttrList: Attrs);
17007 ProcessAPINotes(D);
17008
17009 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: D))
17010 if (Method->isStatic())
17011 checkThisInStaticMemberFunctionAttributes(Method);
17012}
17013
17014NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
17015 IdentifierInfo &II, Scope *S) {
17016 // It is not valid to implicitly define a function in C23.
17017 assert(LangOpts.implicitFunctionsAllowed() &&
17018 "Implicit function declarations aren't allowed in this language mode");
17019
17020 // Find the scope in which the identifier is injected and the corresponding
17021 // DeclContext.
17022 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17023 // In that case, we inject the declaration into the translation unit scope
17024 // instead.
17025 Scope *BlockScope = S;
17026 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17027 BlockScope = BlockScope->getParent();
17028
17029 // Loop until we find a DeclContext that is either a function/method or the
17030 // translation unit, which are the only two valid places to implicitly define
17031 // a function. This avoids accidentally defining the function within a tag
17032 // declaration, for example.
17033 Scope *ContextScope = BlockScope;
17034 while (!ContextScope->getEntity() ||
17035 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17036 !ContextScope->getEntity()->isTranslationUnit()))
17037 ContextScope = ContextScope->getParent();
17038 ContextRAII SavedContext(*this, ContextScope->getEntity());
17039
17040 // Before we produce a declaration for an implicitly defined
17041 // function, see whether there was a locally-scoped declaration of
17042 // this name as a function or variable. If so, use that
17043 // (non-visible) declaration, and complain about it.
17044 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(Name: &II);
17045 if (ExternCPrev) {
17046 // We still need to inject the function into the enclosing block scope so
17047 // that later (non-call) uses can see it.
17048 PushOnScopeChains(D: ExternCPrev, S: BlockScope, /*AddToContext*/false);
17049
17050 // C89 footnote 38:
17051 // If in fact it is not defined as having type "function returning int",
17052 // the behavior is undefined.
17053 if (!isa<FunctionDecl>(Val: ExternCPrev) ||
17054 !Context.typesAreCompatible(
17055 T1: cast<FunctionDecl>(Val: ExternCPrev)->getType(),
17056 T2: Context.getFunctionNoProtoType(ResultTy: Context.IntTy))) {
17057 Diag(Loc, DiagID: diag::ext_use_out_of_scope_declaration)
17058 << ExternCPrev << !getLangOpts().C99;
17059 Diag(Loc: ExternCPrev->getLocation(), DiagID: diag::note_previous_declaration);
17060 return ExternCPrev;
17061 }
17062 }
17063
17064 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17065 unsigned diag_id;
17066 if (II.getName().starts_with(Prefix: "__builtin_"))
17067 diag_id = diag::warn_builtin_unknown;
17068 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17069 else if (getLangOpts().C99)
17070 diag_id = diag::ext_implicit_function_decl_c99;
17071 else
17072 diag_id = diag::warn_implicit_function_decl;
17073
17074 TypoCorrection Corrected;
17075 // Because typo correction is expensive, only do it if the implicit
17076 // function declaration is going to be treated as an error.
17077 //
17078 // Perform the correction before issuing the main diagnostic, as some
17079 // consumers use typo-correction callbacks to enhance the main diagnostic.
17080 if (S && !ExternCPrev &&
17081 (Diags.getDiagnosticLevel(DiagID: diag_id, Loc) >= DiagnosticsEngine::Error)) {
17082 DeclFilterCCC<FunctionDecl> CCC{};
17083 Corrected = CorrectTypo(Typo: DeclarationNameInfo(&II, Loc), LookupKind: LookupOrdinaryName,
17084 S, SS: nullptr, CCC, Mode: CorrectTypoKind::NonError);
17085 }
17086
17087 Diag(Loc, DiagID: diag_id) << &II;
17088 if (Corrected) {
17089 // If the correction is going to suggest an implicitly defined function,
17090 // skip the correction as not being a particularly good idea.
17091 bool Diagnose = true;
17092 if (const auto *D = Corrected.getCorrectionDecl())
17093 Diagnose = !D->isImplicit();
17094 if (Diagnose)
17095 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::note_function_suggestion),
17096 /*ErrorRecovery*/ false);
17097 }
17098
17099 // If we found a prior declaration of this function, don't bother building
17100 // another one. We've already pushed that one into scope, so there's nothing
17101 // more to do.
17102 if (ExternCPrev)
17103 return ExternCPrev;
17104
17105 // Set a Declarator for the implicit definition: int foo();
17106 const char *Dummy;
17107 AttributeFactory attrFactory;
17108 DeclSpec DS(attrFactory);
17109 unsigned DiagID;
17110 bool Error = DS.SetTypeSpecType(T: DeclSpec::TST_int, Loc, PrevSpec&: Dummy, DiagID,
17111 Policy: Context.getPrintingPolicy());
17112 (void)Error; // Silence warning.
17113 assert(!Error && "Error setting up implicit decl!");
17114 SourceLocation NoLoc;
17115 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
17116 D.AddTypeInfo(TI: DeclaratorChunk::getFunction(/*HasProto=*/false,
17117 /*IsAmbiguous=*/false,
17118 /*LParenLoc=*/NoLoc,
17119 /*Params=*/nullptr,
17120 /*NumParams=*/0,
17121 /*EllipsisLoc=*/NoLoc,
17122 /*RParenLoc=*/NoLoc,
17123 /*RefQualifierIsLvalueRef=*/true,
17124 /*RefQualifierLoc=*/NoLoc,
17125 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
17126 /*ESpecRange=*/SourceRange(),
17127 /*Exceptions=*/nullptr,
17128 /*ExceptionRanges=*/nullptr,
17129 /*NumExceptions=*/0,
17130 /*NoexceptExpr=*/nullptr,
17131 /*ExceptionSpecTokens=*/nullptr,
17132 /*DeclsInPrototype=*/{}, LocalRangeBegin: Loc, LocalRangeEnd: Loc,
17133 TheDeclarator&: D),
17134 attrs: std::move(DS.getAttributes()), EndLoc: SourceLocation());
17135 D.SetIdentifier(Id: &II, IdLoc: Loc);
17136
17137 // Insert this function into the enclosing block scope.
17138 FunctionDecl *FD = cast<FunctionDecl>(Val: ActOnDeclarator(S: BlockScope, D));
17139 FD->setImplicit();
17140
17141 AddKnownFunctionAttributes(FD);
17142
17143 return FD;
17144}
17145
17146void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
17147 FunctionDecl *FD) {
17148 if (FD->isInvalidDecl())
17149 return;
17150
17151 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17152 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17153 return;
17154
17155 UnsignedOrNone AlignmentParam = std::nullopt;
17156 bool IsNothrow = false;
17157 if (!FD->isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam, IsNothrow: &IsNothrow))
17158 return;
17159
17160 // C++2a [basic.stc.dynamic.allocation]p4:
17161 // An allocation function that has a non-throwing exception specification
17162 // indicates failure by returning a null pointer value. Any other allocation
17163 // function never returns a null pointer value and indicates failure only by
17164 // throwing an exception [...]
17165 //
17166 // However, -fcheck-new invalidates this possible assumption, so don't add
17167 // NonNull when that is enabled.
17168 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17169 !getLangOpts().CheckNew)
17170 FD->addAttr(A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17171
17172 // C++2a [basic.stc.dynamic.allocation]p2:
17173 // An allocation function attempts to allocate the requested amount of
17174 // storage. [...] If the request succeeds, the value returned by a
17175 // replaceable allocation function is a [...] pointer value p0 different
17176 // from any previously returned value p1 [...]
17177 //
17178 // However, this particular information is being added in codegen,
17179 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17180
17181 // C++2a [basic.stc.dynamic.allocation]p2:
17182 // An allocation function attempts to allocate the requested amount of
17183 // storage. If it is successful, it returns the address of the start of a
17184 // block of storage whose length in bytes is at least as large as the
17185 // requested size.
17186 if (!FD->hasAttr<AllocSizeAttr>()) {
17187 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17188 Ctx&: Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17189 /*NumElemsParam=*/ParamIdx(), Range: FD->getLocation()));
17190 }
17191
17192 // C++2a [basic.stc.dynamic.allocation]p3:
17193 // For an allocation function [...], the pointer returned on a successful
17194 // call shall represent the address of storage that is aligned as follows:
17195 // (3.1) If the allocation function takes an argument of type
17196 // std​::​align_­val_­t, the storage will have the alignment
17197 // specified by the value of this argument.
17198 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17199 FD->addAttr(A: AllocAlignAttr::CreateImplicit(
17200 Ctx&: Context, ParamIndex: ParamIdx(*AlignmentParam, FD), Range: FD->getLocation()));
17201 }
17202
17203 // FIXME:
17204 // C++2a [basic.stc.dynamic.allocation]p3:
17205 // For an allocation function [...], the pointer returned on a successful
17206 // call shall represent the address of storage that is aligned as follows:
17207 // (3.2) Otherwise, if the allocation function is named operator new[],
17208 // the storage is aligned for any object that does not have
17209 // new-extended alignment ([basic.align]) and is no larger than the
17210 // requested size.
17211 // (3.3) Otherwise, the storage is aligned for any object that does not
17212 // have new-extended alignment and is of the requested size.
17213}
17214
17215void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
17216 if (FD->isInvalidDecl())
17217 return;
17218
17219 // If this is a built-in function, map its builtin attributes to
17220 // actual attributes.
17221 if (unsigned BuiltinID = FD->getBuiltinID()) {
17222 // Handle printf-formatting attributes.
17223 unsigned FormatIdx;
17224 bool HasVAListArg;
17225 if (Context.BuiltinInfo.isPrintfLike(ID: BuiltinID, FormatIdx, HasVAListArg)) {
17226 if (!FD->hasAttr<FormatAttr>()) {
17227 const char *fmt = "printf";
17228 unsigned int NumParams = FD->getNumParams();
17229 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17230 FD->getParamDecl(i: FormatIdx)->getType()->isObjCObjectPointerType())
17231 fmt = "NSString";
17232 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17233 Type: &Context.Idents.get(Name: fmt),
17234 FormatIdx: FormatIdx+1,
17235 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17236 Range: FD->getLocation()));
17237 }
17238 }
17239 if (Context.BuiltinInfo.isScanfLike(ID: BuiltinID, FormatIdx,
17240 HasVAListArg)) {
17241 if (!FD->hasAttr<FormatAttr>())
17242 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17243 Type: &Context.Idents.get(Name: "scanf"),
17244 FormatIdx: FormatIdx+1,
17245 FirstArg: HasVAListArg ? 0 : FormatIdx+2,
17246 Range: FD->getLocation()));
17247 }
17248
17249 // Handle automatically recognized callbacks.
17250 SmallVector<int, 4> Encoding;
17251 if (!FD->hasAttr<CallbackAttr>() &&
17252 Context.BuiltinInfo.performsCallback(ID: BuiltinID, Encoding))
17253 FD->addAttr(A: CallbackAttr::CreateImplicit(
17254 Ctx&: Context, Encoding: Encoding.data(), EncodingSize: Encoding.size(), Range: FD->getLocation()));
17255
17256 // Mark const if we don't care about errno and/or floating point exceptions
17257 // that are the only thing preventing the function from being const. This
17258 // allows IRgen to use LLVM intrinsics for such functions.
17259 bool NoExceptions =
17260 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
17261 bool ConstWithoutErrnoAndExceptions =
17262 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(ID: BuiltinID);
17263 bool ConstWithoutExceptions =
17264 Context.BuiltinInfo.isConstWithoutExceptions(ID: BuiltinID);
17265 if (!FD->hasAttr<ConstAttr>() &&
17266 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17267 (!ConstWithoutErrnoAndExceptions ||
17268 (!getLangOpts().MathErrno && NoExceptions)) &&
17269 (!ConstWithoutExceptions || NoExceptions))
17270 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17271
17272 // We make "fma" on GNU or Windows const because we know it does not set
17273 // errno in those environments even though it could set errno based on the
17274 // C standard.
17275 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17276 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17277 !FD->hasAttr<ConstAttr>()) {
17278 switch (BuiltinID) {
17279 case Builtin::BI__builtin_fma:
17280 case Builtin::BI__builtin_fmaf:
17281 case Builtin::BI__builtin_fmal:
17282 case Builtin::BIfma:
17283 case Builtin::BIfmaf:
17284 case Builtin::BIfmal:
17285 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17286 break;
17287 default:
17288 break;
17289 }
17290 }
17291
17292 SmallVector<int, 4> Indxs;
17293 Builtin::Info::NonNullMode OptMode;
17294 if (Context.BuiltinInfo.isNonNull(ID: BuiltinID, Indxs, Mode&: OptMode) &&
17295 !FD->hasAttr<NonNullAttr>()) {
17296 if (OptMode == Builtin::Info::NonNullMode::NonOptimizing) {
17297 for (int I : Indxs) {
17298 ParmVarDecl *PVD = FD->getParamDecl(i: I);
17299 QualType T = PVD->getType();
17300 T = Context.getAttributedType(attrKind: attr::TypeNonNull, modifiedType: T, equivalentType: T);
17301 PVD->setType(T);
17302 }
17303 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17304 llvm::SmallVector<ParamIdx, 4> ParamIndxs;
17305 for (int I : Indxs)
17306 ParamIndxs.push_back(Elt: ParamIdx(I + 1, FD));
17307 FD->addAttr(A: NonNullAttr::CreateImplicit(Ctx&: Context, Args: ParamIndxs.data(),
17308 ArgsSize: ParamIndxs.size()));
17309 }
17310 }
17311 if (Context.BuiltinInfo.isReturnsTwice(ID: BuiltinID) &&
17312 !FD->hasAttr<ReturnsTwiceAttr>())
17313 FD->addAttr(A: ReturnsTwiceAttr::CreateImplicit(Ctx&: Context,
17314 Range: FD->getLocation()));
17315 if (Context.BuiltinInfo.isNoThrow(ID: BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17316 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17317 if (Context.BuiltinInfo.isPure(ID: BuiltinID) && !FD->hasAttr<PureAttr>())
17318 FD->addAttr(A: PureAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17319 if (Context.BuiltinInfo.isConst(ID: BuiltinID) && !FD->hasAttr<ConstAttr>())
17320 FD->addAttr(A: ConstAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17321 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID) &&
17322 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17323 // Add the appropriate attribute, depending on the CUDA compilation mode
17324 // and which target the builtin belongs to. For example, during host
17325 // compilation, aux builtins are __device__, while the rest are __host__.
17326 if (getLangOpts().CUDAIsDevice !=
17327 Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
17328 FD->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17329 else
17330 FD->addAttr(A: CUDAHostAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17331 }
17332
17333 // Add known guaranteed alignment for allocation functions.
17334 switch (BuiltinID) {
17335 case Builtin::BImemalign:
17336 case Builtin::BIaligned_alloc:
17337 if (!FD->hasAttr<AllocAlignAttr>())
17338 FD->addAttr(A: AllocAlignAttr::CreateImplicit(Ctx&: Context, ParamIndex: ParamIdx(1, FD),
17339 Range: FD->getLocation()));
17340 break;
17341 default:
17342 break;
17343 }
17344
17345 // Add allocsize attribute for allocation functions.
17346 switch (BuiltinID) {
17347 case Builtin::BIcalloc:
17348 FD->addAttr(A: AllocSizeAttr::CreateImplicit(
17349 Ctx&: Context, ElemSizeParam: ParamIdx(1, FD), NumElemsParam: ParamIdx(2, FD), Range: FD->getLocation()));
17350 break;
17351 case Builtin::BImemalign:
17352 case Builtin::BIaligned_alloc:
17353 case Builtin::BIrealloc:
17354 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(2, FD),
17355 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17356 break;
17357 case Builtin::BImalloc:
17358 FD->addAttr(A: AllocSizeAttr::CreateImplicit(Ctx&: Context, ElemSizeParam: ParamIdx(1, FD),
17359 NumElemsParam: ParamIdx(), Range: FD->getLocation()));
17360 break;
17361 default:
17362 break;
17363 }
17364 }
17365
17366 LazyProcessLifetimeCaptureByParams(FD);
17367 inferLifetimeBoundAttribute(FD);
17368 inferLifetimeCaptureByAttribute(FD);
17369 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
17370
17371 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17372 // throw, add an implicit nothrow attribute to any extern "C" function we come
17373 // across.
17374 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17375 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17376 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17377 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17378 FD->addAttr(A: NoThrowAttr::CreateImplicit(Ctx&: Context, Range: FD->getLocation()));
17379 }
17380
17381 IdentifierInfo *Name = FD->getIdentifier();
17382 if (!Name)
17383 return;
17384 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
17385 (isa<LinkageSpecDecl>(Val: FD->getDeclContext()) &&
17386 cast<LinkageSpecDecl>(Val: FD->getDeclContext())->getLanguage() ==
17387 LinkageSpecLanguageIDs::C)) {
17388 // Okay: this could be a libc/libm/Objective-C function we know
17389 // about.
17390 } else
17391 return;
17392
17393 if (Name->isStr(Str: "asprintf") || Name->isStr(Str: "vasprintf")) {
17394 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17395 // target-specific builtins, perhaps?
17396 if (!FD->hasAttr<FormatAttr>())
17397 FD->addAttr(A: FormatAttr::CreateImplicit(Ctx&: Context,
17398 Type: &Context.Idents.get(Name: "printf"), FormatIdx: 2,
17399 FirstArg: Name->isStr(Str: "vasprintf") ? 0 : 3,
17400 Range: FD->getLocation()));
17401 }
17402
17403 if (Name->isStr(Str: "__CFStringMakeConstantString")) {
17404 // We already have a __builtin___CFStringMakeConstantString,
17405 // but builds that use -fno-constant-cfstrings don't go through that.
17406 if (!FD->hasAttr<FormatArgAttr>())
17407 FD->addAttr(A: FormatArgAttr::CreateImplicit(Ctx&: Context, FormatIdx: ParamIdx(1, FD),
17408 Range: FD->getLocation()));
17409 }
17410}
17411
17412TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
17413 TypeSourceInfo *TInfo) {
17414 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17415 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17416
17417 if (!TInfo) {
17418 assert(D.isInvalidType() && "no declarator info for valid type");
17419 TInfo = Context.getTrivialTypeSourceInfo(T);
17420 }
17421
17422 // Scope manipulation handled by caller.
17423 TypedefDecl *NewTD =
17424 TypedefDecl::Create(C&: Context, DC: CurContext, StartLoc: D.getBeginLoc(),
17425 IdLoc: D.getIdentifierLoc(), Id: D.getIdentifier(), TInfo);
17426
17427 // Bail out immediately if we have an invalid declaration.
17428 if (D.isInvalidType()) {
17429 NewTD->setInvalidDecl();
17430 return NewTD;
17431 }
17432
17433 if (D.getDeclSpec().isModulePrivateSpecified()) {
17434 if (CurContext->isFunctionOrMethod())
17435 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_module_private_local)
17436 << 2 << NewTD
17437 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
17438 << FixItHint::CreateRemoval(
17439 RemoveRange: D.getDeclSpec().getModulePrivateSpecLoc());
17440 else
17441 NewTD->setModulePrivate();
17442 }
17443
17444 // C++ [dcl.typedef]p8:
17445 // If the typedef declaration defines an unnamed class (or
17446 // enum), the first typedef-name declared by the declaration
17447 // to be that class type (or enum type) is used to denote the
17448 // class type (or enum type) for linkage purposes only.
17449 // We need to check whether the type was declared in the declaration.
17450 switch (D.getDeclSpec().getTypeSpecType()) {
17451 case TST_enum:
17452 case TST_struct:
17453 case TST_interface:
17454 case TST_union:
17455 case TST_class: {
17456 TagDecl *tagFromDeclSpec = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
17457 setTagNameForLinkagePurposes(TagFromDeclSpec: tagFromDeclSpec, NewTD);
17458 break;
17459 }
17460
17461 default:
17462 break;
17463 }
17464
17465 return NewTD;
17466}
17467
17468bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
17469 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17470 QualType T = TI->getType();
17471
17472 if (T->isDependentType())
17473 return false;
17474
17475 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17476 // integral type; any cv-qualification is ignored.
17477 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17478 // non-atomic version of the type specified by the type specifiers in the
17479 // specifier qualifier list.
17480 // Because of how odd C's rule is, we'll let the user know that operations
17481 // involving the enumeration type will be non-atomic.
17482 if (T->isAtomicType())
17483 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_atomic_stripped_in_enum);
17484
17485 Qualifiers Q = T.getQualifiers();
17486 std::optional<unsigned> QualSelect;
17487 if (Q.hasConst() && Q.hasVolatile())
17488 QualSelect = diag::CVQualList::Both;
17489 else if (Q.hasConst())
17490 QualSelect = diag::CVQualList::Const;
17491 else if (Q.hasVolatile())
17492 QualSelect = diag::CVQualList::Volatile;
17493
17494 if (QualSelect)
17495 Diag(Loc: UnderlyingLoc, DiagID: diag::warn_cv_stripped_in_enum) << *QualSelect;
17496
17497 T = T.getAtomicUnqualifiedType();
17498
17499 // This doesn't use 'isIntegralType' despite the error message mentioning
17500 // integral type because isIntegralType would also allow enum types in C.
17501 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17502 if (BT->isInteger())
17503 return false;
17504
17505 return Diag(Loc: UnderlyingLoc, DiagID: diag::err_enum_invalid_underlying)
17506 << T << T->isBitIntType();
17507}
17508
17509bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
17510 QualType EnumUnderlyingTy, bool IsFixed,
17511 const EnumDecl *Prev) {
17512 if (IsScoped != Prev->isScoped()) {
17513 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_scoped_mismatch)
17514 << Prev->isScoped();
17515 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17516 return true;
17517 }
17518
17519 if (IsFixed && Prev->isFixed()) {
17520 if (!EnumUnderlyingTy->isDependentType() &&
17521 !Prev->getIntegerType()->isDependentType() &&
17522 !Context.hasSameUnqualifiedType(T1: EnumUnderlyingTy,
17523 T2: Prev->getIntegerType())) {
17524 // TODO: Highlight the underlying type of the redeclaration.
17525 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_type_mismatch)
17526 << EnumUnderlyingTy << Prev->getIntegerType();
17527 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration)
17528 << Prev->getIntegerTypeRange();
17529 return true;
17530 }
17531 } else if (IsFixed != Prev->isFixed()) {
17532 Diag(Loc: EnumLoc, DiagID: diag::err_enum_redeclare_fixed_mismatch)
17533 << Prev->isFixed();
17534 Diag(Loc: Prev->getLocation(), DiagID: diag::note_previous_declaration);
17535 return true;
17536 }
17537
17538 return false;
17539}
17540
17541/// Get diagnostic %select index for tag kind for
17542/// redeclaration diagnostic message.
17543/// WARNING: Indexes apply to particular diagnostics only!
17544///
17545/// \returns diagnostic %select index.
17546static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
17547 switch (Tag) {
17548 case TagTypeKind::Struct:
17549 return 0;
17550 case TagTypeKind::Interface:
17551 return 1;
17552 case TagTypeKind::Class:
17553 return 2;
17554 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17555 }
17556}
17557
17558/// Determine if tag kind is a class-key compatible with
17559/// class for redeclaration (class, struct, or __interface).
17560///
17561/// \returns true iff the tag kind is compatible.
17562static bool isClassCompatTagKind(TagTypeKind Tag)
17563{
17564 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17565 Tag == TagTypeKind::Interface;
17566}
17567
17568NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, TagTypeKind TTK) {
17569 if (isa<TypedefDecl>(Val: PrevDecl))
17570 return NonTagKind::Typedef;
17571 else if (isa<TypeAliasDecl>(Val: PrevDecl))
17572 return NonTagKind::TypeAlias;
17573 else if (isa<ClassTemplateDecl>(Val: PrevDecl))
17574 return NonTagKind::Template;
17575 else if (isa<TypeAliasTemplateDecl>(Val: PrevDecl))
17576 return NonTagKind::TypeAliasTemplate;
17577 else if (isa<TemplateTemplateParmDecl>(Val: PrevDecl))
17578 return NonTagKind::TemplateTemplateArgument;
17579 switch (TTK) {
17580 case TagTypeKind::Struct:
17581 case TagTypeKind::Interface:
17582 case TagTypeKind::Class:
17583 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17584 : NonTagKind::NonStruct;
17585 case TagTypeKind::Union:
17586 return NonTagKind::NonUnion;
17587 case TagTypeKind::Enum:
17588 return NonTagKind::NonEnum;
17589 }
17590 llvm_unreachable("invalid TTK");
17591}
17592
17593bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
17594 TagTypeKind NewTag, bool isDefinition,
17595 SourceLocation NewTagLoc,
17596 const IdentifierInfo *Name) {
17597 // C++ [dcl.type.elab]p3:
17598 // The class-key or enum keyword present in the
17599 // elaborated-type-specifier shall agree in kind with the
17600 // declaration to which the name in the elaborated-type-specifier
17601 // refers. This rule also applies to the form of
17602 // elaborated-type-specifier that declares a class-name or
17603 // friend class since it can be construed as referring to the
17604 // definition of the class. Thus, in any
17605 // elaborated-type-specifier, the enum keyword shall be used to
17606 // refer to an enumeration (7.2), the union class-key shall be
17607 // used to refer to a union (clause 9), and either the class or
17608 // struct class-key shall be used to refer to a class (clause 9)
17609 // declared using the class or struct class-key.
17610 TagTypeKind OldTag = Previous->getTagKind();
17611 if (OldTag != NewTag &&
17612 !(isClassCompatTagKind(Tag: OldTag) && isClassCompatTagKind(Tag: NewTag)))
17613 return false;
17614
17615 // Tags are compatible, but we might still want to warn on mismatched tags.
17616 // Non-class tags can't be mismatched at this point.
17617 if (!isClassCompatTagKind(Tag: NewTag))
17618 return true;
17619
17620 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17621 // by our warning analysis. We don't want to warn about mismatches with (eg)
17622 // declarations in system headers that are designed to be specialized, but if
17623 // a user asks us to warn, we should warn if their code contains mismatched
17624 // declarations.
17625 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17626 return getDiagnostics().isIgnored(DiagID: diag::warn_struct_class_tag_mismatch,
17627 Loc);
17628 };
17629 if (IsIgnoredLoc(NewTagLoc))
17630 return true;
17631
17632 auto IsIgnored = [&](const TagDecl *Tag) {
17633 return IsIgnoredLoc(Tag->getLocation());
17634 };
17635 while (IsIgnored(Previous)) {
17636 Previous = Previous->getPreviousDecl();
17637 if (!Previous)
17638 return true;
17639 OldTag = Previous->getTagKind();
17640 }
17641
17642 bool isTemplate = false;
17643 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Previous))
17644 isTemplate = Record->getDescribedClassTemplate();
17645
17646 if (inTemplateInstantiation()) {
17647 if (OldTag != NewTag) {
17648 // In a template instantiation, do not offer fix-its for tag mismatches
17649 // since they usually mess up the template instead of fixing the problem.
17650 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17651 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17652 << getRedeclDiagFromTagKind(Tag: OldTag);
17653 // FIXME: Note previous location?
17654 }
17655 return true;
17656 }
17657
17658 if (isDefinition) {
17659 // On definitions, check all previous tags and issue a fix-it for each
17660 // one that doesn't match the current tag.
17661 if (Previous->getDefinition()) {
17662 // Don't suggest fix-its for redefinitions.
17663 return true;
17664 }
17665
17666 bool previousMismatch = false;
17667 for (const TagDecl *I : Previous->redecls()) {
17668 if (I->getTagKind() != NewTag) {
17669 // Ignore previous declarations for which the warning was disabled.
17670 if (IsIgnored(I))
17671 continue;
17672
17673 if (!previousMismatch) {
17674 previousMismatch = true;
17675 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_previous_tag_mismatch)
17676 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17677 << getRedeclDiagFromTagKind(Tag: I->getTagKind());
17678 }
17679 Diag(Loc: I->getInnerLocStart(), DiagID: diag::note_struct_class_suggestion)
17680 << getRedeclDiagFromTagKind(Tag: NewTag)
17681 << FixItHint::CreateReplacement(RemoveRange: I->getInnerLocStart(),
17682 Code: TypeWithKeyword::getTagTypeKindName(Kind: NewTag));
17683 }
17684 }
17685 return true;
17686 }
17687
17688 // Identify the prevailing tag kind: this is the kind of the definition (if
17689 // there is a non-ignored definition), or otherwise the kind of the prior
17690 // (non-ignored) declaration.
17691 const TagDecl *PrevDef = Previous->getDefinition();
17692 if (PrevDef && IsIgnored(PrevDef))
17693 PrevDef = nullptr;
17694 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17695 if (Redecl->getTagKind() != NewTag) {
17696 Diag(Loc: NewTagLoc, DiagID: diag::warn_struct_class_tag_mismatch)
17697 << getRedeclDiagFromTagKind(Tag: NewTag) << isTemplate << Name
17698 << getRedeclDiagFromTagKind(Tag: OldTag);
17699 Diag(Loc: Redecl->getLocation(), DiagID: diag::note_previous_use);
17700
17701 // If there is a previous definition, suggest a fix-it.
17702 if (PrevDef) {
17703 Diag(Loc: NewTagLoc, DiagID: diag::note_struct_class_suggestion)
17704 << getRedeclDiagFromTagKind(Tag: Redecl->getTagKind())
17705 << FixItHint::CreateReplacement(RemoveRange: SourceRange(NewTagLoc),
17706 Code: TypeWithKeyword::getTagTypeKindName(Kind: Redecl->getTagKind()));
17707 }
17708 }
17709
17710 return true;
17711}
17712
17713/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17714/// from an outer enclosing namespace or file scope inside a friend declaration.
17715/// This should provide the commented out code in the following snippet:
17716/// namespace N {
17717/// struct X;
17718/// namespace M {
17719/// struct Y { friend struct /*N::*/ X; };
17720/// }
17721/// }
17722static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17723 SourceLocation NameLoc) {
17724 // While the decl is in a namespace, do repeated lookup of that name and see
17725 // if we get the same namespace back. If we do not, continue until
17726 // translation unit scope, at which point we have a fully qualified NNS.
17727 SmallVector<IdentifierInfo *, 4> Namespaces;
17728 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17729 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17730 // This tag should be declared in a namespace, which can only be enclosed by
17731 // other namespaces. Bail if there's an anonymous namespace in the chain.
17732 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: DC);
17733 if (!Namespace || Namespace->isAnonymousNamespace())
17734 return FixItHint();
17735 IdentifierInfo *II = Namespace->getIdentifier();
17736 Namespaces.push_back(Elt: II);
17737 NamedDecl *Lookup = SemaRef.LookupSingleName(
17738 S, Name: II, Loc: NameLoc, NameKind: Sema::LookupNestedNameSpecifierName);
17739 if (Lookup == Namespace)
17740 break;
17741 }
17742
17743 // Once we have all the namespaces, reverse them to go outermost first, and
17744 // build an NNS.
17745 SmallString<64> Insertion;
17746 llvm::raw_svector_ostream OS(Insertion);
17747 if (DC->isTranslationUnit())
17748 OS << "::";
17749 std::reverse(first: Namespaces.begin(), last: Namespaces.end());
17750 for (auto *II : Namespaces)
17751 OS << II->getName() << "::";
17752 return FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: Insertion);
17753}
17754
17755/// Determine whether a tag originally declared in context \p OldDC can
17756/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17757/// found a declaration in \p OldDC as a previous decl, perhaps through a
17758/// using-declaration).
17759static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17760 DeclContext *NewDC) {
17761 OldDC = OldDC->getRedeclContext();
17762 NewDC = NewDC->getRedeclContext();
17763
17764 if (OldDC->Equals(DC: NewDC))
17765 return true;
17766
17767 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17768 // encloses the other).
17769 if (S.getLangOpts().MSVCCompat &&
17770 (OldDC->Encloses(DC: NewDC) || NewDC->Encloses(DC: OldDC)))
17771 return true;
17772
17773 return false;
17774}
17775
17776DeclResult
17777Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17778 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17779 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17780 SourceLocation ModulePrivateLoc,
17781 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17782 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17783 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17784 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17785 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17786 // If this is not a definition, it must have a name.
17787 IdentifierInfo *OrigName = Name;
17788 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17789 "Nameless record must be a definition!");
17790 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17791
17792 OwnedDecl = false;
17793 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
17794 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17795
17796 // FIXME: Check member specializations more carefully.
17797 bool isMemberSpecialization = false;
17798 bool IsInjectedClassName = false;
17799 bool Invalid = false;
17800
17801 // We only need to do this matching if we have template parameters
17802 // or a scope specifier, which also conveniently avoids this work
17803 // for non-C++ cases.
17804 if (TemplateParameterLists.size() > 0 ||
17805 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17806 TemplateParameterList *TemplateParams =
17807 MatchTemplateParametersToScopeSpecifier(
17808 DeclStartLoc: KWLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TemplateParameterLists,
17809 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
17810
17811 // C++23 [dcl.type.elab] p2:
17812 // If an elaborated-type-specifier is the sole constituent of a
17813 // declaration, the declaration is ill-formed unless it is an explicit
17814 // specialization, an explicit instantiation or it has one of the
17815 // following forms: [...]
17816 // C++23 [dcl.enum] p1:
17817 // If the enum-head-name of an opaque-enum-declaration contains a
17818 // nested-name-specifier, the declaration shall be an explicit
17819 // specialization.
17820 //
17821 // FIXME: Class template partial specializations can be forward declared
17822 // per CWG2213, but the resolution failed to allow qualified forward
17823 // declarations. This is almost certainly unintentional, so we allow them.
17824 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17825 !isMemberSpecialization)
17826 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_standalone_class_nested_name_specifier)
17827 << TypeWithKeyword::getTagTypeKindName(Kind) << SS.getRange();
17828
17829 if (TemplateParams) {
17830 if (Kind == TagTypeKind::Enum) {
17831 Diag(Loc: KWLoc, DiagID: diag::err_enum_template);
17832 return true;
17833 }
17834
17835 if (TemplateParams->size() > 0) {
17836 // This is a declaration or definition of a class template (which may
17837 // be a member of another template).
17838
17839 if (Invalid)
17840 return true;
17841
17842 OwnedDecl = false;
17843 DeclResult Result = CheckClassTemplate(
17844 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attr: Attrs, TemplateParams,
17845 AS, ModulePrivateLoc,
17846 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
17847 OuterTemplateParamLists: TemplateParameterLists.data(), SkipBody);
17848 return Result.get();
17849 } else {
17850 // The "template<>" header is extraneous.
17851 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
17852 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17853 isMemberSpecialization = true;
17854 }
17855 }
17856
17857 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17858 CheckTemplateDeclScope(S, TemplateParams: TemplateParameterLists.back()))
17859 return true;
17860 }
17861
17862 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17863 // C++23 [dcl.type.elab]p4:
17864 // If an elaborated-type-specifier appears with the friend specifier as
17865 // an entire member-declaration, the member-declaration shall have one
17866 // of the following forms:
17867 // friend class-key nested-name-specifier(opt) identifier ;
17868 // friend class-key simple-template-id ;
17869 // friend class-key nested-name-specifier template(opt)
17870 // simple-template-id ;
17871 //
17872 // Since enum is not a class-key, so declarations like "friend enum E;"
17873 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17874 // invalid, most implementations accept so we issue a pedantic warning.
17875 Diag(Loc: KWLoc, DiagID: diag::ext_enum_friend) << FixItHint::CreateRemoval(
17876 RemoveRange: ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17877 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17878 Diag(Loc: KWLoc, DiagID: diag::note_enum_friend)
17879 << (ScopedEnum + ScopedEnumUsesClassTag);
17880 }
17881
17882 // Figure out the underlying type if this a enum declaration. We need to do
17883 // this early, because it's needed to detect if this is an incompatible
17884 // redeclaration.
17885 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17886 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17887
17888 if (Kind == TagTypeKind::Enum) {
17889 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17890 // No underlying type explicitly specified, or we failed to parse the
17891 // type, default to int.
17892 EnumUnderlying = Context.IntTy.getTypePtr();
17893 } else if (UnderlyingType.get()) {
17894 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17895 // integral type; any cv-qualification is ignored.
17896 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17897 // unqualified, non-atomic version of the type specified by the type
17898 // specifiers in the specifier qualifier list.
17899 TypeSourceInfo *TI = nullptr;
17900 GetTypeFromParser(Ty: UnderlyingType.get(), TInfo: &TI);
17901 EnumUnderlying = TI;
17902
17903 if (CheckEnumUnderlyingType(TI))
17904 // Recover by falling back to int.
17905 EnumUnderlying = Context.IntTy.getTypePtr();
17906
17907 if (DiagnoseUnexpandedParameterPack(Loc: TI->getTypeLoc().getBeginLoc(), T: TI,
17908 UPPC: UPPC_FixedUnderlyingType))
17909 EnumUnderlying = Context.IntTy.getTypePtr();
17910
17911 // If the underlying type is atomic, we need to adjust the type before
17912 // continuing. This only happens in the case we stored a TypeSourceInfo
17913 // into EnumUnderlying because the other cases are error recovery up to
17914 // this point. But because it's not possible to gin up a TypeSourceInfo
17915 // for a non-atomic type from an atomic one, we'll store into the Type
17916 // field instead. FIXME: it would be nice to have an easy way to get a
17917 // derived TypeSourceInfo which strips qualifiers including the weird
17918 // ones like _Atomic where it forms a different type.
17919 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying);
17920 TI && TI->getType()->isAtomicType())
17921 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17922
17923 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17924 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17925 // of 'int'. However, if this is an unfixed forward declaration, don't set
17926 // the underlying type unless the user enables -fms-compatibility. This
17927 // makes unfixed forward declared enums incomplete and is more conforming.
17928 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17929 EnumUnderlying = Context.IntTy.getTypePtr();
17930 }
17931 }
17932
17933 DeclContext *SearchDC = CurContext;
17934 DeclContext *DC = CurContext;
17935 bool isStdBadAlloc = false;
17936 bool isStdAlignValT = false;
17937
17938 RedeclarationKind Redecl = forRedeclarationInCurContext();
17939 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17940 Redecl = RedeclarationKind::NotForRedeclaration;
17941
17942 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17943 /// implemented asks for structural equivalence checking, the returned decl
17944 /// here is passed back to the parser, allowing the tag body to be parsed.
17945 auto createTagFromNewDecl = [&]() -> TagDecl * {
17946 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17947 // If there is an identifier, use the location of the identifier as the
17948 // location of the decl, otherwise use the location of the struct/union
17949 // keyword.
17950 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17951 TagDecl *New = nullptr;
17952
17953 if (Kind == TagTypeKind::Enum) {
17954 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name, PrevDecl: nullptr,
17955 IsScoped: ScopedEnum, IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
17956 // If this is an undefined enum, bail.
17957 if (TUK != TagUseKind::Definition && !Invalid)
17958 return nullptr;
17959 if (EnumUnderlying) {
17960 EnumDecl *ED = cast<EnumDecl>(Val: New);
17961 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
17962 ED->setIntegerTypeSourceInfo(TI);
17963 else
17964 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
17965 QualType EnumTy = ED->getIntegerType();
17966 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
17967 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
17968 : EnumTy);
17969 }
17970 } else { // struct/union
17971 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
17972 PrevDecl: nullptr);
17973 }
17974
17975 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
17976 // Add alignment attributes if necessary; these attributes are checked
17977 // when the ASTContext lays out the structure.
17978 //
17979 // It is important for implementing the correct semantics that this
17980 // happen here (in ActOnTag). The #pragma pack stack is
17981 // maintained as a result of parser callbacks which can occur at
17982 // many points during the parsing of a struct declaration (because
17983 // the #pragma tokens are effectively skipped over during the
17984 // parsing of the struct).
17985 if (TUK == TagUseKind::Definition &&
17986 (!SkipBody || !SkipBody->ShouldSkip)) {
17987 if (LangOpts.HLSL)
17988 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
17989 AddAlignmentAttributesForRecord(RD);
17990 AddMsStructLayoutForRecord(RD);
17991 }
17992 }
17993 New->setLexicalDeclContext(CurContext);
17994 return New;
17995 };
17996
17997 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17998 if (Name && SS.isNotEmpty()) {
17999 // We have a nested-name tag ('struct foo::bar').
18000
18001 // Check for invalid 'foo::'.
18002 if (SS.isInvalid()) {
18003 Name = nullptr;
18004 goto CreateNewDecl;
18005 }
18006
18007 // If this is a friend or a reference to a class in a dependent
18008 // context, don't try to make a decl for it.
18009 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18010 DC = computeDeclContext(SS, EnteringContext: false);
18011 if (!DC) {
18012 IsDependent = true;
18013 return true;
18014 }
18015 } else {
18016 DC = computeDeclContext(SS, EnteringContext: true);
18017 if (!DC) {
18018 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_dependent_nested_name_spec)
18019 << SS.getRange();
18020 return true;
18021 }
18022 }
18023
18024 if (RequireCompleteDeclContext(SS, DC))
18025 return true;
18026
18027 SearchDC = DC;
18028 // Look-up name inside 'foo::'.
18029 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18030
18031 if (Previous.isAmbiguous())
18032 return true;
18033
18034 if (Previous.empty()) {
18035 // Name lookup did not find anything. However, if the
18036 // nested-name-specifier refers to the current instantiation,
18037 // and that current instantiation has any dependent base
18038 // classes, we might find something at instantiation time: treat
18039 // this as a dependent elaborated-type-specifier.
18040 // But this only makes any sense for reference-like lookups.
18041 if (Previous.wasNotFoundInCurrentInstantiation() &&
18042 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18043 IsDependent = true;
18044 return true;
18045 }
18046
18047 // A tag 'foo::bar' must already exist.
18048 Diag(Loc: NameLoc, DiagID: diag::err_not_tag_in_scope)
18049 << Kind << Name << DC << SS.getRange();
18050 Name = nullptr;
18051 Invalid = true;
18052 goto CreateNewDecl;
18053 }
18054 } else if (Name) {
18055 // C++14 [class.mem]p14:
18056 // If T is the name of a class, then each of the following shall have a
18057 // name different from T:
18058 // -- every member of class T that is itself a type
18059 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18060 DiagnoseClassNameShadow(DC: SearchDC, NameInfo: DeclarationNameInfo(Name, NameLoc)))
18061 return true;
18062
18063 // If this is a named struct, check to see if there was a previous forward
18064 // declaration or definition.
18065 // FIXME: We're looking into outer scopes here, even when we
18066 // shouldn't be. Doing so can result in ambiguities that we
18067 // shouldn't be diagnosing.
18068 LookupName(R&: Previous, S);
18069
18070 // When declaring or defining a tag, ignore ambiguities introduced
18071 // by types using'ed into this scope.
18072 if (Previous.isAmbiguous() &&
18073 (TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration)) {
18074 LookupResult::Filter F = Previous.makeFilter();
18075 while (F.hasNext()) {
18076 NamedDecl *ND = F.next();
18077 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18078 DC: SearchDC->getRedeclContext()))
18079 F.erase();
18080 }
18081 F.done();
18082 }
18083
18084 // C++11 [namespace.memdef]p3:
18085 // If the name in a friend declaration is neither qualified nor
18086 // a template-id and the declaration is a function or an
18087 // elaborated-type-specifier, the lookup to determine whether
18088 // the entity has been previously declared shall not consider
18089 // any scopes outside the innermost enclosing namespace.
18090 //
18091 // MSVC doesn't implement the above rule for types, so a friend tag
18092 // declaration may be a redeclaration of a type declared in an enclosing
18093 // scope. They do implement this rule for friend functions.
18094 //
18095 // Does it matter that this should be by scope instead of by
18096 // semantic context?
18097 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18098 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18099 LookupResult::Filter F = Previous.makeFilter();
18100 bool FriendSawTagOutsideEnclosingNamespace = false;
18101 while (F.hasNext()) {
18102 NamedDecl *ND = F.next();
18103 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
18104 if (DC->isFileContext() &&
18105 !EnclosingNS->Encloses(DC: ND->getDeclContext())) {
18106 if (getLangOpts().MSVCCompat)
18107 FriendSawTagOutsideEnclosingNamespace = true;
18108 else
18109 F.erase();
18110 }
18111 }
18112 F.done();
18113
18114 // Diagnose this MSVC extension in the easy case where lookup would have
18115 // unambiguously found something outside the enclosing namespace.
18116 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18117 NamedDecl *ND = Previous.getFoundDecl();
18118 Diag(Loc: NameLoc, DiagID: diag::ext_friend_tag_redecl_outside_namespace)
18119 << createFriendTagNNSFixIt(SemaRef&: *this, ND, S, NameLoc);
18120 }
18121 }
18122
18123 // Note: there used to be some attempt at recovery here.
18124 if (Previous.isAmbiguous())
18125 return true;
18126
18127 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18128 // FIXME: This makes sure that we ignore the contexts associated
18129 // with C structs, unions, and enums when looking for a matching
18130 // tag declaration or definition. See the similar lookup tweak
18131 // in Sema::LookupName; is there a better way to deal with this?
18132 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(Val: SearchDC))
18133 SearchDC = SearchDC->getParent();
18134 } else if (getLangOpts().CPlusPlus) {
18135 // Inside ObjCContainer want to keep it as a lexical decl context but go
18136 // past it (most often to TranslationUnit) to find the semantic decl
18137 // context.
18138 while (isa<ObjCContainerDecl>(Val: SearchDC))
18139 SearchDC = SearchDC->getParent();
18140 }
18141 } else if (getLangOpts().CPlusPlus) {
18142 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18143 // TagDecl the same way as we skip it for named TagDecl.
18144 while (isa<ObjCContainerDecl>(Val: SearchDC))
18145 SearchDC = SearchDC->getParent();
18146 }
18147
18148 if (Previous.isSingleResult() &&
18149 Previous.getFoundDecl()->isTemplateParameter()) {
18150 // Maybe we will complain about the shadowed template parameter.
18151 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl: Previous.getFoundDecl());
18152 // Just pretend that we didn't see the previous declaration.
18153 Previous.clear();
18154 }
18155
18156 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18157 DC->Equals(DC: getStdNamespace())) {
18158 if (Name->isStr(Str: "bad_alloc")) {
18159 // This is a declaration of or a reference to "std::bad_alloc".
18160 isStdBadAlloc = true;
18161
18162 // If std::bad_alloc has been implicitly declared (but made invisible to
18163 // name lookup), fill in this implicit declaration as the previous
18164 // declaration, so that the declarations get chained appropriately.
18165 if (Previous.empty() && StdBadAlloc)
18166 Previous.addDecl(D: getStdBadAlloc());
18167 } else if (Name->isStr(Str: "align_val_t")) {
18168 isStdAlignValT = true;
18169 if (Previous.empty() && StdAlignValT)
18170 Previous.addDecl(D: getStdAlignValT());
18171 }
18172 }
18173
18174 // If we didn't find a previous declaration, and this is a reference
18175 // (or friend reference), move to the correct scope. In C++, we
18176 // also need to do a redeclaration lookup there, just in case
18177 // there's a shadow friend decl.
18178 if (Name && Previous.empty() &&
18179 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18180 IsTemplateParamOrArg)) {
18181 if (Invalid) goto CreateNewDecl;
18182 assert(SS.isEmpty());
18183
18184 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18185 // C++ [basic.scope.pdecl]p5:
18186 // -- for an elaborated-type-specifier of the form
18187 //
18188 // class-key identifier
18189 //
18190 // if the elaborated-type-specifier is used in the
18191 // decl-specifier-seq or parameter-declaration-clause of a
18192 // function defined in namespace scope, the identifier is
18193 // declared as a class-name in the namespace that contains
18194 // the declaration; otherwise, except as a friend
18195 // declaration, the identifier is declared in the smallest
18196 // non-class, non-function-prototype scope that contains the
18197 // declaration.
18198 //
18199 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18200 // C structs and unions.
18201 //
18202 // It is an error in C++ to declare (rather than define) an enum
18203 // type, including via an elaborated type specifier. We'll
18204 // diagnose that later; for now, declare the enum in the same
18205 // scope as we would have picked for any other tag type.
18206 //
18207 // GNU C also supports this behavior as part of its incomplete
18208 // enum types extension, while GNU C++ does not.
18209 //
18210 // Find the context where we'll be declaring the tag.
18211 // FIXME: We would like to maintain the current DeclContext as the
18212 // lexical context,
18213 SearchDC = getTagInjectionContext(DC: SearchDC);
18214
18215 // Find the scope where we'll be declaring the tag.
18216 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18217 } else {
18218 assert(TUK == TagUseKind::Friend);
18219 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: SearchDC);
18220
18221 // C++ [namespace.memdef]p3:
18222 // If a friend declaration in a non-local class first declares a
18223 // class or function, the friend class or function is a member of
18224 // the innermost enclosing namespace.
18225 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18226 : SearchDC->getEnclosingNamespaceContext();
18227 }
18228
18229 // In C++, we need to do a redeclaration lookup to properly
18230 // diagnose some problems.
18231 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18232 // hidden declaration so that we don't get ambiguity errors when using a
18233 // type declared by an elaborated-type-specifier. In C that is not correct
18234 // and we should instead merge compatible types found by lookup.
18235 if (getLangOpts().CPlusPlus) {
18236 // FIXME: This can perform qualified lookups into function contexts,
18237 // which are meaningless.
18238 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18239 LookupQualifiedName(R&: Previous, LookupCtx: SearchDC);
18240 } else {
18241 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18242 LookupName(R&: Previous, S);
18243 }
18244 }
18245
18246 // If we have a known previous declaration to use, then use it.
18247 if (Previous.empty() && SkipBody && SkipBody->Previous)
18248 Previous.addDecl(D: SkipBody->Previous);
18249
18250 if (!Previous.empty()) {
18251 NamedDecl *PrevDecl = Previous.getFoundDecl();
18252 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18253
18254 // It's okay to have a tag decl in the same scope as a typedef
18255 // which hides a tag decl in the same scope. Finding this
18256 // with a redeclaration lookup can only actually happen in C++.
18257 //
18258 // This is also okay for elaborated-type-specifiers, which is
18259 // technically forbidden by the current standard but which is
18260 // okay according to the likely resolution of an open issue;
18261 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18262 if (getLangOpts().CPlusPlus) {
18263 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18264 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18265 if (Tag->getDeclName() == Name &&
18266 Tag->getDeclContext()->getRedeclContext()
18267 ->Equals(DC: TD->getDeclContext()->getRedeclContext())) {
18268 PrevDecl = Tag;
18269 Previous.clear();
18270 Previous.addDecl(D: Tag);
18271 Previous.resolveKind();
18272 }
18273 }
18274 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: PrevDecl);
18275 TUK == TagUseKind::Reference && RD &&
18276 RD->isInjectedClassName()) {
18277 // If lookup found the injected class name, the previous declaration is
18278 // the class being injected into.
18279 PrevDecl = cast<TagDecl>(Val: RD->getDeclContext());
18280 Previous.clear();
18281 Previous.addDecl(D: PrevDecl);
18282 Previous.resolveKind();
18283 IsInjectedClassName = true;
18284 }
18285 }
18286
18287 // If this is a redeclaration of a using shadow declaration, it must
18288 // declare a tag in the same context. In MSVC mode, we allow a
18289 // redefinition if either context is within the other.
18290 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: DirectPrevDecl)) {
18291 auto *OldTag = dyn_cast<TagDecl>(Val: PrevDecl);
18292 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18293 TUK != TagUseKind::Friend &&
18294 isDeclInScope(D: Shadow, Ctx: SearchDC, S, AllowInlineNamespace: isMemberSpecialization) &&
18295 !(OldTag && isAcceptableTagRedeclContext(
18296 S&: *this, OldDC: OldTag->getDeclContext(), NewDC: SearchDC))) {
18297 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
18298 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
18299 DiagID: diag::note_using_decl_target);
18300 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl)
18301 << 0;
18302 // Recover by ignoring the old declaration.
18303 Previous.clear();
18304 goto CreateNewDecl;
18305 }
18306 }
18307
18308 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(Val: PrevDecl)) {
18309 // If this is a use of a previous tag, or if the tag is already declared
18310 // in the same scope (so that the definition/declaration completes or
18311 // rementions the tag), reuse the decl.
18312 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18313 isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18314 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18315 // Make sure that this wasn't declared as an enum and now used as a
18316 // struct or something similar.
18317 if (!isAcceptableTagRedeclaration(Previous: PrevTagDecl, NewTag: Kind,
18318 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
18319 Name)) {
18320 bool SafeToContinue =
18321 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18322 Kind != TagTypeKind::Enum);
18323 if (SafeToContinue)
18324 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
18325 << Name
18326 << FixItHint::CreateReplacement(RemoveRange: SourceRange(KWLoc),
18327 Code: PrevTagDecl->getKindName());
18328 else
18329 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag) << Name;
18330 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_use);
18331
18332 if (SafeToContinue)
18333 Kind = PrevTagDecl->getTagKind();
18334 else {
18335 // Recover by making this an anonymous redefinition.
18336 Name = nullptr;
18337 Previous.clear();
18338 Invalid = true;
18339 }
18340 }
18341
18342 if (Kind == TagTypeKind::Enum &&
18343 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18344 const EnumDecl *PrevEnum = cast<EnumDecl>(Val: PrevTagDecl);
18345 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18346 return PrevTagDecl;
18347
18348 QualType EnumUnderlyingTy;
18349 if (TypeSourceInfo *TI =
18350 dyn_cast_if_present<TypeSourceInfo *>(Val&: EnumUnderlying))
18351 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18352 else if (const Type *T =
18353 dyn_cast_if_present<const Type *>(Val&: EnumUnderlying))
18354 EnumUnderlyingTy = QualType(T, 0);
18355
18356 // All conflicts with previous declarations are recovered by
18357 // returning the previous declaration, unless this is a definition,
18358 // in which case we want the caller to bail out.
18359 if (CheckEnumRedeclaration(EnumLoc: NameLoc.isValid() ? NameLoc : KWLoc,
18360 IsScoped: ScopedEnum, EnumUnderlyingTy,
18361 IsFixed, Prev: PrevEnum))
18362 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18363 }
18364
18365 // C++11 [class.mem]p1:
18366 // A member shall not be declared twice in the member-specification,
18367 // except that a nested class or member class template can be declared
18368 // and then later defined.
18369 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18370 S->isDeclScope(D: PrevDecl)) {
18371 Diag(Loc: NameLoc, DiagID: diag::ext_member_redeclared);
18372 Diag(Loc: PrevTagDecl->getLocation(), DiagID: diag::note_previous_declaration);
18373 }
18374
18375 if (!Invalid) {
18376 // If this is a use, just return the declaration we found, unless
18377 // we have attributes.
18378 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18379 if (!Attrs.empty()) {
18380 // FIXME: Diagnose these attributes. For now, we create a new
18381 // declaration to hold them.
18382 } else if (TUK == TagUseKind::Reference &&
18383 (PrevTagDecl->getFriendObjectKind() ==
18384 Decl::FOK_Undeclared ||
18385 PrevDecl->getOwningModule() != getCurrentModule()) &&
18386 SS.isEmpty()) {
18387 // This declaration is a reference to an existing entity, but
18388 // has different visibility from that entity: it either makes
18389 // a friend visible or it makes a type visible in a new module.
18390 // In either case, create a new declaration. We only do this if
18391 // the declaration would have meant the same thing if no prior
18392 // declaration were found, that is, if it was found in the same
18393 // scope where we would have injected a declaration.
18394 if (!getTagInjectionContext(DC: CurContext)->getRedeclContext()
18395 ->Equals(DC: PrevDecl->getDeclContext()->getRedeclContext()))
18396 return PrevTagDecl;
18397 // This is in the injected scope, create a new declaration in
18398 // that scope.
18399 S = getTagInjectionScope(S, LangOpts: getLangOpts());
18400 } else {
18401 return PrevTagDecl;
18402 }
18403 }
18404
18405 // Diagnose attempts to redefine a tag.
18406 if (TUK == TagUseKind::Definition) {
18407 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18408 // If the type is currently being defined, complain
18409 // about a nested redefinition.
18410 if (Def->isBeingDefined()) {
18411 Diag(Loc: NameLoc, DiagID: diag::err_nested_redefinition) << Name;
18412 Diag(Loc: PrevTagDecl->getLocation(),
18413 DiagID: diag::note_previous_definition);
18414 Name = nullptr;
18415 Previous.clear();
18416 Invalid = true;
18417 } else {
18418 // If we're defining a specialization and the previous
18419 // definition is from an implicit instantiation, don't emit an
18420 // error here; we'll catch this in the general case below.
18421 bool IsExplicitSpecializationAfterInstantiation = false;
18422 if (isMemberSpecialization) {
18423 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Def))
18424 IsExplicitSpecializationAfterInstantiation =
18425 RD->getTemplateSpecializationKind() !=
18426 TSK_ExplicitSpecialization;
18427 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: Def))
18428 IsExplicitSpecializationAfterInstantiation =
18429 ED->getTemplateSpecializationKind() !=
18430 TSK_ExplicitSpecialization;
18431 }
18432
18433 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18434 // do not keep more that one definition around (merge them).
18435 // However, ensure the decl passes the structural compatibility
18436 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18437 NamedDecl *Hidden = nullptr;
18438 bool HiddenDefVisible = false;
18439 if (SkipBody &&
18440 (isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible) ||
18441 getLangOpts().C23)) {
18442 // There is a definition of this tag, but it is not visible.
18443 // We explicitly make use of C++'s one definition rule here,
18444 // and assume that this definition is identical to the hidden
18445 // one we already have. Make the existing definition visible
18446 // and use it in place of this one.
18447 if (!getLangOpts().CPlusPlus) {
18448 // Postpone making the old definition visible until after we
18449 // complete parsing the new one and do the structural
18450 // comparison.
18451 SkipBody->CheckSameAsPrevious = true;
18452 SkipBody->New = createTagFromNewDecl();
18453 SkipBody->Previous = Def;
18454
18455 ProcessDeclAttributeList(S, D: SkipBody->New, AttrList: Attrs);
18456 return Def;
18457 }
18458
18459 SkipBody->ShouldSkip = true;
18460 SkipBody->Previous = Def;
18461 if (!HiddenDefVisible && Hidden)
18462 makeMergedDefinitionVisible(ND: Hidden);
18463 // Carry on and handle it like a normal definition. We'll
18464 // skip starting the definition later.
18465
18466 } else if (!IsExplicitSpecializationAfterInstantiation) {
18467 // A redeclaration in function prototype scope in C isn't
18468 // visible elsewhere, so merely issue a warning.
18469 if (!getLangOpts().CPlusPlus &&
18470 S->containedInPrototypeScope())
18471 Diag(Loc: NameLoc, DiagID: diag::warn_redefinition_in_param_list)
18472 << Name;
18473 else
18474 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
18475 notePreviousDefinition(Old: Def,
18476 New: NameLoc.isValid() ? NameLoc : KWLoc);
18477 // If this is a redefinition, recover by making this
18478 // struct be anonymous, which will make any later
18479 // references get the previous definition.
18480 Name = nullptr;
18481 Previous.clear();
18482 Invalid = true;
18483 }
18484 }
18485 }
18486
18487 // Okay, this is definition of a previously declared or referenced
18488 // tag. We're going to create a new Decl for it.
18489 }
18490
18491 // Okay, we're going to make a redeclaration. If this is some kind
18492 // of reference, make sure we build the redeclaration in the same DC
18493 // as the original, and ignore the current access specifier.
18494 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18495 SearchDC = PrevTagDecl->getDeclContext();
18496 AS = AS_none;
18497 }
18498 }
18499 // If we get here we have (another) forward declaration or we
18500 // have a definition. Just create a new decl.
18501
18502 } else {
18503 // If we get here, this is a definition of a new tag type in a nested
18504 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18505 // new decl/type. We set PrevDecl to NULL so that the entities
18506 // have distinct types.
18507 Previous.clear();
18508 }
18509 // If we get here, we're going to create a new Decl. If PrevDecl
18510 // is non-NULL, it's a definition of the tag declared by
18511 // PrevDecl. If it's NULL, we have a new definition.
18512
18513 // Otherwise, PrevDecl is not a tag, but was found with tag
18514 // lookup. This is only actually possible in C++, where a few
18515 // things like templates still live in the tag namespace.
18516 } else {
18517 // Use a better diagnostic if an elaborated-type-specifier
18518 // found the wrong kind of type on the first
18519 // (non-redeclaration) lookup.
18520 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18521 !Previous.isForRedeclaration()) {
18522 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18523 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_non_tag)
18524 << PrevDecl << NTK << Kind;
18525 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_declared_at);
18526 Invalid = true;
18527
18528 // Otherwise, only diagnose if the declaration is in scope.
18529 } else if (!isDeclInScope(D: DirectPrevDecl, Ctx: SearchDC, S,
18530 AllowInlineNamespace: SS.isNotEmpty() || isMemberSpecialization)) {
18531 // do nothing
18532
18533 // Diagnose implicit declarations introduced by elaborated types.
18534 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18535 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, TTK: Kind);
18536 Diag(Loc: NameLoc, DiagID: diag::err_tag_reference_conflict) << NTK;
18537 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18538 Invalid = true;
18539
18540 // Otherwise it's a declaration. Call out a particularly common
18541 // case here.
18542 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(Val: PrevDecl)) {
18543 unsigned Kind = 0;
18544 if (isa<TypeAliasDecl>(Val: PrevDecl)) Kind = 1;
18545 Diag(Loc: NameLoc, DiagID: diag::err_tag_definition_of_typedef)
18546 << Name << Kind << TND->getUnderlyingType();
18547 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_decl) << PrevDecl;
18548 Invalid = true;
18549
18550 // Otherwise, diagnose.
18551 } else {
18552 // The tag name clashes with something else in the target scope,
18553 // issue an error and recover by making this tag be anonymous.
18554 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
18555 notePreviousDefinition(Old: PrevDecl, New: NameLoc);
18556 Name = nullptr;
18557 Invalid = true;
18558 }
18559
18560 // The existing declaration isn't relevant to us; we're in a
18561 // new scope, so clear out the previous declaration.
18562 Previous.clear();
18563 }
18564 }
18565
18566CreateNewDecl:
18567
18568 TagDecl *PrevDecl = nullptr;
18569 if (Previous.isSingleResult())
18570 PrevDecl = cast<TagDecl>(Val: Previous.getFoundDecl());
18571
18572 // If there is an identifier, use the location of the identifier as the
18573 // location of the decl, otherwise use the location of the struct/union
18574 // keyword.
18575 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18576
18577 // Otherwise, create a new declaration. If there is a previous
18578 // declaration of the same entity, the two will be linked via
18579 // PrevDecl.
18580 TagDecl *New;
18581
18582 if (Kind == TagTypeKind::Enum) {
18583 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18584 // enum X { A, B, C } D; D should chain to X.
18585 New = EnumDecl::Create(C&: Context, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18586 PrevDecl: cast_or_null<EnumDecl>(Val: PrevDecl), IsScoped: ScopedEnum,
18587 IsScopedUsingClassTag: ScopedEnumUsesClassTag, IsFixed);
18588
18589 EnumDecl *ED = cast<EnumDecl>(Val: New);
18590 ED->setEnumKeyRange(SourceRange(
18591 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18592
18593 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18594 StdAlignValT = cast<EnumDecl>(Val: New);
18595
18596 // If this is an undefined enum, warn.
18597 if (TUK != TagUseKind::Definition && !Invalid) {
18598 TagDecl *Def;
18599 if (IsFixed && ED->isFixed()) {
18600 // C++0x: 7.2p2: opaque-enum-declaration.
18601 // Conflicts are diagnosed above. Do nothing.
18602 } else if (PrevDecl &&
18603 (Def = cast<EnumDecl>(Val: PrevDecl)->getDefinition())) {
18604 Diag(Loc, DiagID: diag::ext_forward_ref_enum_def)
18605 << New;
18606 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
18607 } else {
18608 unsigned DiagID = diag::ext_forward_ref_enum;
18609 if (getLangOpts().MSVCCompat)
18610 DiagID = diag::ext_ms_forward_ref_enum;
18611 else if (getLangOpts().CPlusPlus)
18612 DiagID = diag::err_forward_ref_enum;
18613 Diag(Loc, DiagID);
18614 }
18615 }
18616
18617 if (EnumUnderlying) {
18618 EnumDecl *ED = cast<EnumDecl>(Val: New);
18619 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(Val&: EnumUnderlying))
18620 ED->setIntegerTypeSourceInfo(TI);
18621 else
18622 ED->setIntegerType(QualType(cast<const Type *>(Val&: EnumUnderlying), 0));
18623 QualType EnumTy = ED->getIntegerType();
18624 ED->setPromotionType(Context.isPromotableIntegerType(T: EnumTy)
18625 ? Context.getPromotedIntegerType(PromotableType: EnumTy)
18626 : EnumTy);
18627 assert(ED->isComplete() && "enum with type should be complete");
18628 }
18629 } else {
18630 // struct/union/class
18631
18632 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18633 // struct X { int A; } D; D should chain to X.
18634 if (getLangOpts().CPlusPlus) {
18635 // FIXME: Look for a way to use RecordDecl for simple structs.
18636 New = CXXRecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18637 PrevDecl: cast_or_null<CXXRecordDecl>(Val: PrevDecl));
18638
18639 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18640 StdBadAlloc = cast<CXXRecordDecl>(Val: New);
18641 } else
18642 New = RecordDecl::Create(C: Context, TK: Kind, DC: SearchDC, StartLoc: KWLoc, IdLoc: Loc, Id: Name,
18643 PrevDecl: cast_or_null<RecordDecl>(Val: PrevDecl));
18644 }
18645
18646 // Only C23 and later allow defining new types in 'offsetof()'.
18647 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18648 !getLangOpts().CPlusPlus && !getLangOpts().C23)
18649 Diag(Loc: New->getLocation(), DiagID: diag::ext_type_defined_in_offsetof)
18650 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18651
18652 // C++11 [dcl.type]p3:
18653 // A type-specifier-seq shall not define a class or enumeration [...].
18654 if (!Invalid && getLangOpts().CPlusPlus &&
18655 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18656 TUK == TagUseKind::Definition) {
18657 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_type_specifier)
18658 << Context.getCanonicalTagType(TD: New);
18659 Invalid = true;
18660 }
18661
18662 if (!Invalid && getLangOpts().CPlusPlus && TUK == TagUseKind::Definition &&
18663 DC->getDeclKind() == Decl::Enum) {
18664 Diag(Loc: New->getLocation(), DiagID: diag::err_type_defined_in_enum)
18665 << Context.getCanonicalTagType(TD: New);
18666 Invalid = true;
18667 }
18668
18669 // Maybe add qualifier info.
18670 if (SS.isNotEmpty()) {
18671 if (SS.isSet()) {
18672 // If this is either a declaration or a definition, check the
18673 // nested-name-specifier against the current context.
18674 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18675 diagnoseQualifiedDeclaration(SS, DC, Name: OrigName, Loc,
18676 /*TemplateId=*/nullptr,
18677 IsMemberSpecialization: isMemberSpecialization))
18678 Invalid = true;
18679
18680 New->setQualifierInfo(SS.getWithLocInContext(Context));
18681 if (TemplateParameterLists.size() > 0) {
18682 New->setTemplateParameterListsInfo(Context, TPLists: TemplateParameterLists);
18683 }
18684 }
18685 else
18686 Invalid = true;
18687 }
18688
18689 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: New)) {
18690 // Add alignment attributes if necessary; these attributes are checked when
18691 // the ASTContext lays out the structure.
18692 //
18693 // It is important for implementing the correct semantics that this
18694 // happen here (in ActOnTag). The #pragma pack stack is
18695 // maintained as a result of parser callbacks which can occur at
18696 // many points during the parsing of a struct declaration (because
18697 // the #pragma tokens are effectively skipped over during the
18698 // parsing of the struct).
18699 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18700 if (LangOpts.HLSL)
18701 RD->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
18702 AddAlignmentAttributesForRecord(RD);
18703 AddMsStructLayoutForRecord(RD);
18704 }
18705 }
18706
18707 if (ModulePrivateLoc.isValid()) {
18708 if (isMemberSpecialization)
18709 Diag(Loc: New->getLocation(), DiagID: diag::err_module_private_specialization)
18710 << 2
18711 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
18712 // __module_private__ does not apply to local classes. However, we only
18713 // diagnose this as an error when the declaration specifiers are
18714 // freestanding. Here, we just ignore the __module_private__.
18715 else if (!SearchDC->isFunctionOrMethod())
18716 New->setModulePrivate();
18717 }
18718
18719 // If this is a specialization of a member class (of a class template),
18720 // check the specialization.
18721 if (isMemberSpecialization && CheckMemberSpecialization(Member: New, Previous))
18722 Invalid = true;
18723
18724 // If we're declaring or defining a tag in function prototype scope in C,
18725 // note that this type can only be used within the function and add it to
18726 // the list of decls to inject into the function definition scope. However,
18727 // in C23 and later, while the type is only visible within the function, the
18728 // function can be called with a compatible type defined in the same TU, so
18729 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18730 if ((Name || Kind == TagTypeKind::Enum) &&
18731 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18732 if (getLangOpts().CPlusPlus) {
18733 // C++ [dcl.fct]p6:
18734 // Types shall not be defined in return or parameter types.
18735 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18736 Diag(Loc, DiagID: diag::err_type_defined_in_param_type)
18737 << Name;
18738 Invalid = true;
18739 }
18740 if (TUK == TagUseKind::Declaration)
18741 Invalid = true;
18742 } else if (!PrevDecl) {
18743 // In C23 mode, if the declaration is complete, we do not want to
18744 // diagnose.
18745 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18746 Diag(Loc, DiagID: diag::warn_decl_in_param_list)
18747 << Context.getCanonicalTagType(TD: New);
18748 }
18749 }
18750
18751 if (Invalid)
18752 New->setInvalidDecl();
18753
18754 // Set the lexical context. If the tag has a C++ scope specifier, the
18755 // lexical context will be different from the semantic context.
18756 New->setLexicalDeclContext(CurContext);
18757
18758 // Mark this as a friend decl if applicable.
18759 // In Microsoft mode, a friend declaration also acts as a forward
18760 // declaration so we always pass true to setObjectOfFriendDecl to make
18761 // the tag name visible.
18762 if (TUK == TagUseKind::Friend)
18763 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18764
18765 // Set the access specifier.
18766 if (!Invalid && SearchDC->isRecord())
18767 SetMemberAccessSpecifier(MemberDecl: New, PrevMemberDecl: PrevDecl, LexicalAS: AS);
18768
18769 if (PrevDecl)
18770 CheckRedeclarationInModule(New, Old: PrevDecl);
18771
18772 if (TUK == TagUseKind::Definition) {
18773 if (!SkipBody || !SkipBody->ShouldSkip) {
18774 New->startDefinition();
18775 } else {
18776 New->setCompleteDefinition();
18777 New->demoteThisDefinitionToDeclaration();
18778 }
18779 }
18780
18781 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
18782 AddPragmaAttributes(S, D: New);
18783
18784 // If this has an identifier, add it to the scope stack.
18785 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18786 // We might be replacing an existing declaration in the lookup tables;
18787 // if so, borrow its access specifier.
18788 if (PrevDecl)
18789 New->setAccess(PrevDecl->getAccess());
18790
18791 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18792 DC->makeDeclVisibleInContext(D: New);
18793 if (Name) // can be null along some error paths
18794 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18795 PushOnScopeChains(D: New, S: EnclosingScope, /* AddToContext = */ false);
18796 } else if (Name) {
18797 S = getNonFieldDeclScope(S);
18798 PushOnScopeChains(D: New, S, AddToContext: true);
18799 } else {
18800 CurContext->addDecl(D: New);
18801 }
18802
18803 // If this is the C FILE type, notify the AST context.
18804 if (IdentifierInfo *II = New->getIdentifier())
18805 if (!New->isInvalidDecl() &&
18806 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18807 II->isStr(Str: "FILE"))
18808 Context.setFILEDecl(New);
18809
18810 if (PrevDecl)
18811 mergeDeclAttributes(New, Old: PrevDecl);
18812
18813 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: New)) {
18814 inferGslOwnerPointerAttribute(Record: CXXRD);
18815 inferNullableClassAttribute(CRD: CXXRD);
18816 }
18817
18818 // If there's a #pragma GCC visibility in scope, set the visibility of this
18819 // record.
18820 AddPushedVisibilityAttribute(RD: New);
18821
18822 // If this is not a definition, process API notes for it now.
18823 if (TUK != TagUseKind::Definition)
18824 ProcessAPINotes(D: New);
18825
18826 if (isMemberSpecialization && !New->isInvalidDecl())
18827 CompleteMemberSpecialization(Member: New, Previous);
18828
18829 OwnedDecl = true;
18830 // In C++, don't return an invalid declaration. We can't recover well from
18831 // the cases where we make the type anonymous.
18832 if (Invalid && getLangOpts().CPlusPlus) {
18833 if (New->isBeingDefined())
18834 if (auto RD = dyn_cast<RecordDecl>(Val: New))
18835 RD->completeDefinition();
18836 return true;
18837 } else if (SkipBody && SkipBody->ShouldSkip) {
18838 return SkipBody->Previous;
18839 } else {
18840 return New;
18841 }
18842}
18843
18844void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18845 AdjustDeclIfTemplate(Decl&: TagD);
18846 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18847
18848 // Enter the tag context.
18849 PushDeclContext(S, DC: Tag);
18850
18851 ActOnDocumentableDecl(D: TagD);
18852
18853 // If there's a #pragma GCC visibility in scope, set the visibility of this
18854 // record.
18855 AddPushedVisibilityAttribute(RD: Tag);
18856}
18857
18858bool Sema::ActOnDuplicateDefinition(Scope *S, Decl *Prev,
18859 SkipBodyInfo &SkipBody) {
18860 if (!hasStructuralCompatLayout(D: Prev, Suggested: SkipBody.New))
18861 return false;
18862
18863 // Make the previous decl visible.
18864 makeMergedDefinitionVisible(ND: SkipBody.Previous);
18865 CleanupMergedEnum(S, New: SkipBody.New);
18866 return true;
18867}
18868
18869void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18870 SourceLocation FinalLoc,
18871 bool IsFinalSpelledSealed,
18872 bool IsAbstract,
18873 SourceLocation LBraceLoc) {
18874 AdjustDeclIfTemplate(Decl&: TagD);
18875 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: TagD);
18876
18877 FieldCollector->StartClass();
18878
18879 if (!Record->getIdentifier())
18880 return;
18881
18882 if (IsAbstract)
18883 Record->markAbstract();
18884
18885 if (FinalLoc.isValid()) {
18886 Record->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: FinalLoc,
18887 S: IsFinalSpelledSealed
18888 ? FinalAttr::Keyword_sealed
18889 : FinalAttr::Keyword_final));
18890 }
18891
18892 // C++ [class]p2:
18893 // [...] The class-name is also inserted into the scope of the
18894 // class itself; this is known as the injected-class-name. For
18895 // purposes of access checking, the injected-class-name is treated
18896 // as if it were a public member name.
18897 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18898 C: Context, TK: Record->getTagKind(), DC: CurContext, StartLoc: Record->getBeginLoc(),
18899 IdLoc: Record->getLocation(), Id: Record->getIdentifier());
18900 InjectedClassName->setImplicit();
18901 InjectedClassName->setAccess(AS_public);
18902 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18903 InjectedClassName->setDescribedClassTemplate(Template);
18904
18905 PushOnScopeChains(D: InjectedClassName, S);
18906 assert(InjectedClassName->isInjectedClassName() &&
18907 "Broken injected-class-name");
18908}
18909
18910void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18911 SourceRange BraceRange) {
18912 AdjustDeclIfTemplate(Decl&: TagD);
18913 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18914 Tag->setBraceRange(BraceRange);
18915
18916 // Make sure we "complete" the definition even it is invalid.
18917 if (Tag->isBeingDefined()) {
18918 assert(Tag->isInvalidDecl() && "We should already have completed it");
18919 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18920 RD->completeDefinition();
18921 }
18922
18923 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Tag)) {
18924 FieldCollector->FinishClass();
18925 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18926 auto *Def = RD->getDefinition();
18927 assert(Def && "The record is expected to have a completed definition");
18928 unsigned NumInitMethods = 0;
18929 for (auto *Method : Def->methods()) {
18930 if (!Method->getIdentifier())
18931 continue;
18932 if (Method->getName() == "__init")
18933 NumInitMethods++;
18934 }
18935 if (NumInitMethods > 1 || !Def->hasInitMethod())
18936 Diag(Loc: RD->getLocation(), DiagID: diag::err_sycl_special_type_num_init_method);
18937 }
18938
18939 // If we're defining a dynamic class in a module interface unit, we always
18940 // need to produce the vtable for it, even if the vtable is not used in the
18941 // current TU.
18942 //
18943 // The case where the current class is not dynamic is handled in
18944 // MarkVTableUsed.
18945 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18946 MarkVTableUsed(Loc: RD->getLocation(), Class: RD, /*DefinitionRequired=*/true);
18947 }
18948
18949 // Exit this scope of this tag's definition.
18950 PopDeclContext();
18951
18952 if (getCurLexicalContext()->isObjCContainer() &&
18953 Tag->getDeclContext()->isFileContext())
18954 Tag->setTopLevelDeclInObjCContainer();
18955
18956 // Notify the consumer that we've defined a tag.
18957 if (!Tag->isInvalidDecl())
18958 Consumer.HandleTagDeclDefinition(D: Tag);
18959
18960 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18961 // from XLs and instead matches the XL #pragma pack(1) behavior.
18962 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18963 AlignPackStack.hasValue()) {
18964 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18965 // Only diagnose #pragma align(packed).
18966 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18967 return;
18968 const RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag);
18969 if (!RD)
18970 return;
18971 // Only warn if there is at least 1 bitfield member.
18972 if (llvm::any_of(Range: RD->fields(),
18973 P: [](const FieldDecl *FD) { return FD->isBitField(); }))
18974 Diag(Loc: BraceRange.getBegin(), DiagID: diag::warn_pragma_align_not_xl_compatible);
18975 }
18976}
18977
18978void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18979 AdjustDeclIfTemplate(Decl&: TagD);
18980 TagDecl *Tag = cast<TagDecl>(Val: TagD);
18981 Tag->setInvalidDecl();
18982
18983 // Make sure we "complete" the definition even it is invalid.
18984 if (Tag->isBeingDefined()) {
18985 if (RecordDecl *RD = dyn_cast<RecordDecl>(Val: Tag))
18986 RD->completeDefinition();
18987 }
18988
18989 // We're undoing ActOnTagStartDefinition here, not
18990 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18991 // the FieldCollector.
18992
18993 PopDeclContext();
18994}
18995
18996// Note that FieldName may be null for anonymous bitfields.
18997ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18998 const IdentifierInfo *FieldName,
18999 QualType FieldTy, bool IsMsStruct,
19000 Expr *BitWidth) {
19001 assert(BitWidth);
19002 if (BitWidth->containsErrors())
19003 return ExprError();
19004
19005 // C99 6.7.2.1p4 - verify the field type.
19006 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19007 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19008 // Handle incomplete and sizeless types with a specific error.
19009 if (RequireCompleteSizedType(Loc: FieldLoc, T: FieldTy,
19010 DiagID: diag::err_field_incomplete_or_sizeless))
19011 return ExprError();
19012 if (FieldName)
19013 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_bitfield)
19014 << FieldName << FieldTy << BitWidth->getSourceRange();
19015 return Diag(Loc: FieldLoc, DiagID: diag::err_not_integral_type_anon_bitfield)
19016 << FieldTy << BitWidth->getSourceRange();
19017 } else if (DiagnoseUnexpandedParameterPack(E: BitWidth, UPPC: UPPC_BitFieldWidth))
19018 return ExprError();
19019
19020 // If the bit-width is type- or value-dependent, don't try to check
19021 // it now.
19022 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19023 return BitWidth;
19024
19025 llvm::APSInt Value;
19026 ExprResult ICE =
19027 VerifyIntegerConstantExpression(E: BitWidth, Result: &Value, CanFold: AllowFoldKind::Allow);
19028 if (ICE.isInvalid())
19029 return ICE;
19030 BitWidth = ICE.get();
19031
19032 // Zero-width bitfield is ok for anonymous field.
19033 if (Value == 0 && FieldName)
19034 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_zero_width)
19035 << FieldName << BitWidth->getSourceRange();
19036
19037 if (Value.isSigned() && Value.isNegative()) {
19038 if (FieldName)
19039 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_has_negative_width)
19040 << FieldName << toString(I: Value, Radix: 10);
19041 return Diag(Loc: FieldLoc, DiagID: diag::err_anon_bitfield_has_negative_width)
19042 << toString(I: Value, Radix: 10);
19043 }
19044
19045 // The size of the bit-field must not exceed our maximum permitted object
19046 // size.
19047 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19048 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_too_wide)
19049 << !FieldName << FieldName << toString(I: Value, Radix: 10);
19050 }
19051
19052 if (!FieldTy->isDependentType()) {
19053 uint64_t TypeStorageSize = Context.getTypeSize(T: FieldTy);
19054 uint64_t TypeWidth = Context.getIntWidth(T: FieldTy);
19055 bool BitfieldIsOverwide = Value.ugt(RHS: TypeWidth);
19056
19057 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19058 // ABI.
19059 bool CStdConstraintViolation =
19060 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19061 bool MSBitfieldViolation = Value.ugt(RHS: TypeStorageSize) && IsMsStruct;
19062 if (CStdConstraintViolation || MSBitfieldViolation) {
19063 unsigned DiagWidth =
19064 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19065 return Diag(Loc: FieldLoc, DiagID: diag::err_bitfield_width_exceeds_type_width)
19066 << (bool)FieldName << FieldName << toString(I: Value, Radix: 10)
19067 << !CStdConstraintViolation << DiagWidth;
19068 }
19069
19070 // Warn on types where the user might conceivably expect to get all
19071 // specified bits as value bits: that's all integral types other than
19072 // 'bool'.
19073 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19074 Diag(Loc: FieldLoc, DiagID: diag::warn_bitfield_width_exceeds_type_width)
19075 << FieldName << Value << (unsigned)TypeWidth;
19076 }
19077 }
19078
19079 if (isa<ConstantExpr>(Val: BitWidth))
19080 return BitWidth;
19081 return ConstantExpr::Create(Context: getASTContext(), E: BitWidth, Result: APValue{Value});
19082}
19083
19084Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
19085 Declarator &D, Expr *BitfieldWidth) {
19086 FieldDecl *Res = HandleField(S, TagD: cast_if_present<RecordDecl>(Val: TagD), DeclStart,
19087 D, BitfieldWidth,
19088 /*InitStyle=*/ICIS_NoInit, AS: AS_public);
19089 return Res;
19090}
19091
19092FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
19093 SourceLocation DeclStart,
19094 Declarator &D, Expr *BitWidth,
19095 InClassInitStyle InitStyle,
19096 AccessSpecifier AS) {
19097 if (D.isDecompositionDeclarator()) {
19098 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
19099 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
19100 << Decomp.getSourceRange();
19101 return nullptr;
19102 }
19103
19104 const IdentifierInfo *II = D.getIdentifier();
19105 SourceLocation Loc = DeclStart;
19106 if (II) Loc = D.getIdentifierLoc();
19107
19108 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19109 QualType T = TInfo->getType();
19110 if (getLangOpts().CPlusPlus) {
19111 CheckExtraCXXDefaultArguments(D);
19112
19113 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19114 UPPC: UPPC_DataMemberType)) {
19115 D.setInvalidType();
19116 T = Context.IntTy;
19117 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19118 }
19119 }
19120
19121 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19122
19123 if (D.getDeclSpec().isInlineSpecified())
19124 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19125 << getLangOpts().CPlusPlus17;
19126 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19127 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19128 DiagID: diag::err_invalid_thread)
19129 << DeclSpec::getSpecifierName(S: TSCS);
19130
19131 // Check to see if this name was declared as a member previously
19132 NamedDecl *PrevDecl = nullptr;
19133 LookupResult Previous(*this, II, Loc, LookupMemberName,
19134 RedeclarationKind::ForVisibleRedeclaration);
19135 LookupName(R&: Previous, S);
19136 switch (Previous.getResultKind()) {
19137 case LookupResultKind::Found:
19138 case LookupResultKind::FoundUnresolvedValue:
19139 PrevDecl = Previous.getAsSingle<NamedDecl>();
19140 break;
19141
19142 case LookupResultKind::FoundOverloaded:
19143 PrevDecl = Previous.getRepresentativeDecl();
19144 break;
19145
19146 case LookupResultKind::NotFound:
19147 case LookupResultKind::NotFoundInCurrentInstantiation:
19148 case LookupResultKind::Ambiguous:
19149 break;
19150 }
19151 Previous.suppressDiagnostics();
19152
19153 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19154 // Maybe we will complain about the shadowed template parameter.
19155 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19156 // Just pretend that we didn't see the previous declaration.
19157 PrevDecl = nullptr;
19158 }
19159
19160 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19161 PrevDecl = nullptr;
19162
19163 bool Mutable
19164 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19165 SourceLocation TSSL = D.getBeginLoc();
19166 FieldDecl *NewFD
19167 = CheckFieldDecl(Name: II, T, TInfo, Record, Loc, Mutable, BitfieldWidth: BitWidth, InitStyle,
19168 TSSL, AS, PrevDecl, D: &D);
19169
19170 if (NewFD->isInvalidDecl())
19171 Record->setInvalidDecl();
19172
19173 if (D.getDeclSpec().isModulePrivateSpecified())
19174 NewFD->setModulePrivate();
19175
19176 if (NewFD->isInvalidDecl() && PrevDecl) {
19177 // Don't introduce NewFD into scope; there's already something
19178 // with the same name in the same scope.
19179 } else if (II) {
19180 PushOnScopeChains(D: NewFD, S);
19181 } else
19182 Record->addDecl(D: NewFD);
19183
19184 return NewFD;
19185}
19186
19187FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
19188 TypeSourceInfo *TInfo,
19189 RecordDecl *Record, SourceLocation Loc,
19190 bool Mutable, Expr *BitWidth,
19191 InClassInitStyle InitStyle,
19192 SourceLocation TSSL,
19193 AccessSpecifier AS, NamedDecl *PrevDecl,
19194 Declarator *D) {
19195 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19196 bool InvalidDecl = false;
19197 if (D) InvalidDecl = D->isInvalidType();
19198
19199 // If we receive a broken type, recover by assuming 'int' and
19200 // marking this declaration as invalid.
19201 if (T.isNull() || T->containsErrors()) {
19202 InvalidDecl = true;
19203 T = Context.IntTy;
19204 }
19205
19206 QualType EltTy = Context.getBaseElementType(QT: T);
19207 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19208 bool isIncomplete =
19209 LangOpts.HLSL // HLSL allows sizeless builtin types
19210 ? RequireCompleteType(Loc, T: EltTy, DiagID: diag::err_incomplete_type)
19211 : RequireCompleteSizedType(Loc, T: EltTy,
19212 DiagID: diag::err_field_incomplete_or_sizeless);
19213 if (isIncomplete) {
19214 // Fields of incomplete type force their record to be invalid.
19215 Record->setInvalidDecl();
19216 InvalidDecl = true;
19217 } else {
19218 NamedDecl *Def;
19219 EltTy->isIncompleteType(Def: &Def);
19220 if (Def && Def->isInvalidDecl()) {
19221 Record->setInvalidDecl();
19222 InvalidDecl = true;
19223 }
19224 }
19225 }
19226
19227 // TR 18037 does not allow fields to be declared with address space
19228 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19229 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19230 Diag(Loc, DiagID: diag::err_field_with_address_space);
19231 Record->setInvalidDecl();
19232 InvalidDecl = true;
19233 }
19234
19235 if (LangOpts.OpenCL) {
19236 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19237 // used as structure or union field: image, sampler, event or block types.
19238 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19239 T->isBlockPointerType()) {
19240 Diag(Loc, DiagID: diag::err_opencl_type_struct_or_union_field) << T;
19241 Record->setInvalidDecl();
19242 InvalidDecl = true;
19243 }
19244 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19245 // is enabled.
19246 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19247 Ext: "__cl_clang_bitfields", LO: LangOpts)) {
19248 Diag(Loc, DiagID: diag::err_opencl_bitfields);
19249 InvalidDecl = true;
19250 }
19251 }
19252
19253 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19254 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19255 T.hasQualifiers()) {
19256 InvalidDecl = true;
19257 Diag(Loc, DiagID: diag::err_anon_bitfield_qualifiers);
19258 }
19259
19260 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19261 // than a variably modified type.
19262 if (!InvalidDecl && T->isVariablyModifiedType()) {
19263 if (!tryToFixVariablyModifiedVarType(
19264 TInfo, T, Loc, FailedFoldDiagID: diag::err_typecheck_field_variable_size))
19265 InvalidDecl = true;
19266 }
19267
19268 // Fields can not have abstract class types
19269 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19270 DiagID: diag::err_abstract_type_in_decl,
19271 Args: AbstractFieldType))
19272 InvalidDecl = true;
19273
19274 if (InvalidDecl)
19275 BitWidth = nullptr;
19276 // If this is declared as a bit-field, check the bit-field.
19277 if (BitWidth) {
19278 BitWidth =
19279 VerifyBitField(FieldLoc: Loc, FieldName: II, FieldTy: T, IsMsStruct: Record->isMsStruct(C: Context), BitWidth).get();
19280 if (!BitWidth) {
19281 InvalidDecl = true;
19282 BitWidth = nullptr;
19283 }
19284 }
19285
19286 // Check that 'mutable' is consistent with the type of the declaration.
19287 if (!InvalidDecl && Mutable) {
19288 unsigned DiagID = 0;
19289 if (T->isReferenceType())
19290 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19291 : diag::err_mutable_reference;
19292 else if (T.isConstQualified())
19293 DiagID = diag::err_mutable_const;
19294
19295 if (DiagID) {
19296 SourceLocation ErrLoc = Loc;
19297 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19298 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19299 Diag(Loc: ErrLoc, DiagID);
19300 if (DiagID != diag::ext_mutable_reference) {
19301 Mutable = false;
19302 InvalidDecl = true;
19303 }
19304 }
19305 }
19306
19307 // C++11 [class.union]p8 (DR1460):
19308 // At most one variant member of a union may have a
19309 // brace-or-equal-initializer.
19310 if (InitStyle != ICIS_NoInit)
19311 checkDuplicateDefaultInit(S&: *this, Parent: cast<CXXRecordDecl>(Val: Record), DefaultInitLoc: Loc);
19312
19313 FieldDecl *NewFD = FieldDecl::Create(C: Context, DC: Record, StartLoc: TSSL, IdLoc: Loc, Id: II, T, TInfo,
19314 BW: BitWidth, Mutable, InitStyle);
19315 if (InvalidDecl)
19316 NewFD->setInvalidDecl();
19317
19318 if (!InvalidDecl)
19319 warnOnCTypeHiddenInCPlusPlus(D: NewFD);
19320
19321 if (PrevDecl && !isa<TagDecl>(Val: PrevDecl) &&
19322 !PrevDecl->isPlaceholderVar(LangOpts: getLangOpts())) {
19323 Diag(Loc, DiagID: diag::err_duplicate_member) << II;
19324 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_declaration);
19325 NewFD->setInvalidDecl();
19326 }
19327
19328 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19329 if (Record->isUnion()) {
19330 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19331 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19332
19333 // C++ [class.union]p1: An object of a class with a non-trivial
19334 // constructor, a non-trivial copy constructor, a non-trivial
19335 // destructor, or a non-trivial copy assignment operator
19336 // cannot be a member of a union, nor can an array of such
19337 // objects.
19338 if (CheckNontrivialField(FD: NewFD))
19339 NewFD->setInvalidDecl();
19340 }
19341
19342 // C++ [class.union]p1: If a union contains a member of reference type,
19343 // the program is ill-formed, except when compiling with MSVC extensions
19344 // enabled.
19345 if (EltTy->isReferenceType()) {
19346 const bool HaveMSExt =
19347 getLangOpts().MicrosoftExt &&
19348 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
19349
19350 Diag(Loc: NewFD->getLocation(),
19351 DiagID: HaveMSExt ? diag::ext_union_member_of_reference_type
19352 : diag::err_union_member_of_reference_type)
19353 << NewFD->getDeclName() << EltTy;
19354 if (!HaveMSExt)
19355 NewFD->setInvalidDecl();
19356 }
19357 }
19358 }
19359
19360 // FIXME: We need to pass in the attributes given an AST
19361 // representation, not a parser representation.
19362 if (D) {
19363 // FIXME: The current scope is almost... but not entirely... correct here.
19364 ProcessDeclAttributes(S: getCurScope(), D: NewFD, PD: *D);
19365
19366 if (NewFD->hasAttrs())
19367 CheckAlignasUnderalignment(D: NewFD);
19368 }
19369
19370 // In auto-retain/release, infer strong retension for fields of
19371 // retainable type.
19372 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: NewFD))
19373 NewFD->setInvalidDecl();
19374
19375 if (T.isObjCGCWeak())
19376 Diag(Loc, DiagID: diag::warn_attribute_weak_on_field);
19377
19378 // PPC MMA non-pointer types are not allowed as field types.
19379 if (Context.getTargetInfo().getTriple().isPPC64() &&
19380 PPC().CheckPPCMMAType(Type: T, TypeLoc: NewFD->getLocation()))
19381 NewFD->setInvalidDecl();
19382
19383 NewFD->setAccess(AS);
19384 return NewFD;
19385}
19386
19387bool Sema::CheckNontrivialField(FieldDecl *FD) {
19388 assert(FD);
19389 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19390
19391 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19392 return false;
19393
19394 QualType EltTy = Context.getBaseElementType(QT: FD->getType());
19395 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19396 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19397 // We check for copy constructors before constructors
19398 // because otherwise we'll never get complaints about
19399 // copy constructors.
19400
19401 CXXSpecialMemberKind member = CXXSpecialMemberKind::Invalid;
19402 // We're required to check for any non-trivial constructors. Since the
19403 // implicit default constructor is suppressed if there are any
19404 // user-declared constructors, we just need to check that there is a
19405 // trivial default constructor and a trivial copy constructor. (We don't
19406 // worry about move constructors here, since this is a C++98 check.)
19407 if (RDecl->hasNonTrivialCopyConstructor())
19408 member = CXXSpecialMemberKind::CopyConstructor;
19409 else if (!RDecl->hasTrivialDefaultConstructor())
19410 member = CXXSpecialMemberKind::DefaultConstructor;
19411 else if (RDecl->hasNonTrivialCopyAssignment())
19412 member = CXXSpecialMemberKind::CopyAssignment;
19413 else if (RDecl->hasNonTrivialDestructor())
19414 member = CXXSpecialMemberKind::Destructor;
19415
19416 if (member != CXXSpecialMemberKind::Invalid) {
19417 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19418 RDecl->hasObjectMember()) {
19419 // Objective-C++ ARC: it is an error to have a non-trivial field of
19420 // a union. However, system headers in Objective-C programs
19421 // occasionally have Objective-C lifetime objects within unions,
19422 // and rather than cause the program to fail, we make those
19423 // members unavailable.
19424 SourceLocation Loc = FD->getLocation();
19425 if (getSourceManager().isInSystemHeader(Loc)) {
19426 if (!FD->hasAttr<UnavailableAttr>())
19427 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19428 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership, Range: Loc));
19429 return false;
19430 }
19431 }
19432
19433 Diag(Loc: FD->getLocation(),
19434 DiagID: getLangOpts().CPlusPlus11
19435 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19436 : diag::err_illegal_union_or_anon_struct_member)
19437 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19438 DiagnoseNontrivial(Record: RDecl, CSM: member);
19439 return !getLangOpts().CPlusPlus11;
19440 }
19441 }
19442
19443 return false;
19444}
19445
19446void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
19447 SmallVectorImpl<Decl *> &AllIvarDecls) {
19448 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19449 return;
19450
19451 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19452 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Val: ivarDecl);
19453
19454 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19455 return;
19456 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: CurContext);
19457 if (!ID) {
19458 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(Val: CurContext)) {
19459 if (!CD->IsClassExtension())
19460 return;
19461 }
19462 // No need to add this to end of @implementation.
19463 else
19464 return;
19465 }
19466 // All conditions are met. Add a new bitfield to the tail end of ivars.
19467 llvm::APInt Zero(Context.getTypeSize(T: Context.IntTy), 0);
19468 Expr * BW = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: DeclLoc);
19469 Expr *BitWidth =
19470 ConstantExpr::Create(Context, E: BW, Result: APValue(llvm::APSInt(Zero)));
19471
19472 Ivar = ObjCIvarDecl::Create(
19473 C&: Context, DC: cast<ObjCContainerDecl>(Val: CurContext), StartLoc: DeclLoc, IdLoc: DeclLoc, Id: nullptr,
19474 T: Context.CharTy, TInfo: Context.getTrivialTypeSourceInfo(T: Context.CharTy, Loc: DeclLoc),
19475 ac: ObjCIvarDecl::Private, BW: BitWidth, synthesized: true);
19476 AllIvarDecls.push_back(Elt: Ivar);
19477}
19478
19479/// [class.dtor]p4:
19480/// At the end of the definition of a class, overload resolution is
19481/// performed among the prospective destructors declared in that class with
19482/// an empty argument list to select the destructor for the class, also
19483/// known as the selected destructor.
19484///
19485/// We do the overload resolution here, then mark the selected constructor in the AST.
19486/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19487static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
19488 if (!Record->hasUserDeclaredDestructor()) {
19489 return;
19490 }
19491
19492 SourceLocation Loc = Record->getLocation();
19493 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
19494
19495 for (auto *Decl : Record->decls()) {
19496 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: Decl)) {
19497 if (DD->isInvalidDecl())
19498 continue;
19499 S.AddOverloadCandidate(Function: DD, FoundDecl: DeclAccessPair::make(D: DD, AS: DD->getAccess()), Args: {},
19500 CandidateSet&: OCS);
19501 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19502 }
19503 }
19504
19505 if (OCS.empty()) {
19506 return;
19507 }
19508 OverloadCandidateSet::iterator Best;
19509 unsigned Msg = 0;
19510 OverloadCandidateDisplayKind DisplayKind;
19511
19512 switch (OCS.BestViableFunction(S, Loc, Best)) {
19513 case OR_Success:
19514 case OR_Deleted:
19515 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: Best->Function));
19516 break;
19517
19518 case OR_Ambiguous:
19519 Msg = diag::err_ambiguous_destructor;
19520 DisplayKind = OCD_AmbiguousCandidates;
19521 break;
19522
19523 case OR_No_Viable_Function:
19524 Msg = diag::err_no_viable_destructor;
19525 DisplayKind = OCD_AllCandidates;
19526 break;
19527 }
19528
19529 if (Msg) {
19530 // OpenCL have got their own thing going with destructors. It's slightly broken,
19531 // but we allow it.
19532 if (!S.LangOpts.OpenCL) {
19533 PartialDiagnostic Diag = S.PDiag(DiagID: Msg) << Record;
19534 OCS.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, OCD: DisplayKind, Args: {});
19535 Record->setInvalidDecl();
19536 }
19537 // It's a bit hacky: At this point we've raised an error but we want the
19538 // rest of the compiler to continue somehow working. However almost
19539 // everything we'll try to do with the class will depend on there being a
19540 // destructor. So let's pretend the first one is selected and hope for the
19541 // best.
19542 Record->addedSelectedDestructor(DD: dyn_cast<CXXDestructorDecl>(Val: OCS.begin()->Function));
19543 }
19544}
19545
19546/// [class.mem.special]p5
19547/// Two special member functions are of the same kind if:
19548/// - they are both default constructors,
19549/// - they are both copy or move constructors with the same first parameter
19550/// type, or
19551/// - they are both copy or move assignment operators with the same first
19552/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19553static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
19554 CXXMethodDecl *M1,
19555 CXXMethodDecl *M2,
19556 CXXSpecialMemberKind CSM) {
19557 // We don't want to compare templates to non-templates: See
19558 // https://github.com/llvm/llvm-project/issues/59206
19559 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
19560 return bool(M1->getDescribedFunctionTemplate()) ==
19561 bool(M2->getDescribedFunctionTemplate());
19562 // FIXME: better resolve CWG
19563 // https://cplusplus.github.io/CWG/issues/2787.html
19564 if (!Context.hasSameType(T1: M1->getNonObjectParameter(I: 0)->getType(),
19565 T2: M2->getNonObjectParameter(I: 0)->getType()))
19566 return false;
19567 if (!Context.hasSameType(T1: M1->getFunctionObjectParameterReferenceType(),
19568 T2: M2->getFunctionObjectParameterReferenceType()))
19569 return false;
19570
19571 return true;
19572}
19573
19574/// [class.mem.special]p6:
19575/// An eligible special member function is a special member function for which:
19576/// - the function is not deleted,
19577/// - the associated constraints, if any, are satisfied, and
19578/// - no special member function of the same kind whose associated constraints
19579/// [CWG2595], if any, are satisfied is more constrained.
19580static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
19581 ArrayRef<CXXMethodDecl *> Methods,
19582 CXXSpecialMemberKind CSM) {
19583 SmallVector<bool, 4> SatisfactionStatus;
19584
19585 for (CXXMethodDecl *Method : Methods) {
19586 if (!Method->getTrailingRequiresClause())
19587 SatisfactionStatus.push_back(Elt: true);
19588 else {
19589 ConstraintSatisfaction Satisfaction;
19590 if (S.CheckFunctionConstraints(FD: Method, Satisfaction))
19591 SatisfactionStatus.push_back(Elt: false);
19592 else
19593 SatisfactionStatus.push_back(Elt: Satisfaction.IsSatisfied);
19594 }
19595 }
19596
19597 for (size_t i = 0; i < Methods.size(); i++) {
19598 if (!SatisfactionStatus[i])
19599 continue;
19600 CXXMethodDecl *Method = Methods[i];
19601 CXXMethodDecl *OrigMethod = Method;
19602 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19603 OrigMethod = cast<CXXMethodDecl>(Val: MF);
19604
19605 AssociatedConstraint Orig = OrigMethod->getTrailingRequiresClause();
19606 bool AnotherMethodIsMoreConstrained = false;
19607 for (size_t j = 0; j < Methods.size(); j++) {
19608 if (i == j || !SatisfactionStatus[j])
19609 continue;
19610 CXXMethodDecl *OtherMethod = Methods[j];
19611 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19612 OtherMethod = cast<CXXMethodDecl>(Val: MF);
19613
19614 if (!AreSpecialMemberFunctionsSameKind(Context&: S.Context, M1: OrigMethod, M2: OtherMethod,
19615 CSM))
19616 continue;
19617
19618 AssociatedConstraint Other = OtherMethod->getTrailingRequiresClause();
19619 if (!Other)
19620 continue;
19621 if (!Orig) {
19622 AnotherMethodIsMoreConstrained = true;
19623 break;
19624 }
19625 if (S.IsAtLeastAsConstrained(D1: OtherMethod, AC1: {Other}, D2: OrigMethod, AC2: {Orig},
19626 Result&: AnotherMethodIsMoreConstrained)) {
19627 // There was an error with the constraints comparison. Exit the loop
19628 // and don't consider this function eligible.
19629 AnotherMethodIsMoreConstrained = true;
19630 }
19631 if (AnotherMethodIsMoreConstrained)
19632 break;
19633 }
19634 // FIXME: Do not consider deleted methods as eligible after implementing
19635 // DR1734 and DR1496.
19636 if (!AnotherMethodIsMoreConstrained) {
19637 Method->setIneligibleOrNotSelected(false);
19638 Record->addedEligibleSpecialMemberFunction(MD: Method,
19639 SMKind: 1 << llvm::to_underlying(E: CSM));
19640 }
19641 }
19642}
19643
19644static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
19645 CXXRecordDecl *Record) {
19646 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19647 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19648 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19649 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19650 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19651
19652 for (auto *Decl : Record->decls()) {
19653 auto *MD = dyn_cast<CXXMethodDecl>(Val: Decl);
19654 if (!MD) {
19655 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Decl);
19656 if (FTD)
19657 MD = dyn_cast<CXXMethodDecl>(Val: FTD->getTemplatedDecl());
19658 }
19659 if (!MD)
19660 continue;
19661 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD)) {
19662 if (CD->isInvalidDecl())
19663 continue;
19664 if (CD->isDefaultConstructor())
19665 DefaultConstructors.push_back(Elt: MD);
19666 else if (CD->isCopyConstructor())
19667 CopyConstructors.push_back(Elt: MD);
19668 else if (CD->isMoveConstructor())
19669 MoveConstructors.push_back(Elt: MD);
19670 } else if (MD->isCopyAssignmentOperator()) {
19671 CopyAssignmentOperators.push_back(Elt: MD);
19672 } else if (MD->isMoveAssignmentOperator()) {
19673 MoveAssignmentOperators.push_back(Elt: MD);
19674 }
19675 }
19676
19677 SetEligibleMethods(S, Record, Methods: DefaultConstructors,
19678 CSM: CXXSpecialMemberKind::DefaultConstructor);
19679 SetEligibleMethods(S, Record, Methods: CopyConstructors,
19680 CSM: CXXSpecialMemberKind::CopyConstructor);
19681 SetEligibleMethods(S, Record, Methods: MoveConstructors,
19682 CSM: CXXSpecialMemberKind::MoveConstructor);
19683 SetEligibleMethods(S, Record, Methods: CopyAssignmentOperators,
19684 CSM: CXXSpecialMemberKind::CopyAssignment);
19685 SetEligibleMethods(S, Record, Methods: MoveAssignmentOperators,
19686 CSM: CXXSpecialMemberKind::MoveAssignment);
19687}
19688
19689bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19690 // Check to see if a FieldDecl is a pointer to a function.
19691 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19692 const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
19693 if (!FD) {
19694 // Check whether this is a forward declaration that was inserted by
19695 // Clang. This happens when a non-forward declared / defined type is
19696 // used, e.g.:
19697 //
19698 // struct foo {
19699 // struct bar *(*f)();
19700 // struct bar *(*g)();
19701 // };
19702 //
19703 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19704 // incomplete definition.
19705 if (const auto *TD = dyn_cast<TagDecl>(Val: D))
19706 return !TD->isCompleteDefinition();
19707 return false;
19708 }
19709 QualType FieldType = FD->getType().getDesugaredType(Context);
19710 if (isa<PointerType>(Val: FieldType)) {
19711 QualType PointeeType = cast<PointerType>(Val&: FieldType)->getPointeeType();
19712 return PointeeType.getDesugaredType(Context)->isFunctionType();
19713 }
19714 // If a member is a struct entirely of function pointers, that counts too.
19715 if (const auto *Record = FieldType->getAsRecordDecl();
19716 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19717 return true;
19718 return false;
19719 };
19720
19721 return llvm::all_of(Range: Record->decls(), P: IsFunctionPointerOrForwardDecl);
19722}
19723
19724void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19725 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19726 SourceLocation RBrac,
19727 const ParsedAttributesView &Attrs) {
19728 assert(EnclosingDecl && "missing record or interface decl");
19729
19730 // If this is an Objective-C @implementation or category and we have
19731 // new fields here we should reset the layout of the interface since
19732 // it will now change.
19733 if (!Fields.empty() && isa<ObjCContainerDecl>(Val: EnclosingDecl)) {
19734 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(Val: EnclosingDecl);
19735 switch (DC->getKind()) {
19736 default: break;
19737 case Decl::ObjCCategory:
19738 Context.ResetObjCLayout(D: cast<ObjCCategoryDecl>(Val: DC)->getClassInterface());
19739 break;
19740 case Decl::ObjCImplementation:
19741 Context.
19742 ResetObjCLayout(D: cast<ObjCImplementationDecl>(Val: DC)->getClassInterface());
19743 break;
19744 }
19745 }
19746
19747 RecordDecl *Record = dyn_cast<RecordDecl>(Val: EnclosingDecl);
19748 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: EnclosingDecl);
19749
19750 // Start counting up the number of named members; make sure to include
19751 // members of anonymous structs and unions in the total.
19752 unsigned NumNamedMembers = 0;
19753 if (Record) {
19754 for (const auto *I : Record->decls()) {
19755 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I))
19756 if (IFD->getDeclName())
19757 ++NumNamedMembers;
19758 }
19759 }
19760
19761 // Verify that all the fields are okay.
19762 SmallVector<FieldDecl*, 32> RecFields;
19763 const FieldDecl *PreviousField = nullptr;
19764 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19765 i != end; PreviousField = cast<FieldDecl>(Val: *i), ++i) {
19766 FieldDecl *FD = cast<FieldDecl>(Val: *i);
19767
19768 // Get the type for the field.
19769 const Type *FDTy = FD->getType().getTypePtr();
19770
19771 if (!FD->isAnonymousStructOrUnion()) {
19772 // Remember all fields written by the user.
19773 RecFields.push_back(Elt: FD);
19774 }
19775
19776 // If the field is already invalid for some reason, don't emit more
19777 // diagnostics about it.
19778 if (FD->isInvalidDecl()) {
19779 EnclosingDecl->setInvalidDecl();
19780 continue;
19781 }
19782
19783 // C99 6.7.2.1p2:
19784 // A structure or union shall not contain a member with
19785 // incomplete or function type (hence, a structure shall not
19786 // contain an instance of itself, but may contain a pointer to
19787 // an instance of itself), except that the last member of a
19788 // structure with more than one named member may have incomplete
19789 // array type; such a structure (and any union containing,
19790 // possibly recursively, a member that is such a structure)
19791 // shall not be a member of a structure or an element of an
19792 // array.
19793 bool IsLastField = (i + 1 == Fields.end());
19794 if (FDTy->isFunctionType()) {
19795 // Field declared as a function.
19796 Diag(Loc: FD->getLocation(), DiagID: diag::err_field_declared_as_function)
19797 << FD->getDeclName();
19798 FD->setInvalidDecl();
19799 EnclosingDecl->setInvalidDecl();
19800 continue;
19801 } else if (FDTy->isIncompleteArrayType() &&
19802 (Record || isa<ObjCContainerDecl>(Val: EnclosingDecl))) {
19803 if (Record) {
19804 // Flexible array member.
19805 // Microsoft and g++ is more permissive regarding flexible array.
19806 // It will accept flexible array in union and also
19807 // as the sole element of a struct/class.
19808 unsigned DiagID = 0;
19809 if (!Record->isUnion() && !IsLastField) {
19810 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_not_at_end)
19811 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19812 Diag(Loc: (*(i + 1))->getLocation(), DiagID: diag::note_next_field_declaration);
19813 FD->setInvalidDecl();
19814 EnclosingDecl->setInvalidDecl();
19815 continue;
19816 } else if (Record->isUnion())
19817 DiagID = getLangOpts().MicrosoftExt
19818 ? diag::ext_flexible_array_union_ms
19819 : diag::ext_flexible_array_union_gnu;
19820 else if (NumNamedMembers < 1)
19821 DiagID = getLangOpts().MicrosoftExt
19822 ? diag::ext_flexible_array_empty_aggregate_ms
19823 : diag::ext_flexible_array_empty_aggregate_gnu;
19824
19825 if (DiagID)
19826 Diag(Loc: FD->getLocation(), DiagID)
19827 << FD->getDeclName() << Record->getTagKind();
19828 // While the layout of types that contain virtual bases is not specified
19829 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19830 // virtual bases after the derived members. This would make a flexible
19831 // array member declared at the end of an object not adjacent to the end
19832 // of the type.
19833 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19834 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_virtual_base)
19835 << FD->getDeclName() << Record->getTagKind();
19836 if (!getLangOpts().C99)
19837 Diag(Loc: FD->getLocation(), DiagID: diag::ext_c99_flexible_array_member)
19838 << FD->getDeclName() << Record->getTagKind();
19839
19840 // If the element type has a non-trivial destructor, we would not
19841 // implicitly destroy the elements, so disallow it for now.
19842 //
19843 // FIXME: GCC allows this. We should probably either implicitly delete
19844 // the destructor of the containing class, or just allow this.
19845 QualType BaseElem = Context.getBaseElementType(QT: FD->getType());
19846 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19847 Diag(Loc: FD->getLocation(), DiagID: diag::err_flexible_array_has_nontrivial_dtor)
19848 << FD->getDeclName() << FD->getType();
19849 FD->setInvalidDecl();
19850 EnclosingDecl->setInvalidDecl();
19851 continue;
19852 }
19853 // Okay, we have a legal flexible array member at the end of the struct.
19854 Record->setHasFlexibleArrayMember(true);
19855 } else {
19856 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19857 // unless they are followed by another ivar. That check is done
19858 // elsewhere, after synthesized ivars are known.
19859 }
19860 } else if (!FDTy->isDependentType() &&
19861 (LangOpts.HLSL // HLSL allows sizeless builtin types
19862 ? RequireCompleteType(Loc: FD->getLocation(), T: FD->getType(),
19863 DiagID: diag::err_incomplete_type)
19864 : RequireCompleteSizedType(
19865 Loc: FD->getLocation(), T: FD->getType(),
19866 DiagID: diag::err_field_incomplete_or_sizeless))) {
19867 // Incomplete type
19868 FD->setInvalidDecl();
19869 EnclosingDecl->setInvalidDecl();
19870 continue;
19871 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
19872 if (Record && RD->hasFlexibleArrayMember()) {
19873 // A type which contains a flexible array member is considered to be a
19874 // flexible array member.
19875 Record->setHasFlexibleArrayMember(true);
19876 if (!Record->isUnion()) {
19877 // If this is a struct/class and this is not the last element, reject
19878 // it. Note that GCC supports variable sized arrays in the middle of
19879 // structures.
19880 if (!IsLastField)
19881 Diag(Loc: FD->getLocation(), DiagID: diag::ext_variable_sized_type_in_struct)
19882 << FD->getDeclName() << FD->getType();
19883 else {
19884 // We support flexible arrays at the end of structs in
19885 // other structs as an extension.
19886 Diag(Loc: FD->getLocation(), DiagID: diag::ext_flexible_array_in_struct)
19887 << FD->getDeclName();
19888 }
19889 }
19890 }
19891 if (isa<ObjCContainerDecl>(Val: EnclosingDecl) &&
19892 RequireNonAbstractType(Loc: FD->getLocation(), T: FD->getType(),
19893 DiagID: diag::err_abstract_type_in_decl,
19894 Args: AbstractIvarType)) {
19895 // Ivars can not have abstract class types
19896 FD->setInvalidDecl();
19897 }
19898 if (Record && RD->hasObjectMember())
19899 Record->setHasObjectMember(true);
19900 if (Record && RD->hasVolatileMember())
19901 Record->setHasVolatileMember(true);
19902 } else if (FDTy->isObjCObjectType()) {
19903 /// A field cannot be an Objective-c object
19904 Diag(Loc: FD->getLocation(), DiagID: diag::err_statically_allocated_object)
19905 << FixItHint::CreateInsertion(InsertionLoc: FD->getLocation(), Code: "*");
19906 QualType T = Context.getObjCObjectPointerType(OIT: FD->getType());
19907 FD->setType(T);
19908 } else if (Record && Record->isUnion() &&
19909 FD->getType().hasNonTrivialObjCLifetime() &&
19910 getSourceManager().isInSystemHeader(Loc: FD->getLocation()) &&
19911 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19912 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19913 !Context.hasDirectOwnershipQualifier(Ty: FD->getType()))) {
19914 // For backward compatibility, fields of C unions declared in system
19915 // headers that have non-trivial ObjC ownership qualifications are marked
19916 // as unavailable unless the qualifier is explicit and __strong. This can
19917 // break ABI compatibility between programs compiled with ARC and MRR, but
19918 // is a better option than rejecting programs using those unions under
19919 // ARC.
19920 FD->addAttr(A: UnavailableAttr::CreateImplicit(
19921 Ctx&: Context, Message: "", ImplicitReason: UnavailableAttr::IR_ARCFieldWithOwnership,
19922 Range: FD->getLocation()));
19923 } else if (getLangOpts().ObjC &&
19924 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19925 !Record->hasObjectMember()) {
19926 if (FD->getType()->isObjCObjectPointerType() ||
19927 FD->getType().isObjCGCStrong())
19928 Record->setHasObjectMember(true);
19929 else if (Context.getAsArrayType(T: FD->getType())) {
19930 QualType BaseType = Context.getBaseElementType(QT: FD->getType());
19931 if (const auto *RD = BaseType->getAsRecordDecl();
19932 RD && RD->hasObjectMember())
19933 Record->setHasObjectMember(true);
19934 else if (BaseType->isObjCObjectPointerType() ||
19935 BaseType.isObjCGCStrong())
19936 Record->setHasObjectMember(true);
19937 }
19938 }
19939
19940 if (Record && !getLangOpts().CPlusPlus &&
19941 !shouldIgnoreForRecordTriviality(FD)) {
19942 QualType FT = FD->getType();
19943 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19944 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19945 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19946 Record->isUnion())
19947 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19948 }
19949 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19950 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19951 Record->setNonTrivialToPrimitiveCopy(true);
19952 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19953 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19954 }
19955 if (FD->hasAttr<ExplicitInitAttr>())
19956 Record->setHasUninitializedExplicitInitFields(true);
19957 if (FT.isDestructedType()) {
19958 Record->setNonTrivialToPrimitiveDestroy(true);
19959 Record->setParamDestroyedInCallee(true);
19960 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19961 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19962 }
19963
19964 if (const auto *RD = FT->getAsRecordDecl()) {
19965 if (RD->getArgPassingRestrictions() ==
19966 RecordArgPassingKind::CanNeverPassInRegs)
19967 Record->setArgPassingRestrictions(
19968 RecordArgPassingKind::CanNeverPassInRegs);
19969 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
19970 Record->setArgPassingRestrictions(
19971 RecordArgPassingKind::CanNeverPassInRegs);
19972 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
19973 Q && Q.isAddressDiscriminated()) {
19974 Record->setArgPassingRestrictions(
19975 RecordArgPassingKind::CanNeverPassInRegs);
19976 Record->setNonTrivialToPrimitiveCopy(true);
19977 }
19978 }
19979
19980 if (Record && FD->getType().isVolatileQualified())
19981 Record->setHasVolatileMember(true);
19982 bool ReportMSBitfieldStoragePacking =
19983 Record && PreviousField &&
19984 !Diags.isIgnored(DiagID: diag::warn_ms_bitfield_mismatched_storage_packing,
19985 Loc: Record->getLocation());
19986 auto IsNonDependentBitField = [](const FieldDecl *FD) {
19987 return FD->isBitField() && !FD->getType()->isDependentType();
19988 };
19989
19990 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
19991 IsNonDependentBitField(PreviousField)) {
19992 CharUnits FDStorageSize = Context.getTypeSizeInChars(T: FD->getType());
19993 CharUnits PreviousFieldStorageSize =
19994 Context.getTypeSizeInChars(T: PreviousField->getType());
19995 if (FDStorageSize != PreviousFieldStorageSize) {
19996 Diag(Loc: FD->getLocation(),
19997 DiagID: diag::warn_ms_bitfield_mismatched_storage_packing)
19998 << FD << FD->getType() << FDStorageSize.getQuantity()
19999 << PreviousFieldStorageSize.getQuantity();
20000 Diag(Loc: PreviousField->getLocation(),
20001 DiagID: diag::note_ms_bitfield_mismatched_storage_size_previous)
20002 << PreviousField << PreviousField->getType();
20003 }
20004 }
20005 // Keep track of the number of named members.
20006 if (FD->getIdentifier())
20007 ++NumNamedMembers;
20008 }
20009
20010 // Okay, we successfully defined 'Record'.
20011 if (Record) {
20012 bool Completed = false;
20013 if (S) {
20014 Scope *Parent = S->getParent();
20015 if (Parent && Parent->isTypeAliasScope() &&
20016 Parent->isTemplateParamScope())
20017 Record->setInvalidDecl();
20018 }
20019
20020 if (CXXRecord) {
20021 if (!CXXRecord->isInvalidDecl()) {
20022 // Set access bits correctly on the directly-declared conversions.
20023 for (CXXRecordDecl::conversion_iterator
20024 I = CXXRecord->conversion_begin(),
20025 E = CXXRecord->conversion_end(); I != E; ++I)
20026 I.setAccess((*I)->getAccess());
20027 }
20028
20029 // Add any implicitly-declared members to this class.
20030 AddImplicitlyDeclaredMembersToClass(ClassDecl: CXXRecord);
20031
20032 if (!CXXRecord->isDependentType()) {
20033 if (!CXXRecord->isInvalidDecl()) {
20034 // If we have virtual base classes, we may end up finding multiple
20035 // final overriders for a given virtual function. Check for this
20036 // problem now.
20037 if (CXXRecord->getNumVBases()) {
20038 CXXFinalOverriderMap FinalOverriders;
20039 CXXRecord->getFinalOverriders(FinaOverriders&: FinalOverriders);
20040
20041 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20042 MEnd = FinalOverriders.end();
20043 M != MEnd; ++M) {
20044 for (OverridingMethods::iterator SO = M->second.begin(),
20045 SOEnd = M->second.end();
20046 SO != SOEnd; ++SO) {
20047 assert(SO->second.size() > 0 &&
20048 "Virtual function without overriding functions?");
20049 if (SO->second.size() == 1)
20050 continue;
20051
20052 // C++ [class.virtual]p2:
20053 // In a derived class, if a virtual member function of a base
20054 // class subobject has more than one final overrider the
20055 // program is ill-formed.
20056 Diag(Loc: Record->getLocation(), DiagID: diag::err_multiple_final_overriders)
20057 << (const NamedDecl *)M->first << Record;
20058 Diag(Loc: M->first->getLocation(),
20059 DiagID: diag::note_overridden_virtual_function);
20060 for (OverridingMethods::overriding_iterator
20061 OM = SO->second.begin(),
20062 OMEnd = SO->second.end();
20063 OM != OMEnd; ++OM)
20064 Diag(Loc: OM->Method->getLocation(), DiagID: diag::note_final_overrider)
20065 << (const NamedDecl *)M->first << OM->Method->getParent();
20066
20067 Record->setInvalidDecl();
20068 }
20069 }
20070 CXXRecord->completeDefinition(FinalOverriders: &FinalOverriders);
20071 Completed = true;
20072 }
20073 }
20074 ComputeSelectedDestructor(S&: *this, Record: CXXRecord);
20075 ComputeSpecialMemberFunctionsEligiblity(S&: *this, Record: CXXRecord);
20076 }
20077 }
20078
20079 if (!Completed)
20080 Record->completeDefinition();
20081
20082 // Handle attributes before checking the layout.
20083 ProcessDeclAttributeList(S, D: Record, AttrList: Attrs);
20084
20085 // Maybe randomize the record's decls. We automatically randomize a record
20086 // of function pointers, unless it has the "no_randomize_layout" attribute.
20087 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20088 !Record->isRandomized() && !Record->isUnion() &&
20089 (Record->hasAttr<RandomizeLayoutAttr>() ||
20090 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20091 EntirelyFunctionPointers(Record)))) {
20092 SmallVector<Decl *, 32> NewDeclOrdering;
20093 if (randstruct::randomizeStructureLayout(Context, RD: Record,
20094 FinalOrdering&: NewDeclOrdering))
20095 Record->reorderDecls(Decls: NewDeclOrdering);
20096 }
20097
20098 // We may have deferred checking for a deleted destructor. Check now.
20099 if (CXXRecord) {
20100 auto *Dtor = CXXRecord->getDestructor();
20101 if (Dtor && Dtor->isImplicit() &&
20102 ShouldDeleteSpecialMember(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor)) {
20103 CXXRecord->setImplicitDestructorIsDeleted();
20104 SetDeclDeleted(dcl: Dtor, DelLoc: CXXRecord->getLocation());
20105 }
20106 }
20107
20108 if (Record->hasAttrs()) {
20109 CheckAlignasUnderalignment(D: Record);
20110
20111 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20112 checkMSInheritanceAttrOnDefinition(RD: cast<CXXRecordDecl>(Val: Record),
20113 Range: IA->getRange(), BestCase: IA->getBestCase(),
20114 SemanticSpelling: IA->getInheritanceModel());
20115 }
20116
20117 // Check if the structure/union declaration is a type that can have zero
20118 // size in C. For C this is a language extension, for C++ it may cause
20119 // compatibility problems.
20120 bool CheckForZeroSize;
20121 if (!getLangOpts().CPlusPlus) {
20122 CheckForZeroSize = true;
20123 } else {
20124 // For C++ filter out types that cannot be referenced in C code.
20125 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Val: Record);
20126 CheckForZeroSize =
20127 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20128 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20129 CXXRecord->isCLike();
20130 }
20131 if (CheckForZeroSize) {
20132 bool ZeroSize = true;
20133 bool IsEmpty = true;
20134 unsigned NonBitFields = 0;
20135 for (RecordDecl::field_iterator I = Record->field_begin(),
20136 E = Record->field_end();
20137 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20138 IsEmpty = false;
20139 if (I->isUnnamedBitField()) {
20140 if (!I->isZeroLengthBitField())
20141 ZeroSize = false;
20142 } else {
20143 ++NonBitFields;
20144 QualType FieldType = I->getType();
20145 if (FieldType->isIncompleteType() ||
20146 !Context.getTypeSizeInChars(T: FieldType).isZero())
20147 ZeroSize = false;
20148 }
20149 }
20150
20151 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20152 // allowed in C++, but warn if its declaration is inside
20153 // extern "C" block.
20154 if (ZeroSize) {
20155 Diag(Loc: RecLoc, DiagID: getLangOpts().CPlusPlus ?
20156 diag::warn_zero_size_struct_union_in_extern_c :
20157 diag::warn_zero_size_struct_union_compat)
20158 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20159 }
20160
20161 // Structs without named members are extension in C (C99 6.7.2.1p7),
20162 // but are accepted by GCC. In C2y, this became implementation-defined
20163 // (C2y 6.7.3.2p10).
20164 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20165 Diag(Loc: RecLoc, DiagID: IsEmpty ? diag::ext_empty_struct_union
20166 : diag::ext_no_named_members_in_struct_union)
20167 << Record->isUnion();
20168 }
20169 }
20170 } else {
20171 ObjCIvarDecl **ClsFields =
20172 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20173 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Val: EnclosingDecl)) {
20174 ID->setEndOfDefinitionLoc(RBrac);
20175 // Add ivar's to class's DeclContext.
20176 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20177 ClsFields[i]->setLexicalDeclContext(ID);
20178 ID->addDecl(D: ClsFields[i]);
20179 }
20180 // Must enforce the rule that ivars in the base classes may not be
20181 // duplicates.
20182 if (ID->getSuperClass())
20183 ObjC().DiagnoseDuplicateIvars(ID, SID: ID->getSuperClass());
20184 } else if (ObjCImplementationDecl *IMPDecl =
20185 dyn_cast<ObjCImplementationDecl>(Val: EnclosingDecl)) {
20186 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20187 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20188 // Ivar declared in @implementation never belongs to the implementation.
20189 // Only it is in implementation's lexical context.
20190 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20191 ObjC().CheckImplementationIvars(ImpDecl: IMPDecl, Fields: ClsFields, nIvars: RecFields.size(),
20192 Loc: RBrac);
20193 IMPDecl->setIvarLBraceLoc(LBrac);
20194 IMPDecl->setIvarRBraceLoc(RBrac);
20195 } else if (ObjCCategoryDecl *CDecl =
20196 dyn_cast<ObjCCategoryDecl>(Val: EnclosingDecl)) {
20197 // case of ivars in class extension; all other cases have been
20198 // reported as errors elsewhere.
20199 // FIXME. Class extension does not have a LocEnd field.
20200 // CDecl->setLocEnd(RBrac);
20201 // Add ivar's to class extension's DeclContext.
20202 // Diagnose redeclaration of private ivars.
20203 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20204 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20205 if (IDecl) {
20206 if (const ObjCIvarDecl *ClsIvar =
20207 IDecl->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20208 Diag(Loc: ClsFields[i]->getLocation(),
20209 DiagID: diag::err_duplicate_ivar_declaration);
20210 Diag(Loc: ClsIvar->getLocation(), DiagID: diag::note_previous_definition);
20211 continue;
20212 }
20213 for (const auto *Ext : IDecl->known_extensions()) {
20214 if (const ObjCIvarDecl *ClsExtIvar
20215 = Ext->getIvarDecl(Id: ClsFields[i]->getIdentifier())) {
20216 Diag(Loc: ClsFields[i]->getLocation(),
20217 DiagID: diag::err_duplicate_ivar_declaration);
20218 Diag(Loc: ClsExtIvar->getLocation(), DiagID: diag::note_previous_definition);
20219 continue;
20220 }
20221 }
20222 }
20223 ClsFields[i]->setLexicalDeclContext(CDecl);
20224 CDecl->addDecl(D: ClsFields[i]);
20225 }
20226 CDecl->setIvarLBraceLoc(LBrac);
20227 CDecl->setIvarRBraceLoc(RBrac);
20228 }
20229 }
20230 if (Record && !isa<ClassTemplateSpecializationDecl>(Val: Record))
20231 ProcessAPINotes(D: Record);
20232}
20233
20234// Given an integral type, return the next larger integral type
20235// (or a NULL type of no such type exists).
20236static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
20237 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20238 // enum checking below.
20239 assert((T->isIntegralType(Context) ||
20240 T->isEnumeralType()) && "Integral type required!");
20241 const unsigned NumTypes = 4;
20242 QualType SignedIntegralTypes[NumTypes] = {
20243 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20244 };
20245 QualType UnsignedIntegralTypes[NumTypes] = {
20246 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20247 Context.UnsignedLongLongTy
20248 };
20249
20250 unsigned BitWidth = Context.getTypeSize(T);
20251 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20252 : UnsignedIntegralTypes;
20253 for (unsigned I = 0; I != NumTypes; ++I)
20254 if (Context.getTypeSize(T: Types[I]) > BitWidth)
20255 return Types[I];
20256
20257 return QualType();
20258}
20259
20260EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
20261 EnumConstantDecl *LastEnumConst,
20262 SourceLocation IdLoc,
20263 IdentifierInfo *Id,
20264 Expr *Val) {
20265 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20266 llvm::APSInt EnumVal(IntWidth);
20267 QualType EltTy;
20268
20269 if (Val && DiagnoseUnexpandedParameterPack(E: Val, UPPC: UPPC_EnumeratorValue))
20270 Val = nullptr;
20271
20272 if (Val)
20273 Val = DefaultLvalueConversion(E: Val).get();
20274
20275 if (Val) {
20276 if (Enum->isDependentType() || Val->isTypeDependent() ||
20277 Val->containsErrors())
20278 EltTy = Context.DependentTy;
20279 else {
20280 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20281 // underlying type, but do allow it in all other contexts.
20282 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20283 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20284 // constant-expression in the enumerator-definition shall be a converted
20285 // constant expression of the underlying type.
20286 EltTy = Enum->getIntegerType();
20287 ExprResult Converted = CheckConvertedConstantExpression(
20288 From: Val, T: EltTy, Value&: EnumVal, CCE: CCEKind::Enumerator);
20289 if (Converted.isInvalid())
20290 Val = nullptr;
20291 else
20292 Val = Converted.get();
20293 } else if (!Val->isValueDependent() &&
20294 !(Val = VerifyIntegerConstantExpression(E: Val, Result: &EnumVal,
20295 CanFold: AllowFoldKind::Allow)
20296 .get())) {
20297 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20298 } else {
20299 if (Enum->isComplete()) {
20300 EltTy = Enum->getIntegerType();
20301
20302 // In Obj-C and Microsoft mode, require the enumeration value to be
20303 // representable in the underlying type of the enumeration. In C++11,
20304 // we perform a non-narrowing conversion as part of converted constant
20305 // expression checking.
20306 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20307 if (Context.getTargetInfo()
20308 .getTriple()
20309 .isWindowsMSVCEnvironment()) {
20310 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_too_large) << EltTy;
20311 } else {
20312 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_too_large) << EltTy;
20313 }
20314 }
20315
20316 // Cast to the underlying type.
20317 Val = ImpCastExprToType(E: Val, Type: EltTy,
20318 CK: EltTy->isBooleanType() ? CK_IntegralToBoolean
20319 : CK_IntegralCast)
20320 .get();
20321 } else if (getLangOpts().CPlusPlus) {
20322 // C++11 [dcl.enum]p5:
20323 // If the underlying type is not fixed, the type of each enumerator
20324 // is the type of its initializing value:
20325 // - If an initializer is specified for an enumerator, the
20326 // initializing value has the same type as the expression.
20327 EltTy = Val->getType();
20328 } else {
20329 // C99 6.7.2.2p2:
20330 // The expression that defines the value of an enumeration constant
20331 // shall be an integer constant expression that has a value
20332 // representable as an int.
20333
20334 // Complain if the value is not representable in an int.
20335 if (!Context.isRepresentableIntegerValue(Value&: EnumVal, T: Context.IntTy)) {
20336 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20337 ? diag::warn_c17_compat_enum_value_not_int
20338 : diag::ext_c23_enum_value_not_int)
20339 << 0 << toString(I: EnumVal, Radix: 10) << Val->getSourceRange()
20340 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20341 } else if (!Context.hasSameType(T1: Val->getType(), T2: Context.IntTy)) {
20342 // Force the type of the expression to 'int'.
20343 Val = ImpCastExprToType(E: Val, Type: Context.IntTy, CK: CK_IntegralCast).get();
20344 }
20345 EltTy = Val->getType();
20346 }
20347 }
20348 }
20349 }
20350
20351 if (!Val) {
20352 if (Enum->isDependentType())
20353 EltTy = Context.DependentTy;
20354 else if (!LastEnumConst) {
20355 // C++0x [dcl.enum]p5:
20356 // If the underlying type is not fixed, the type of each enumerator
20357 // is the type of its initializing value:
20358 // - If no initializer is specified for the first enumerator, the
20359 // initializing value has an unspecified integral type.
20360 //
20361 // GCC uses 'int' for its unspecified integral type, as does
20362 // C99 6.7.2.2p3.
20363 if (Enum->isFixed()) {
20364 EltTy = Enum->getIntegerType();
20365 }
20366 else {
20367 EltTy = Context.IntTy;
20368 }
20369 } else {
20370 // Assign the last value + 1.
20371 EnumVal = LastEnumConst->getInitVal();
20372 ++EnumVal;
20373 EltTy = LastEnumConst->getType();
20374
20375 // Check for overflow on increment.
20376 if (EnumVal < LastEnumConst->getInitVal()) {
20377 // C++0x [dcl.enum]p5:
20378 // If the underlying type is not fixed, the type of each enumerator
20379 // is the type of its initializing value:
20380 //
20381 // - Otherwise the type of the initializing value is the same as
20382 // the type of the initializing value of the preceding enumerator
20383 // unless the incremented value is not representable in that type,
20384 // in which case the type is an unspecified integral type
20385 // sufficient to contain the incremented value. If no such type
20386 // exists, the program is ill-formed.
20387 QualType T = getNextLargerIntegralType(Context, T: EltTy);
20388 if (T.isNull() || Enum->isFixed()) {
20389 // There is no integral type larger enough to represent this
20390 // value. Complain, then allow the value to wrap around.
20391 EnumVal = LastEnumConst->getInitVal();
20392 EnumVal = EnumVal.zext(width: EnumVal.getBitWidth() * 2);
20393 ++EnumVal;
20394 if (Enum->isFixed())
20395 // When the underlying type is fixed, this is ill-formed.
20396 Diag(Loc: IdLoc, DiagID: diag::err_enumerator_wrapped)
20397 << toString(I: EnumVal, Radix: 10)
20398 << EltTy;
20399 else
20400 Diag(Loc: IdLoc, DiagID: diag::ext_enumerator_increment_too_large)
20401 << toString(I: EnumVal, Radix: 10);
20402 } else {
20403 EltTy = T;
20404 }
20405
20406 // Retrieve the last enumerator's value, extent that type to the
20407 // type that is supposed to be large enough to represent the incremented
20408 // value, then increment.
20409 EnumVal = LastEnumConst->getInitVal();
20410 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20411 EnumVal = EnumVal.zextOrTrunc(width: Context.getIntWidth(T: EltTy));
20412 ++EnumVal;
20413
20414 // If we're not in C++, diagnose the overflow of enumerator values,
20415 // which in C99 means that the enumerator value is not representable in
20416 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20417 // are representable in some larger integral type and we allow it in
20418 // older language modes as an extension.
20419 // Exclude fixed enumerators since they are diagnosed with an error for
20420 // this case.
20421 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20422 Diag(Loc: IdLoc, DiagID: getLangOpts().C23
20423 ? diag::warn_c17_compat_enum_value_not_int
20424 : diag::ext_c23_enum_value_not_int)
20425 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20426 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20427 !Context.isRepresentableIntegerValue(Value&: EnumVal, T: EltTy)) {
20428 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20429 Diag(Loc: IdLoc, DiagID: getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20430 : diag::ext_c23_enum_value_not_int)
20431 << 1 << toString(I: EnumVal, Radix: 10) << 1;
20432 }
20433 }
20434 }
20435
20436 if (!EltTy->isDependentType()) {
20437 // Make the enumerator value match the signedness and size of the
20438 // enumerator's type.
20439 EnumVal = EnumVal.extOrTrunc(width: Context.getIntWidth(T: EltTy));
20440 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20441 }
20442
20443 return EnumConstantDecl::Create(C&: Context, DC: Enum, L: IdLoc, Id, T: EltTy,
20444 E: Val, V: EnumVal);
20445}
20446
20447SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
20448 SourceLocation IILoc) {
20449 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20450 !getLangOpts().CPlusPlus)
20451 return SkipBodyInfo();
20452
20453 // We have an anonymous enum definition. Look up the first enumerator to
20454 // determine if we should merge the definition with an existing one and
20455 // skip the body.
20456 NamedDecl *PrevDecl = LookupSingleName(S, Name: II, Loc: IILoc, NameKind: LookupOrdinaryName,
20457 Redecl: forRedeclarationInCurContext());
20458 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(Val: PrevDecl);
20459 if (!PrevECD)
20460 return SkipBodyInfo();
20461
20462 EnumDecl *PrevED = cast<EnumDecl>(Val: PrevECD->getDeclContext());
20463 NamedDecl *Hidden;
20464 if (!PrevED->getDeclName() && !hasVisibleDefinition(D: PrevED, Suggested: &Hidden)) {
20465 SkipBodyInfo Skip;
20466 Skip.Previous = Hidden;
20467 return Skip;
20468 }
20469
20470 return SkipBodyInfo();
20471}
20472
20473Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20474 SourceLocation IdLoc, IdentifierInfo *Id,
20475 const ParsedAttributesView &Attrs,
20476 SourceLocation EqualLoc, Expr *Val,
20477 SkipBodyInfo *SkipBody) {
20478 EnumDecl *TheEnumDecl = cast<EnumDecl>(Val: theEnumDecl);
20479 EnumConstantDecl *LastEnumConst =
20480 cast_or_null<EnumConstantDecl>(Val: lastEnumConst);
20481
20482 // The scope passed in may not be a decl scope. Zip up the scope tree until
20483 // we find one that is.
20484 S = getNonFieldDeclScope(S);
20485
20486 // Verify that there isn't already something declared with this name in this
20487 // scope.
20488 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20489 RedeclarationKind::ForVisibleRedeclaration);
20490 LookupName(R, S);
20491 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20492
20493 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20494 // Maybe we will complain about the shadowed template parameter.
20495 DiagnoseTemplateParameterShadow(Loc: IdLoc, PrevDecl);
20496 // Just pretend that we didn't see the previous declaration.
20497 PrevDecl = nullptr;
20498 }
20499
20500 // C++ [class.mem]p15:
20501 // If T is the name of a class, then each of the following shall have a name
20502 // different from T:
20503 // - every enumerator of every member of class T that is an unscoped
20504 // enumerated type
20505 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20506 DiagnoseClassNameShadow(DC: TheEnumDecl->getDeclContext(),
20507 NameInfo: DeclarationNameInfo(Id, IdLoc)))
20508 return nullptr;
20509
20510 EnumConstantDecl *New =
20511 CheckEnumConstant(Enum: TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20512 if (!New)
20513 return nullptr;
20514
20515 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20516 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(Val: PrevDecl)) {
20517 // Check for other kinds of shadowing not already handled.
20518 CheckShadow(D: New, ShadowedDecl: PrevDecl, R);
20519 }
20520
20521 // When in C++, we may get a TagDecl with the same name; in this case the
20522 // enum constant will 'hide' the tag.
20523 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20524 "Received TagDecl when not in C++!");
20525 if (!isa<TagDecl>(Val: PrevDecl) && isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
20526 if (isa<EnumConstantDecl>(Val: PrevDecl))
20527 Diag(Loc: IdLoc, DiagID: diag::err_redefinition_of_enumerator) << Id;
20528 else
20529 Diag(Loc: IdLoc, DiagID: diag::err_redefinition) << Id;
20530 notePreviousDefinition(Old: PrevDecl, New: IdLoc);
20531 return nullptr;
20532 }
20533 }
20534
20535 // Process attributes.
20536 ProcessDeclAttributeList(S, D: New, AttrList: Attrs);
20537 AddPragmaAttributes(S, D: New);
20538 ProcessAPINotes(D: New);
20539
20540 // Register this decl in the current scope stack.
20541 New->setAccess(TheEnumDecl->getAccess());
20542 PushOnScopeChains(D: New, S);
20543
20544 ActOnDocumentableDecl(D: New);
20545
20546 return New;
20547}
20548
20549// Returns true when the enum initial expression does not trigger the
20550// duplicate enum warning. A few common cases are exempted as follows:
20551// Element2 = Element1
20552// Element2 = Element1 + 1
20553// Element2 = Element1 - 1
20554// Where Element2 and Element1 are from the same enum.
20555static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
20556 Expr *InitExpr = ECD->getInitExpr();
20557 if (!InitExpr)
20558 return true;
20559 InitExpr = InitExpr->IgnoreImpCasts();
20560
20561 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: InitExpr)) {
20562 if (!BO->isAdditiveOp())
20563 return true;
20564 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: BO->getRHS());
20565 if (!IL)
20566 return true;
20567 if (IL->getValue() != 1)
20568 return true;
20569
20570 InitExpr = BO->getLHS();
20571 }
20572
20573 // This checks if the elements are from the same enum.
20574 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: InitExpr);
20575 if (!DRE)
20576 return true;
20577
20578 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl());
20579 if (!EnumConstant)
20580 return true;
20581
20582 if (cast<EnumDecl>(Val: TagDecl::castFromDeclContext(DC: ECD->getDeclContext())) !=
20583 Enum)
20584 return true;
20585
20586 return false;
20587}
20588
20589// Emits a warning when an element is implicitly set a value that
20590// a previous element has already been set to.
20591static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
20592 EnumDecl *Enum, QualType EnumType) {
20593 // Avoid anonymous enums
20594 if (!Enum->getIdentifier())
20595 return;
20596
20597 // Only check for small enums.
20598 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20599 return;
20600
20601 if (S.Diags.isIgnored(DiagID: diag::warn_duplicate_enum_values, Loc: Enum->getLocation()))
20602 return;
20603
20604 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20605 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20606
20607 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20608
20609 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20610 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20611
20612 // Use int64_t as a key to avoid needing special handling for map keys.
20613 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20614 llvm::APSInt Val = D->getInitVal();
20615 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20616 };
20617
20618 DuplicatesVector DupVector;
20619 ValueToVectorMap EnumMap;
20620
20621 // Populate the EnumMap with all values represented by enum constants without
20622 // an initializer.
20623 for (auto *Element : Elements) {
20624 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: Element);
20625
20626 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20627 // this constant. Skip this enum since it may be ill-formed.
20628 if (!ECD) {
20629 return;
20630 }
20631
20632 // Constants with initializers are handled in the next loop.
20633 if (ECD->getInitExpr())
20634 continue;
20635
20636 // Duplicate values are handled in the next loop.
20637 EnumMap.insert(x: {EnumConstantToKey(ECD), ECD});
20638 }
20639
20640 if (EnumMap.size() == 0)
20641 return;
20642
20643 // Create vectors for any values that has duplicates.
20644 for (auto *Element : Elements) {
20645 // The last loop returned if any constant was null.
20646 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Val: Element);
20647 if (!ValidDuplicateEnum(ECD, Enum))
20648 continue;
20649
20650 auto Iter = EnumMap.find(x: EnumConstantToKey(ECD));
20651 if (Iter == EnumMap.end())
20652 continue;
20653
20654 DeclOrVector& Entry = Iter->second;
20655 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Val&: Entry)) {
20656 // Ensure constants are different.
20657 if (D == ECD)
20658 continue;
20659
20660 // Create new vector and push values onto it.
20661 auto Vec = std::make_unique<ECDVector>();
20662 Vec->push_back(Elt: D);
20663 Vec->push_back(Elt: ECD);
20664
20665 // Update entry to point to the duplicates vector.
20666 Entry = Vec.get();
20667
20668 // Store the vector somewhere we can consult later for quick emission of
20669 // diagnostics.
20670 DupVector.emplace_back(Args: std::move(Vec));
20671 continue;
20672 }
20673
20674 ECDVector *Vec = cast<ECDVector *>(Val&: Entry);
20675 // Make sure constants are not added more than once.
20676 if (*Vec->begin() == ECD)
20677 continue;
20678
20679 Vec->push_back(Elt: ECD);
20680 }
20681
20682 // Emit diagnostics.
20683 for (const auto &Vec : DupVector) {
20684 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20685
20686 // Emit warning for one enum constant.
20687 auto *FirstECD = Vec->front();
20688 S.Diag(Loc: FirstECD->getLocation(), DiagID: diag::warn_duplicate_enum_values)
20689 << FirstECD << toString(I: FirstECD->getInitVal(), Radix: 10)
20690 << FirstECD->getSourceRange();
20691
20692 // Emit one note for each of the remaining enum constants with
20693 // the same value.
20694 for (auto *ECD : llvm::drop_begin(RangeOrContainer&: *Vec))
20695 S.Diag(Loc: ECD->getLocation(), DiagID: diag::note_duplicate_element)
20696 << ECD << toString(I: ECD->getInitVal(), Radix: 10)
20697 << ECD->getSourceRange();
20698 }
20699}
20700
20701bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20702 bool AllowMask) const {
20703 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20704 assert(ED->isCompleteDefinition() && "expected enum definition");
20705
20706 auto R = FlagBitsCache.try_emplace(Key: ED);
20707 llvm::APInt &FlagBits = R.first->second;
20708
20709 if (R.second) {
20710 for (auto *E : ED->enumerators()) {
20711 const auto &EVal = E->getInitVal();
20712 // Only single-bit enumerators introduce new flag values.
20713 if (EVal.isPowerOf2())
20714 FlagBits = FlagBits.zext(width: EVal.getBitWidth()) | EVal;
20715 }
20716 }
20717
20718 // A value is in a flag enum if either its bits are a subset of the enum's
20719 // flag bits (the first condition) or we are allowing masks and the same is
20720 // true of its complement (the second condition). When masks are allowed, we
20721 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20722 //
20723 // While it's true that any value could be used as a mask, the assumption is
20724 // that a mask will have all of the insignificant bits set. Anything else is
20725 // likely a logic error.
20726 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(width: Val.getBitWidth());
20727 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20728}
20729
20730// Emits a warning when a suspicious comparison operator is used along side
20731// binary operators in enum initializers.
20732static void CheckForComparisonInEnumInitializer(SemaBase &Sema,
20733 const EnumDecl *Enum) {
20734 bool HasBitwiseOp = false;
20735 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20736
20737 // Iterate over all the enum values, gather suspisious comparison ops and
20738 // whether any enum initialisers contain a binary operator.
20739 for (const auto *ECD : Enum->enumerators()) {
20740 const Expr *InitExpr = ECD->getInitExpr();
20741 if (!InitExpr)
20742 continue;
20743
20744 const Expr *E = InitExpr->IgnoreParenImpCasts();
20745
20746 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
20747 BinaryOperatorKind Op = BinOp->getOpcode();
20748
20749 // Check for bitwise ops (<<, >>, &, |)
20750 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20751 HasBitwiseOp = true;
20752 } else if (Op == BO_LT || Op == BO_GT) {
20753 // Check for the typo pattern (Comparison < or >)
20754 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20755 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(Val: LHS)) {
20756 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20757 if (IntLiteral->getValue() == 1)
20758 SuspiciousCompares.push_back(Elt: BinOp);
20759 }
20760 }
20761 }
20762 }
20763
20764 // If we found a bitwise op and some sus compares, iterate over the compares
20765 // and warn.
20766 if (HasBitwiseOp) {
20767 for (const auto *BinOp : SuspiciousCompares) {
20768 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20769 ? BinaryOperator::getOpcodeStr(Op: BO_Shl)
20770 : BinaryOperator::getOpcodeStr(Op: BO_Shr);
20771 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20772
20773 Sema.Diag(Loc: OperatorLoc, DiagID: diag::warn_comparison_in_enum_initializer)
20774 << BinOp->getOpcodeStr() << SuggestedOp;
20775
20776 Sema.Diag(Loc: OperatorLoc, DiagID: diag::note_enum_compare_typo_suggest)
20777 << SuggestedOp
20778 << FixItHint::CreateReplacement(RemoveRange: OperatorLoc, Code: SuggestedOp);
20779 }
20780 }
20781}
20782
20783void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20784 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20785 const ParsedAttributesView &Attrs) {
20786 EnumDecl *Enum = cast<EnumDecl>(Val: EnumDeclX);
20787 CanQualType EnumType = Context.getCanonicalTagType(TD: Enum);
20788
20789 ProcessDeclAttributeList(S, D: Enum, AttrList: Attrs);
20790 ProcessAPINotes(D: Enum);
20791
20792 if (Enum->isDependentType()) {
20793 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20794 EnumConstantDecl *ECD =
20795 cast_or_null<EnumConstantDecl>(Val: Elements[i]);
20796 if (!ECD) continue;
20797
20798 ECD->setType(EnumType);
20799 }
20800
20801 Enum->completeDefinition(NewType: Context.DependentTy, PromotionType: Context.DependentTy, NumPositiveBits: 0, NumNegativeBits: 0);
20802 return;
20803 }
20804
20805 // Verify that all the values are okay, compute the size of the values, and
20806 // reverse the list.
20807 unsigned NumNegativeBits = 0;
20808 unsigned NumPositiveBits = 0;
20809 bool MembersRepresentableByInt =
20810 Context.computeEnumBits(EnumConstants: Elements, NumNegativeBits, NumPositiveBits);
20811
20812 // Figure out the type that should be used for this enum.
20813 QualType BestType;
20814 unsigned BestWidth;
20815
20816 // C++0x N3000 [conv.prom]p3:
20817 // An rvalue of an unscoped enumeration type whose underlying
20818 // type is not fixed can be converted to an rvalue of the first
20819 // of the following types that can represent all the values of
20820 // the enumeration: int, unsigned int, long int, unsigned long
20821 // int, long long int, or unsigned long long int.
20822 // C99 6.4.4.3p2:
20823 // An identifier declared as an enumeration constant has type int.
20824 // The C99 rule is modified by C23.
20825 QualType BestPromotionType;
20826
20827 bool Packed = Enum->hasAttr<PackedAttr>();
20828 // -fshort-enums is the equivalent to specifying the packed attribute on all
20829 // enum definitions.
20830 if (LangOpts.ShortEnums)
20831 Packed = true;
20832
20833 // If the enum already has a type because it is fixed or dictated by the
20834 // target, promote that type instead of analyzing the enumerators.
20835 if (Enum->isComplete()) {
20836 BestType = Enum->getIntegerType();
20837 if (Context.isPromotableIntegerType(T: BestType))
20838 BestPromotionType = Context.getPromotedIntegerType(PromotableType: BestType);
20839 else
20840 BestPromotionType = BestType;
20841
20842 BestWidth = Context.getIntWidth(T: BestType);
20843 } else {
20844 bool EnumTooLarge = Context.computeBestEnumTypes(
20845 IsPacked: Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20846 BestWidth = Context.getIntWidth(T: BestType);
20847 if (EnumTooLarge)
20848 Diag(Loc: Enum->getLocation(), DiagID: diag::ext_enum_too_large);
20849 }
20850
20851 // Loop over all of the enumerator constants, changing their types to match
20852 // the type of the enum if needed.
20853 for (auto *D : Elements) {
20854 auto *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20855 if (!ECD) continue; // Already issued a diagnostic.
20856
20857 // C99 says the enumerators have int type, but we allow, as an
20858 // extension, the enumerators to be larger than int size. If each
20859 // enumerator value fits in an int, type it as an int, otherwise type it the
20860 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20861 // that X has type 'int', not 'unsigned'.
20862
20863 // Determine whether the value fits into an int.
20864 llvm::APSInt InitVal = ECD->getInitVal();
20865
20866 // If it fits into an integer type, force it. Otherwise force it to match
20867 // the enum decl type.
20868 QualType NewTy;
20869 unsigned NewWidth;
20870 bool NewSign;
20871 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20872 MembersRepresentableByInt) {
20873 // C23 6.7.3.3.3p15:
20874 // The enumeration member type for an enumerated type without fixed
20875 // underlying type upon completion is:
20876 // - int if all the values of the enumeration are representable as an
20877 // int; or,
20878 // - the enumerated type
20879 NewTy = Context.IntTy;
20880 NewWidth = Context.getTargetInfo().getIntWidth();
20881 NewSign = true;
20882 } else if (ECD->getType() == BestType) {
20883 // Already the right type!
20884 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
20885 // C++ [dcl.enum]p4: Following the closing brace of an
20886 // enum-specifier, each enumerator has the type of its
20887 // enumeration.
20888 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20889 // with fixed underlying type is the enumerated type.
20890 ECD->setType(EnumType);
20891 continue;
20892 } else {
20893 NewTy = BestType;
20894 NewWidth = BestWidth;
20895 NewSign = BestType->isSignedIntegerOrEnumerationType();
20896 }
20897
20898 // Adjust the APSInt value.
20899 InitVal = InitVal.extOrTrunc(width: NewWidth);
20900 InitVal.setIsSigned(NewSign);
20901 ECD->setInitVal(C: Context, V: InitVal);
20902
20903 // Adjust the Expr initializer and type.
20904 if (ECD->getInitExpr() &&
20905 !Context.hasSameType(T1: NewTy, T2: ECD->getInitExpr()->getType()))
20906 ECD->setInitExpr(ImplicitCastExpr::Create(
20907 Context, T: NewTy, Kind: CK_IntegralCast, Operand: ECD->getInitExpr(),
20908 /*base paths*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()));
20909 if (getLangOpts().CPlusPlus ||
20910 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
20911 // C++ [dcl.enum]p4: Following the closing brace of an
20912 // enum-specifier, each enumerator has the type of its
20913 // enumeration.
20914 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20915 // with fixed underlying type is the enumerated type.
20916 ECD->setType(EnumType);
20917 else
20918 ECD->setType(NewTy);
20919 }
20920
20921 Enum->completeDefinition(NewType: BestType, PromotionType: BestPromotionType,
20922 NumPositiveBits, NumNegativeBits);
20923
20924 CheckForDuplicateEnumValues(S&: *this, Elements, Enum, EnumType);
20925 CheckForComparisonInEnumInitializer(Sema&: *this, Enum);
20926
20927 if (Enum->isClosedFlag()) {
20928 for (Decl *D : Elements) {
20929 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Val: D);
20930 if (!ECD) continue; // Already issued a diagnostic.
20931
20932 llvm::APSInt InitVal = ECD->getInitVal();
20933 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20934 !IsValueInFlagEnum(ED: Enum, Val: InitVal, AllowMask: true))
20935 Diag(Loc: ECD->getLocation(), DiagID: diag::warn_flag_enum_constant_out_of_range)
20936 << ECD << Enum;
20937 }
20938 }
20939
20940 // Now that the enum type is defined, ensure it's not been underaligned.
20941 if (Enum->hasAttrs())
20942 CheckAlignasUnderalignment(D: Enum);
20943}
20944
20945Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, SourceLocation StartLoc,
20946 SourceLocation EndLoc) {
20947
20948 FileScopeAsmDecl *New =
20949 FileScopeAsmDecl::Create(C&: Context, DC: CurContext, Str: expr, AsmLoc: StartLoc, RParenLoc: EndLoc);
20950 CurContext->addDecl(D: New);
20951 return New;
20952}
20953
20954TopLevelStmtDecl *Sema::ActOnStartTopLevelStmtDecl(Scope *S) {
20955 auto *New = TopLevelStmtDecl::Create(C&: Context, /*Statement=*/nullptr);
20956 CurContext->addDecl(D: New);
20957 PushDeclContext(S, DC: New);
20958 PushFunctionScope();
20959 PushCompoundScope(IsStmtExpr: false);
20960 return New;
20961}
20962
20963void Sema::ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement) {
20964 if (Statement)
20965 D->setStmt(Statement);
20966 PopCompoundScope();
20967 PopFunctionScopeInfo();
20968 PopDeclContext();
20969}
20970
20971void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20972 IdentifierInfo* AliasName,
20973 SourceLocation PragmaLoc,
20974 SourceLocation NameLoc,
20975 SourceLocation AliasNameLoc) {
20976 NamedDecl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc,
20977 NameKind: LookupOrdinaryName);
20978 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20979 AttributeCommonInfo::Form::Pragma());
20980 AsmLabelAttr *Attr =
20981 AsmLabelAttr::CreateImplicit(Ctx&: Context, Label: AliasName->getName(), CommonInfo: Info);
20982
20983 // If a declaration that:
20984 // 1) declares a function or a variable
20985 // 2) has external linkage
20986 // already exists, add a label attribute to it.
20987 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
20988 if (isDeclExternC(D: PrevDecl))
20989 PrevDecl->addAttr(A: Attr);
20990 else
20991 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::warn_redefine_extname_not_applied)
20992 << /*Variable*/(isa<FunctionDecl>(Val: PrevDecl) ? 0 : 1) << PrevDecl;
20993 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20994 } else
20995 (void)ExtnameUndeclaredIdentifiers.insert(KV: std::make_pair(x&: Name, y&: Attr));
20996}
20997
20998void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20999 SourceLocation PragmaLoc,
21000 SourceLocation NameLoc) {
21001 Decl *PrevDecl = LookupSingleName(S: TUScope, Name, Loc: NameLoc, NameKind: LookupOrdinaryName);
21002
21003 if (PrevDecl) {
21004 PrevDecl->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: PragmaLoc));
21005 } else {
21006 (void)WeakUndeclaredIdentifiers[Name].insert(X: WeakInfo(nullptr, NameLoc));
21007 }
21008}
21009
21010void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
21011 IdentifierInfo* AliasName,
21012 SourceLocation PragmaLoc,
21013 SourceLocation NameLoc,
21014 SourceLocation AliasNameLoc) {
21015 Decl *PrevDecl = LookupSingleName(S: TUScope, Name: AliasName, Loc: AliasNameLoc,
21016 NameKind: LookupOrdinaryName);
21017 WeakInfo W = WeakInfo(Name, NameLoc);
21018
21019 if (PrevDecl && (isa<FunctionDecl>(Val: PrevDecl) || isa<VarDecl>(Val: PrevDecl))) {
21020 if (!PrevDecl->hasAttr<AliasAttr>())
21021 if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: PrevDecl))
21022 DeclApplyPragmaWeak(S: TUScope, ND, W);
21023 } else {
21024 (void)WeakUndeclaredIdentifiers[AliasName].insert(X: W);
21025 }
21026}
21027
21028Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
21029 bool Final) {
21030 assert(FD && "Expected non-null FunctionDecl");
21031
21032 // SYCL functions can be template, so we check if they have appropriate
21033 // attribute prior to checking if it is a template.
21034 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
21035 return FunctionEmissionStatus::Emitted;
21036
21037 // Templates are emitted when they're instantiated.
21038 if (FD->isDependentContext())
21039 return FunctionEmissionStatus::TemplateDiscarded;
21040
21041 // Check whether this function is an externally visible definition.
21042 auto IsEmittedForExternalSymbol = [this, FD]() {
21043 // We have to check the GVA linkage of the function's *definition* -- if we
21044 // only have a declaration, we don't know whether or not the function will
21045 // be emitted, because (say) the definition could include "inline".
21046 const FunctionDecl *Def = FD->getDefinition();
21047
21048 // We can't compute linkage when we skip function bodies.
21049 return Def && !Def->hasSkippedBody() &&
21050 !isDiscardableGVALinkage(
21051 L: getASTContext().GetGVALinkageForFunction(FD: Def));
21052 };
21053
21054 if (LangOpts.OpenMPIsTargetDevice) {
21055 // In OpenMP device mode we will not emit host only functions, or functions
21056 // we don't need due to their linkage.
21057 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21058 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21059 // DevTy may be changed later by
21060 // #pragma omp declare target to(*) device_type(*).
21061 // Therefore DevTy having no value does not imply host. The emission status
21062 // will be checked again at the end of compilation unit with Final = true.
21063 if (DevTy)
21064 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21065 return FunctionEmissionStatus::OMPDiscarded;
21066 // If we have an explicit value for the device type, or we are in a target
21067 // declare context, we need to emit all extern and used symbols.
21068 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21069 if (IsEmittedForExternalSymbol())
21070 return FunctionEmissionStatus::Emitted;
21071 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21072 // we'll omit it.
21073 if (Final)
21074 return FunctionEmissionStatus::OMPDiscarded;
21075 } else if (LangOpts.OpenMP > 45) {
21076 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21077 // function. In 5.0, no_host was introduced which might cause a function to
21078 // be omitted.
21079 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21080 OMPDeclareTargetDeclAttr::getDeviceType(VD: FD->getCanonicalDecl());
21081 if (DevTy)
21082 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21083 return FunctionEmissionStatus::OMPDiscarded;
21084 }
21085
21086 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21087 return FunctionEmissionStatus::Emitted;
21088
21089 if (LangOpts.CUDA) {
21090 // When compiling for device, host functions are never emitted. Similarly,
21091 // when compiling for host, device and global functions are never emitted.
21092 // (Technically, we do emit a host-side stub for global functions, but this
21093 // doesn't count for our purposes here.)
21094 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: FD);
21095 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21096 return FunctionEmissionStatus::CUDADiscarded;
21097 if (!LangOpts.CUDAIsDevice &&
21098 (T == CUDAFunctionTarget::Device || T == CUDAFunctionTarget::Global))
21099 return FunctionEmissionStatus::CUDADiscarded;
21100
21101 if (IsEmittedForExternalSymbol())
21102 return FunctionEmissionStatus::Emitted;
21103
21104 // If FD is a virtual destructor of an explicit instantiation
21105 // of a template class, return Emitted.
21106 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: FD)) {
21107 if (Destructor->isVirtual()) {
21108 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
21109 Val: Destructor->getParent())) {
21110 TemplateSpecializationKind TSK =
21111 Spec->getTemplateSpecializationKind();
21112 if (TSK == TSK_ExplicitInstantiationDeclaration ||
21113 TSK == TSK_ExplicitInstantiationDefinition)
21114 return FunctionEmissionStatus::Emitted;
21115 }
21116 }
21117 }
21118 }
21119
21120 // Otherwise, the function is known-emitted if it's in our set of
21121 // known-emitted functions.
21122 return FunctionEmissionStatus::Unknown;
21123}
21124
21125bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
21126 // Host-side references to a __global__ function refer to the stub, so the
21127 // function itself is never emitted and therefore should not be marked.
21128 // If we have host fn calls kernel fn calls host+device, the HD function
21129 // does not get instantiated on the host. We model this by omitting at the
21130 // call to the kernel from the callgraph. This ensures that, when compiling
21131 // for host, only HD functions actually called from the host get marked as
21132 // known-emitted.
21133 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21134 CUDA().IdentifyTarget(D: Callee) == CUDAFunctionTarget::Global;
21135}
21136
21137bool Sema::isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
21138 bool &Visible) {
21139 Visible = hasVisibleDefinition(D, Suggested);
21140 // The redefinition of D in the **current** TU is allowed if D is invisible or
21141 // D is defined in the global module of other module units. We didn't check if
21142 // it is in global module as, we'll check the redefinition in named module
21143 // later with better diagnostic message.
21144 return D->isInAnotherModuleUnit() || !Visible;
21145}
21146