[Flang] remove whole-archive option for AIX linker (#76039)
[llvm-project.git] / clang / lib / Sema / SemaDecl.cpp
blobffbe317d559995359c820064dacc376366c76be8
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.
11 //===----------------------------------------------------------------------===//
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/CommentDiagnostic.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.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/HLSLRuntime.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
40 #include "clang/Sema/CXXFieldCollector.h"
41 #include "clang/Sema/DeclSpec.h"
42 #include "clang/Sema/DelayedDiagnostic.h"
43 #include "clang/Sema/Initialization.h"
44 #include "clang/Sema/Lookup.h"
45 #include "clang/Sema/ParsedTemplate.h"
46 #include "clang/Sema/Scope.h"
47 #include "clang/Sema/ScopeInfo.h"
48 #include "clang/Sema/SemaInternal.h"
49 #include "clang/Sema/Template.h"
50 #include "llvm/ADT/SmallString.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/TargetParser/Triple.h"
53 #include <algorithm>
54 #include <cstring>
55 #include <functional>
56 #include <optional>
57 #include <unordered_map>
59 using namespace clang;
60 using namespace sema;
62 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
63 if (OwnedType) {
64 Decl *Group[2] = { OwnedType, Ptr };
65 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
68 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
71 namespace {
73 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
74 public:
75 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
76 bool AllowTemplates = false,
77 bool AllowNonTemplates = true)
78 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
79 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
80 WantExpressionKeywords = false;
81 WantCXXNamedCasts = false;
82 WantRemainingKeywords = false;
85 bool ValidateCandidate(const TypoCorrection &candidate) override {
86 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
87 if (!AllowInvalidDecl && ND->isInvalidDecl())
88 return false;
90 if (getAsTypeTemplateDecl(ND))
91 return AllowTemplates;
93 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
94 if (!IsType)
95 return false;
97 if (AllowNonTemplates)
98 return true;
100 // An injected-class-name of a class template (specialization) is valid
101 // as a template or as a non-template.
102 if (AllowTemplates) {
103 auto *RD = dyn_cast<CXXRecordDecl>(ND);
104 if (!RD || !RD->isInjectedClassName())
105 return false;
106 RD = cast<CXXRecordDecl>(RD->getDeclContext());
107 return RD->getDescribedClassTemplate() ||
108 isa<ClassTemplateSpecializationDecl>(RD);
111 return false;
114 return !WantClassName && candidate.isKeyword();
117 std::unique_ptr<CorrectionCandidateCallback> clone() override {
118 return std::make_unique<TypeNameValidatorCCC>(*this);
121 private:
122 bool AllowInvalidDecl;
123 bool WantClassName;
124 bool AllowTemplates;
125 bool AllowNonTemplates;
128 } // end anonymous namespace
130 /// Determine whether the token kind starts a simple-type-specifier.
131 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
132 switch (Kind) {
133 // FIXME: Take into account the current language when deciding whether a
134 // token kind is a valid type specifier
135 case tok::kw_short:
136 case tok::kw_long:
137 case tok::kw___int64:
138 case tok::kw___int128:
139 case tok::kw_signed:
140 case tok::kw_unsigned:
141 case tok::kw_void:
142 case tok::kw_char:
143 case tok::kw_int:
144 case tok::kw_half:
145 case tok::kw_float:
146 case tok::kw_double:
147 case tok::kw___bf16:
148 case tok::kw__Float16:
149 case tok::kw___float128:
150 case tok::kw___ibm128:
151 case tok::kw_wchar_t:
152 case tok::kw_bool:
153 case tok::kw__Accum:
154 case tok::kw__Fract:
155 case tok::kw__Sat:
156 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
157 #include "clang/Basic/TransformTypeTraits.def"
158 case tok::kw___auto_type:
159 return true;
161 case tok::annot_typename:
162 case tok::kw_char16_t:
163 case tok::kw_char32_t:
164 case tok::kw_typeof:
165 case tok::annot_decltype:
166 case tok::kw_decltype:
167 return getLangOpts().CPlusPlus;
169 case tok::kw_char8_t:
170 return getLangOpts().Char8;
172 default:
173 break;
176 return false;
179 namespace {
180 enum class UnqualifiedTypeNameLookupResult {
181 NotFound,
182 FoundNonType,
183 FoundType
185 } // end anonymous namespace
187 /// Tries to perform unqualified lookup of the type decls in bases for
188 /// dependent class.
189 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
190 /// type decl, \a FoundType if only type decls are found.
191 static UnqualifiedTypeNameLookupResult
192 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
193 SourceLocation NameLoc,
194 const CXXRecordDecl *RD) {
195 if (!RD->hasDefinition())
196 return UnqualifiedTypeNameLookupResult::NotFound;
197 // Look for type decls in base classes.
198 UnqualifiedTypeNameLookupResult FoundTypeDecl =
199 UnqualifiedTypeNameLookupResult::NotFound;
200 for (const auto &Base : RD->bases()) {
201 const CXXRecordDecl *BaseRD = nullptr;
202 if (auto *BaseTT = Base.getType()->getAs<TagType>())
203 BaseRD = BaseTT->getAsCXXRecordDecl();
204 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
205 // Look for type decls in dependent base classes that have known primary
206 // templates.
207 if (!TST || !TST->isDependentType())
208 continue;
209 auto *TD = TST->getTemplateName().getAsTemplateDecl();
210 if (!TD)
211 continue;
212 if (auto *BasePrimaryTemplate =
213 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
214 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
215 BaseRD = BasePrimaryTemplate;
216 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
217 if (const ClassTemplatePartialSpecializationDecl *PS =
218 CTD->findPartialSpecialization(Base.getType()))
219 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
220 BaseRD = PS;
224 if (BaseRD) {
225 for (NamedDecl *ND : BaseRD->lookup(&II)) {
226 if (!isa<TypeDecl>(ND))
227 return UnqualifiedTypeNameLookupResult::FoundNonType;
228 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
230 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
231 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
232 case UnqualifiedTypeNameLookupResult::FoundNonType:
233 return UnqualifiedTypeNameLookupResult::FoundNonType;
234 case UnqualifiedTypeNameLookupResult::FoundType:
235 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
236 break;
237 case UnqualifiedTypeNameLookupResult::NotFound:
238 break;
244 return FoundTypeDecl;
247 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
248 const IdentifierInfo &II,
249 SourceLocation NameLoc) {
250 // Lookup in the parent class template context, if any.
251 const CXXRecordDecl *RD = nullptr;
252 UnqualifiedTypeNameLookupResult FoundTypeDecl =
253 UnqualifiedTypeNameLookupResult::NotFound;
254 for (DeclContext *DC = S.CurContext;
255 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
256 DC = DC->getParent()) {
257 // Look for type decls in dependent base classes that have known primary
258 // templates.
259 RD = dyn_cast<CXXRecordDecl>(DC);
260 if (RD && RD->getDescribedClassTemplate())
261 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
263 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
264 return nullptr;
266 // We found some types in dependent base classes. Recover as if the user
267 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
268 // lookup during template instantiation.
269 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
271 ASTContext &Context = S.Context;
272 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
273 cast<Type>(Context.getRecordType(RD)));
274 QualType T =
275 Context.getDependentNameType(ElaboratedTypeKeyword::Typename, NNS, &II);
277 CXXScopeSpec SS;
278 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
280 TypeLocBuilder Builder;
281 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
282 DepTL.setNameLoc(NameLoc);
283 DepTL.setElaboratedKeywordLoc(SourceLocation());
284 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
285 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
288 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
289 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
290 SourceLocation NameLoc,
291 bool WantNontrivialTypeSourceInfo = true) {
292 switch (T->getTypeClass()) {
293 case Type::DeducedTemplateSpecialization:
294 case Type::Enum:
295 case Type::InjectedClassName:
296 case Type::Record:
297 case Type::Typedef:
298 case Type::UnresolvedUsing:
299 case Type::Using:
300 break;
301 // These can never be qualified so an ElaboratedType node
302 // would carry no additional meaning.
303 case Type::ObjCInterface:
304 case Type::ObjCTypeParam:
305 case Type::TemplateTypeParm:
306 return ParsedType::make(T);
307 default:
308 llvm_unreachable("Unexpected Type Class");
311 if (!SS || SS->isEmpty())
312 return ParsedType::make(S.Context.getElaboratedType(
313 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
315 QualType ElTy = S.getElaboratedType(ElaboratedTypeKeyword::None, *SS, T);
316 if (!WantNontrivialTypeSourceInfo)
317 return ParsedType::make(ElTy);
319 TypeLocBuilder Builder;
320 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
321 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
322 ElabTL.setElaboratedKeywordLoc(SourceLocation());
323 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
324 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
327 /// If the identifier refers to a type name within this scope,
328 /// return the declaration of that type.
330 /// This routine performs ordinary name lookup of the identifier II
331 /// within the given scope, with optional C++ scope specifier SS, to
332 /// determine whether the name refers to a type. If so, returns an
333 /// opaque pointer (actually a QualType) corresponding to that
334 /// type. Otherwise, returns NULL.
335 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
336 Scope *S, CXXScopeSpec *SS, bool isClassName,
337 bool HasTrailingDot, ParsedType ObjectTypePtr,
338 bool IsCtorOrDtorName,
339 bool WantNontrivialTypeSourceInfo,
340 bool IsClassTemplateDeductionContext,
341 ImplicitTypenameContext AllowImplicitTypename,
342 IdentifierInfo **CorrectedII) {
343 // FIXME: Consider allowing this outside C++1z mode as an extension.
344 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
345 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
346 !isClassName && !HasTrailingDot;
348 // Determine where we will perform name lookup.
349 DeclContext *LookupCtx = nullptr;
350 if (ObjectTypePtr) {
351 QualType ObjectType = ObjectTypePtr.get();
352 if (ObjectType->isRecordType())
353 LookupCtx = computeDeclContext(ObjectType);
354 } else if (SS && SS->isNotEmpty()) {
355 LookupCtx = computeDeclContext(*SS, false);
357 if (!LookupCtx) {
358 if (isDependentScopeSpecifier(*SS)) {
359 // C++ [temp.res]p3:
360 // A qualified-id that refers to a type and in which the
361 // nested-name-specifier depends on a template-parameter (14.6.2)
362 // shall be prefixed by the keyword typename to indicate that the
363 // qualified-id denotes a type, forming an
364 // elaborated-type-specifier (7.1.5.3).
366 // We therefore do not perform any name lookup if the result would
367 // refer to a member of an unknown specialization.
368 // In C++2a, in several contexts a 'typename' is not required. Also
369 // allow this as an extension.
370 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
371 !isClassName && !IsCtorOrDtorName)
372 return nullptr;
373 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
374 if (IsImplicitTypename) {
375 SourceLocation QualifiedLoc = SS->getRange().getBegin();
376 if (getLangOpts().CPlusPlus20)
377 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
378 else
379 Diag(QualifiedLoc, diag::ext_implicit_typename)
380 << SS->getScopeRep() << II.getName()
381 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
384 // We know from the grammar that this name refers to a type,
385 // so build a dependent node to describe the type.
386 if (WantNontrivialTypeSourceInfo)
387 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
388 (ImplicitTypenameContext)IsImplicitTypename)
389 .get();
391 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
392 QualType T = CheckTypenameType(
393 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
394 : ElaboratedTypeKeyword::None,
395 SourceLocation(), QualifierLoc, II, NameLoc);
396 return ParsedType::make(T);
399 return nullptr;
402 if (!LookupCtx->isDependentContext() &&
403 RequireCompleteDeclContext(*SS, LookupCtx))
404 return nullptr;
407 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
408 // lookup for class-names.
409 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
410 LookupOrdinaryName;
411 LookupResult Result(*this, &II, NameLoc, Kind);
412 if (LookupCtx) {
413 // Perform "qualified" name lookup into the declaration context we
414 // computed, which is either the type of the base of a member access
415 // expression or the declaration context associated with a prior
416 // nested-name-specifier.
417 LookupQualifiedName(Result, LookupCtx);
419 if (ObjectTypePtr && Result.empty()) {
420 // C++ [basic.lookup.classref]p3:
421 // If the unqualified-id is ~type-name, the type-name is looked up
422 // in the context of the entire postfix-expression. If the type T of
423 // the object expression is of a class type C, the type-name is also
424 // looked up in the scope of class C. At least one of the lookups shall
425 // find a name that refers to (possibly cv-qualified) T.
426 LookupName(Result, S);
428 } else {
429 // Perform unqualified name lookup.
430 LookupName(Result, S);
432 // For unqualified lookup in a class template in MSVC mode, look into
433 // dependent base classes where the primary class template is known.
434 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
435 if (ParsedType TypeInBase =
436 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
437 return TypeInBase;
441 NamedDecl *IIDecl = nullptr;
442 UsingShadowDecl *FoundUsingShadow = nullptr;
443 switch (Result.getResultKind()) {
444 case LookupResult::NotFound:
445 if (CorrectedII) {
446 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
447 AllowDeducedTemplate);
448 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
449 S, SS, CCC, CTK_ErrorRecovery);
450 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
451 TemplateTy Template;
452 bool MemberOfUnknownSpecialization;
453 UnqualifiedId TemplateName;
454 TemplateName.setIdentifier(NewII, NameLoc);
455 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
456 CXXScopeSpec NewSS, *NewSSPtr = SS;
457 if (SS && NNS) {
458 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
459 NewSSPtr = &NewSS;
461 if (Correction && (NNS || NewII != &II) &&
462 // Ignore a correction to a template type as the to-be-corrected
463 // identifier is not a template (typo correction for template names
464 // is handled elsewhere).
465 !(getLangOpts().CPlusPlus && NewSSPtr &&
466 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
467 Template, MemberOfUnknownSpecialization))) {
468 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
469 isClassName, HasTrailingDot, ObjectTypePtr,
470 IsCtorOrDtorName,
471 WantNontrivialTypeSourceInfo,
472 IsClassTemplateDeductionContext);
473 if (Ty) {
474 diagnoseTypo(Correction,
475 PDiag(diag::err_unknown_type_or_class_name_suggest)
476 << Result.getLookupName() << isClassName);
477 if (SS && NNS)
478 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
479 *CorrectedII = NewII;
480 return Ty;
484 Result.suppressDiagnostics();
485 return nullptr;
486 case LookupResult::NotFoundInCurrentInstantiation:
487 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
488 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
489 SS->getScopeRep(), &II);
490 TypeLocBuilder TLB;
491 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T);
492 TL.setElaboratedKeywordLoc(SourceLocation());
493 TL.setQualifierLoc(SS->getWithLocInContext(Context));
494 TL.setNameLoc(NameLoc);
495 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
497 [[fallthrough]];
498 case LookupResult::FoundOverloaded:
499 case LookupResult::FoundUnresolvedValue:
500 Result.suppressDiagnostics();
501 return nullptr;
503 case LookupResult::Ambiguous:
504 // Recover from type-hiding ambiguities by hiding the type. We'll
505 // do the lookup again when looking for an object, and we can
506 // diagnose the error then. If we don't do this, then the error
507 // about hiding the type will be immediately followed by an error
508 // that only makes sense if the identifier was treated like a type.
509 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
510 Result.suppressDiagnostics();
511 return nullptr;
514 // Look to see if we have a type anywhere in the list of results.
515 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
516 Res != ResEnd; ++Res) {
517 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
518 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
519 RealRes) ||
520 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
521 if (!IIDecl ||
522 // Make the selection of the recovery decl deterministic.
523 RealRes->getLocation() < IIDecl->getLocation()) {
524 IIDecl = RealRes;
525 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
530 if (!IIDecl) {
531 // None of the entities we found is a type, so there is no way
532 // to even assume that the result is a type. In this case, don't
533 // complain about the ambiguity. The parser will either try to
534 // perform this lookup again (e.g., as an object name), which
535 // will produce the ambiguity, or will complain that it expected
536 // a type name.
537 Result.suppressDiagnostics();
538 return nullptr;
541 // We found a type within the ambiguous lookup; diagnose the
542 // ambiguity and then return that type. This might be the right
543 // answer, or it might not be, but it suppresses any attempt to
544 // perform the name lookup again.
545 break;
547 case LookupResult::Found:
548 IIDecl = Result.getFoundDecl();
549 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
550 break;
553 assert(IIDecl && "Didn't find decl");
555 QualType T;
556 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
557 // C++ [class.qual]p2: A lookup that would find the injected-class-name
558 // instead names the constructors of the class, except when naming a class.
559 // This is ill-formed when we're not actually forming a ctor or dtor name.
560 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
561 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
562 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
563 FoundRD->isInjectedClassName() &&
564 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
565 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
566 << &II << /*Type*/1;
568 DiagnoseUseOfDecl(IIDecl, NameLoc);
570 T = Context.getTypeDeclType(TD);
571 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
572 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
573 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
574 if (!HasTrailingDot)
575 T = Context.getObjCInterfaceType(IDecl);
576 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
577 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
578 (void)DiagnoseUseOfDecl(UD, NameLoc);
579 // Recover with 'int'
580 return ParsedType::make(Context.IntTy);
581 } else if (AllowDeducedTemplate) {
582 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
583 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
584 TemplateName Template =
585 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
586 T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
587 false);
588 // Don't wrap in a further UsingType.
589 FoundUsingShadow = nullptr;
593 if (T.isNull()) {
594 // If it's not plausibly a type, suppress diagnostics.
595 Result.suppressDiagnostics();
596 return nullptr;
599 if (FoundUsingShadow)
600 T = Context.getUsingType(FoundUsingShadow, T);
602 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
605 // Builds a fake NNS for the given decl context.
606 static NestedNameSpecifier *
607 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
608 for (;; DC = DC->getLookupParent()) {
609 DC = DC->getPrimaryContext();
610 auto *ND = dyn_cast<NamespaceDecl>(DC);
611 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
612 return NestedNameSpecifier::Create(Context, nullptr, ND);
613 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
614 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
615 RD->getTypeForDecl());
616 else if (isa<TranslationUnitDecl>(DC))
617 return NestedNameSpecifier::GlobalSpecifier(Context);
619 llvm_unreachable("something isn't in TU scope?");
622 /// Find the parent class with dependent bases of the innermost enclosing method
623 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
624 /// up allowing unqualified dependent type names at class-level, which MSVC
625 /// correctly rejects.
626 static const CXXRecordDecl *
627 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
628 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
629 DC = DC->getPrimaryContext();
630 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
631 if (MD->getParent()->hasAnyDependentBases())
632 return MD->getParent();
634 return nullptr;
637 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
638 SourceLocation NameLoc,
639 bool IsTemplateTypeArg) {
640 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
642 NestedNameSpecifier *NNS = nullptr;
643 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
644 // If we weren't able to parse a default template argument, delay lookup
645 // until instantiation time by making a non-dependent DependentTypeName. We
646 // pretend we saw a NestedNameSpecifier referring to the current scope, and
647 // lookup is retried.
648 // FIXME: This hurts our diagnostic quality, since we get errors like "no
649 // type named 'Foo' in 'current_namespace'" when the user didn't write any
650 // name specifiers.
651 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
652 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
653 } else if (const CXXRecordDecl *RD =
654 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
655 // Build a DependentNameType that will perform lookup into RD at
656 // instantiation time.
657 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
658 RD->getTypeForDecl());
660 // Diagnose that this identifier was undeclared, and retry the lookup during
661 // template instantiation.
662 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
663 << RD;
664 } else {
665 // This is not a situation that we should recover from.
666 return ParsedType();
669 QualType T =
670 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
672 // Build type location information. We synthesized the qualifier, so we have
673 // to build a fake NestedNameSpecifierLoc.
674 NestedNameSpecifierLocBuilder NNSLocBuilder;
675 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
676 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
678 TypeLocBuilder Builder;
679 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
680 DepTL.setNameLoc(NameLoc);
681 DepTL.setElaboratedKeywordLoc(SourceLocation());
682 DepTL.setQualifierLoc(QualifierLoc);
683 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
686 /// isTagName() - This method is called *for error recovery purposes only*
687 /// to determine if the specified name is a valid tag name ("struct foo"). If
688 /// so, this returns the TST for the tag corresponding to it (TST_enum,
689 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
690 /// cases in C where the user forgot to specify the tag.
691 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
692 // Do a tag name lookup in this scope.
693 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
694 LookupName(R, S, false);
695 R.suppressDiagnostics();
696 if (R.getResultKind() == LookupResult::Found)
697 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
698 switch (TD->getTagKind()) {
699 case TagTypeKind::Struct:
700 return DeclSpec::TST_struct;
701 case TagTypeKind::Interface:
702 return DeclSpec::TST_interface;
703 case TagTypeKind::Union:
704 return DeclSpec::TST_union;
705 case TagTypeKind::Class:
706 return DeclSpec::TST_class;
707 case TagTypeKind::Enum:
708 return DeclSpec::TST_enum;
712 return DeclSpec::TST_unspecified;
715 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
716 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
717 /// then downgrade the missing typename error to a warning.
718 /// This is needed for MSVC compatibility; Example:
719 /// @code
720 /// template<class T> class A {
721 /// public:
722 /// typedef int TYPE;
723 /// };
724 /// template<class T> class B : public A<T> {
725 /// public:
726 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
727 /// };
728 /// @endcode
729 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
730 if (CurContext->isRecord()) {
731 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
732 return true;
734 const Type *Ty = SS->getScopeRep()->getAsType();
736 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
737 for (const auto &Base : RD->bases())
738 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
739 return true;
740 return S->isFunctionPrototypeScope();
742 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
745 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
746 SourceLocation IILoc,
747 Scope *S,
748 CXXScopeSpec *SS,
749 ParsedType &SuggestedType,
750 bool IsTemplateName) {
751 // Don't report typename errors for editor placeholders.
752 if (II->isEditorPlaceholder())
753 return;
754 // We don't have anything to suggest (yet).
755 SuggestedType = nullptr;
757 // There may have been a typo in the name of the type. Look up typo
758 // results, in case we have something that we can suggest.
759 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
760 /*AllowTemplates=*/IsTemplateName,
761 /*AllowNonTemplates=*/!IsTemplateName);
762 if (TypoCorrection Corrected =
763 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
764 CCC, CTK_ErrorRecovery)) {
765 // FIXME: Support error recovery for the template-name case.
766 bool CanRecover = !IsTemplateName;
767 if (Corrected.isKeyword()) {
768 // We corrected to a keyword.
769 diagnoseTypo(Corrected,
770 PDiag(IsTemplateName ? diag::err_no_template_suggest
771 : diag::err_unknown_typename_suggest)
772 << II);
773 II = Corrected.getCorrectionAsIdentifierInfo();
774 } else {
775 // We found a similarly-named type or interface; suggest that.
776 if (!SS || !SS->isSet()) {
777 diagnoseTypo(Corrected,
778 PDiag(IsTemplateName ? diag::err_no_template_suggest
779 : diag::err_unknown_typename_suggest)
780 << II, CanRecover);
781 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
782 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
783 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
784 II->getName().equals(CorrectedStr);
785 diagnoseTypo(Corrected,
786 PDiag(IsTemplateName
787 ? diag::err_no_member_template_suggest
788 : diag::err_unknown_nested_typename_suggest)
789 << II << DC << DroppedSpecifier << SS->getRange(),
790 CanRecover);
791 } else {
792 llvm_unreachable("could not have corrected a typo here");
795 if (!CanRecover)
796 return;
798 CXXScopeSpec tmpSS;
799 if (Corrected.getCorrectionSpecifier())
800 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
801 SourceRange(IILoc));
802 // FIXME: Support class template argument deduction here.
803 SuggestedType =
804 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
805 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
806 /*IsCtorOrDtorName=*/false,
807 /*WantNontrivialTypeSourceInfo=*/true);
809 return;
812 if (getLangOpts().CPlusPlus && !IsTemplateName) {
813 // See if II is a class template that the user forgot to pass arguments to.
814 UnqualifiedId Name;
815 Name.setIdentifier(II, IILoc);
816 CXXScopeSpec EmptySS;
817 TemplateTy TemplateResult;
818 bool MemberOfUnknownSpecialization;
819 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
820 Name, nullptr, true, TemplateResult,
821 MemberOfUnknownSpecialization) == TNK_Type_template) {
822 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
823 return;
827 // FIXME: Should we move the logic that tries to recover from a missing tag
828 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
830 if (!SS || (!SS->isSet() && !SS->isInvalid()))
831 Diag(IILoc, IsTemplateName ? diag::err_no_template
832 : diag::err_unknown_typename)
833 << II;
834 else if (DeclContext *DC = computeDeclContext(*SS, false))
835 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
836 : diag::err_typename_nested_not_found)
837 << II << DC << SS->getRange();
838 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
839 SuggestedType =
840 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
841 } else if (isDependentScopeSpecifier(*SS)) {
842 unsigned DiagID = diag::err_typename_missing;
843 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
844 DiagID = diag::ext_typename_missing;
846 Diag(SS->getRange().getBegin(), DiagID)
847 << SS->getScopeRep() << II->getName()
848 << SourceRange(SS->getRange().getBegin(), IILoc)
849 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
850 SuggestedType = ActOnTypenameType(S, SourceLocation(),
851 *SS, *II, IILoc).get();
852 } else {
853 assert(SS && SS->isInvalid() &&
854 "Invalid scope specifier has already been diagnosed");
858 /// Determine whether the given result set contains either a type name
859 /// or
860 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
861 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
862 NextToken.is(tok::less);
864 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
865 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
866 return true;
868 if (CheckTemplate && isa<TemplateDecl>(*I))
869 return true;
872 return false;
875 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
876 Scope *S, CXXScopeSpec &SS,
877 IdentifierInfo *&Name,
878 SourceLocation NameLoc) {
879 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
880 SemaRef.LookupParsedName(R, S, &SS);
881 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
882 StringRef FixItTagName;
883 switch (Tag->getTagKind()) {
884 case TagTypeKind::Class:
885 FixItTagName = "class ";
886 break;
888 case TagTypeKind::Enum:
889 FixItTagName = "enum ";
890 break;
892 case TagTypeKind::Struct:
893 FixItTagName = "struct ";
894 break;
896 case TagTypeKind::Interface:
897 FixItTagName = "__interface ";
898 break;
900 case TagTypeKind::Union:
901 FixItTagName = "union ";
902 break;
905 StringRef TagName = FixItTagName.drop_back();
906 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
907 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
908 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
910 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
911 I != IEnd; ++I)
912 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
913 << Name << TagName;
915 // Replace lookup results with just the tag decl.
916 Result.clear(Sema::LookupTagName);
917 SemaRef.LookupParsedName(Result, S, &SS);
918 return true;
921 return false;
924 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
925 IdentifierInfo *&Name,
926 SourceLocation NameLoc,
927 const Token &NextToken,
928 CorrectionCandidateCallback *CCC) {
929 DeclarationNameInfo NameInfo(Name, NameLoc);
930 ObjCMethodDecl *CurMethod = getCurMethodDecl();
932 assert(NextToken.isNot(tok::coloncolon) &&
933 "parse nested name specifiers before calling ClassifyName");
934 if (getLangOpts().CPlusPlus && SS.isSet() &&
935 isCurrentClassName(*Name, S, &SS)) {
936 // Per [class.qual]p2, this names the constructors of SS, not the
937 // injected-class-name. We don't have a classification for that.
938 // There's not much point caching this result, since the parser
939 // will reject it later.
940 return NameClassification::Unknown();
943 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
944 LookupParsedName(Result, S, &SS, !CurMethod);
946 if (SS.isInvalid())
947 return NameClassification::Error();
949 // For unqualified lookup in a class template in MSVC mode, look into
950 // dependent base classes where the primary class template is known.
951 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
952 if (ParsedType TypeInBase =
953 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
954 return TypeInBase;
957 // Perform lookup for Objective-C instance variables (including automatically
958 // synthesized instance variables), if we're in an Objective-C method.
959 // FIXME: This lookup really, really needs to be folded in to the normal
960 // unqualified lookup mechanism.
961 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
962 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
963 if (Ivar.isInvalid())
964 return NameClassification::Error();
965 if (Ivar.isUsable())
966 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
968 // We defer builtin creation until after ivar lookup inside ObjC methods.
969 if (Result.empty())
970 LookupBuiltin(Result);
973 bool SecondTry = false;
974 bool IsFilteredTemplateName = false;
976 Corrected:
977 switch (Result.getResultKind()) {
978 case LookupResult::NotFound:
979 // If an unqualified-id is followed by a '(', then we have a function
980 // call.
981 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
982 // In C++, this is an ADL-only call.
983 // FIXME: Reference?
984 if (getLangOpts().CPlusPlus)
985 return NameClassification::UndeclaredNonType();
987 // C90 6.3.2.2:
988 // If the expression that precedes the parenthesized argument list in a
989 // function call consists solely of an identifier, and if no
990 // declaration is visible for this identifier, the identifier is
991 // implicitly declared exactly as if, in the innermost block containing
992 // the function call, the declaration
994 // extern int identifier ();
996 // appeared.
998 // We also allow this in C99 as an extension. However, this is not
999 // allowed in all language modes as functions without prototypes may not
1000 // be supported.
1001 if (getLangOpts().implicitFunctionsAllowed()) {
1002 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
1003 return NameClassification::NonType(D);
1007 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
1008 // In C++20 onwards, this could be an ADL-only call to a function
1009 // template, and we're required to assume that this is a template name.
1011 // FIXME: Find a way to still do typo correction in this case.
1012 TemplateName Template =
1013 Context.getAssumedTemplateName(NameInfo.getName());
1014 return NameClassification::UndeclaredTemplate(Template);
1017 // In C, we first see whether there is a tag type by the same name, in
1018 // which case it's likely that the user just forgot to write "enum",
1019 // "struct", or "union".
1020 if (!getLangOpts().CPlusPlus && !SecondTry &&
1021 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1022 break;
1025 // Perform typo correction to determine if there is another name that is
1026 // close to this name.
1027 if (!SecondTry && CCC) {
1028 SecondTry = true;
1029 if (TypoCorrection Corrected =
1030 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1031 &SS, *CCC, CTK_ErrorRecovery)) {
1032 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1033 unsigned QualifiedDiag = diag::err_no_member_suggest;
1035 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1036 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1037 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1038 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1039 UnqualifiedDiag = diag::err_no_template_suggest;
1040 QualifiedDiag = diag::err_no_member_template_suggest;
1041 } else if (UnderlyingFirstDecl &&
1042 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1043 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1044 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1045 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1046 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1049 if (SS.isEmpty()) {
1050 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1051 } else {// FIXME: is this even reachable? Test it.
1052 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1053 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1054 Name->getName().equals(CorrectedStr);
1055 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1056 << Name << computeDeclContext(SS, false)
1057 << DroppedSpecifier << SS.getRange());
1060 // Update the name, so that the caller has the new name.
1061 Name = Corrected.getCorrectionAsIdentifierInfo();
1063 // Typo correction corrected to a keyword.
1064 if (Corrected.isKeyword())
1065 return Name;
1067 // Also update the LookupResult...
1068 // FIXME: This should probably go away at some point
1069 Result.clear();
1070 Result.setLookupName(Corrected.getCorrection());
1071 if (FirstDecl)
1072 Result.addDecl(FirstDecl);
1074 // If we found an Objective-C instance variable, let
1075 // LookupInObjCMethod build the appropriate expression to
1076 // reference the ivar.
1077 // FIXME: This is a gross hack.
1078 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1079 DeclResult R =
1080 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1081 if (R.isInvalid())
1082 return NameClassification::Error();
1083 if (R.isUsable())
1084 return NameClassification::NonType(Ivar);
1087 goto Corrected;
1091 // We failed to correct; just fall through and let the parser deal with it.
1092 Result.suppressDiagnostics();
1093 return NameClassification::Unknown();
1095 case LookupResult::NotFoundInCurrentInstantiation: {
1096 // We performed name lookup into the current instantiation, and there were
1097 // dependent bases, so we treat this result the same way as any other
1098 // dependent nested-name-specifier.
1100 // C++ [temp.res]p2:
1101 // A name used in a template declaration or definition and that is
1102 // dependent on a template-parameter is assumed not to name a type
1103 // unless the applicable name lookup finds a type name or the name is
1104 // qualified by the keyword typename.
1106 // FIXME: If the next token is '<', we might want to ask the parser to
1107 // perform some heroics to see if we actually have a
1108 // template-argument-list, which would indicate a missing 'template'
1109 // keyword here.
1110 return NameClassification::DependentNonType();
1113 case LookupResult::Found:
1114 case LookupResult::FoundOverloaded:
1115 case LookupResult::FoundUnresolvedValue:
1116 break;
1118 case LookupResult::Ambiguous:
1119 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1120 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1121 /*AllowDependent=*/false)) {
1122 // C++ [temp.local]p3:
1123 // A lookup that finds an injected-class-name (10.2) can result in an
1124 // ambiguity in certain cases (for example, if it is found in more than
1125 // one base class). If all of the injected-class-names that are found
1126 // refer to specializations of the same class template, and if the name
1127 // is followed by a template-argument-list, the reference refers to the
1128 // class template itself and not a specialization thereof, and is not
1129 // ambiguous.
1131 // This filtering can make an ambiguous result into an unambiguous one,
1132 // so try again after filtering out template names.
1133 FilterAcceptableTemplateNames(Result);
1134 if (!Result.isAmbiguous()) {
1135 IsFilteredTemplateName = true;
1136 break;
1140 // Diagnose the ambiguity and return an error.
1141 return NameClassification::Error();
1144 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1145 (IsFilteredTemplateName ||
1146 hasAnyAcceptableTemplateNames(
1147 Result, /*AllowFunctionTemplates=*/true,
1148 /*AllowDependent=*/false,
1149 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1150 getLangOpts().CPlusPlus20))) {
1151 // C++ [temp.names]p3:
1152 // After name lookup (3.4) finds that a name is a template-name or that
1153 // an operator-function-id or a literal- operator-id refers to a set of
1154 // overloaded functions any member of which is a function template if
1155 // this is followed by a <, the < is always taken as the delimiter of a
1156 // template-argument-list and never as the less-than operator.
1157 // C++2a [temp.names]p2:
1158 // A name is also considered to refer to a template if it is an
1159 // unqualified-id followed by a < and name lookup finds either one
1160 // or more functions or finds nothing.
1161 if (!IsFilteredTemplateName)
1162 FilterAcceptableTemplateNames(Result);
1164 bool IsFunctionTemplate;
1165 bool IsVarTemplate;
1166 TemplateName Template;
1167 if (Result.end() - Result.begin() > 1) {
1168 IsFunctionTemplate = true;
1169 Template = Context.getOverloadedTemplateName(Result.begin(),
1170 Result.end());
1171 } else if (!Result.empty()) {
1172 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1173 *Result.begin(), /*AllowFunctionTemplates=*/true,
1174 /*AllowDependent=*/false));
1175 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1176 IsVarTemplate = isa<VarTemplateDecl>(TD);
1178 UsingShadowDecl *FoundUsingShadow =
1179 dyn_cast<UsingShadowDecl>(*Result.begin());
1180 assert(!FoundUsingShadow ||
1181 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1182 Template =
1183 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
1184 if (SS.isNotEmpty())
1185 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1186 /*TemplateKeyword=*/false,
1187 Template);
1188 } else {
1189 // All results were non-template functions. This is a function template
1190 // name.
1191 IsFunctionTemplate = true;
1192 Template = Context.getAssumedTemplateName(NameInfo.getName());
1195 if (IsFunctionTemplate) {
1196 // Function templates always go through overload resolution, at which
1197 // point we'll perform the various checks (e.g., accessibility) we need
1198 // to based on which function we selected.
1199 Result.suppressDiagnostics();
1201 return NameClassification::FunctionTemplate(Template);
1204 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1205 : NameClassification::TypeTemplate(Template);
1208 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1209 QualType T = Context.getTypeDeclType(Type);
1210 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1211 T = Context.getUsingType(USD, T);
1212 return buildNamedType(*this, &SS, T, NameLoc);
1215 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1216 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1217 DiagnoseUseOfDecl(Type, NameLoc);
1218 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1219 return BuildTypeFor(Type, *Result.begin());
1222 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1223 if (!Class) {
1224 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1225 if (ObjCCompatibleAliasDecl *Alias =
1226 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1227 Class = Alias->getClassInterface();
1230 if (Class) {
1231 DiagnoseUseOfDecl(Class, NameLoc);
1233 if (NextToken.is(tok::period)) {
1234 // Interface. <something> is parsed as a property reference expression.
1235 // Just return "unknown" as a fall-through for now.
1236 Result.suppressDiagnostics();
1237 return NameClassification::Unknown();
1240 QualType T = Context.getObjCInterfaceType(Class);
1241 return ParsedType::make(T);
1244 if (isa<ConceptDecl>(FirstDecl))
1245 return NameClassification::Concept(
1246 TemplateName(cast<TemplateDecl>(FirstDecl)));
1248 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1249 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1250 return NameClassification::Error();
1253 // We can have a type template here if we're classifying a template argument.
1254 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1255 !isa<VarTemplateDecl>(FirstDecl))
1256 return NameClassification::TypeTemplate(
1257 TemplateName(cast<TemplateDecl>(FirstDecl)));
1259 // Check for a tag type hidden by a non-type decl in a few cases where it
1260 // seems likely a type is wanted instead of the non-type that was found.
1261 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1262 if ((NextToken.is(tok::identifier) ||
1263 (NextIsOp &&
1264 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1265 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1266 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1267 DiagnoseUseOfDecl(Type, NameLoc);
1268 return BuildTypeFor(Type, *Result.begin());
1271 // If we already know which single declaration is referenced, just annotate
1272 // that declaration directly. Defer resolving even non-overloaded class
1273 // member accesses, as we need to defer certain access checks until we know
1274 // the context.
1275 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1276 if (Result.isSingleResult() && !ADL &&
1277 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1278 return NameClassification::NonType(Result.getRepresentativeDecl());
1280 // Otherwise, this is an overload set that we will need to resolve later.
1281 Result.suppressDiagnostics();
1282 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1283 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1284 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1285 Result.begin(), Result.end()));
1288 ExprResult
1289 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1290 SourceLocation NameLoc) {
1291 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1292 CXXScopeSpec SS;
1293 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1294 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1297 ExprResult
1298 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1299 IdentifierInfo *Name,
1300 SourceLocation NameLoc,
1301 bool IsAddressOfOperand) {
1302 DeclarationNameInfo NameInfo(Name, NameLoc);
1303 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1304 NameInfo, IsAddressOfOperand,
1305 /*TemplateArgs=*/nullptr);
1308 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1309 NamedDecl *Found,
1310 SourceLocation NameLoc,
1311 const Token &NextToken) {
1312 if (getCurMethodDecl() && SS.isEmpty())
1313 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1314 return BuildIvarRefExpr(S, NameLoc, Ivar);
1316 // Reconstruct the lookup result.
1317 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1318 Result.addDecl(Found);
1319 Result.resolveKind();
1321 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1322 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1325 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1326 // For an implicit class member access, transform the result into a member
1327 // access expression if necessary.
1328 auto *ULE = cast<UnresolvedLookupExpr>(E);
1329 if ((*ULE->decls_begin())->isCXXClassMember()) {
1330 CXXScopeSpec SS;
1331 SS.Adopt(ULE->getQualifierLoc());
1333 // Reconstruct the lookup result.
1334 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1335 LookupOrdinaryName);
1336 Result.setNamingClass(ULE->getNamingClass());
1337 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1338 Result.addDecl(*I, I.getAccess());
1339 Result.resolveKind();
1340 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1341 nullptr, S);
1344 // Otherwise, this is already in the form we needed, and no further checks
1345 // are necessary.
1346 return ULE;
1349 Sema::TemplateNameKindForDiagnostics
1350 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1351 auto *TD = Name.getAsTemplateDecl();
1352 if (!TD)
1353 return TemplateNameKindForDiagnostics::DependentTemplate;
1354 if (isa<ClassTemplateDecl>(TD))
1355 return TemplateNameKindForDiagnostics::ClassTemplate;
1356 if (isa<FunctionTemplateDecl>(TD))
1357 return TemplateNameKindForDiagnostics::FunctionTemplate;
1358 if (isa<VarTemplateDecl>(TD))
1359 return TemplateNameKindForDiagnostics::VarTemplate;
1360 if (isa<TypeAliasTemplateDecl>(TD))
1361 return TemplateNameKindForDiagnostics::AliasTemplate;
1362 if (isa<TemplateTemplateParmDecl>(TD))
1363 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1364 if (isa<ConceptDecl>(TD))
1365 return TemplateNameKindForDiagnostics::Concept;
1366 return TemplateNameKindForDiagnostics::DependentTemplate;
1369 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1370 assert(DC->getLexicalParent() == CurContext &&
1371 "The next DeclContext should be lexically contained in the current one.");
1372 CurContext = DC;
1373 S->setEntity(DC);
1376 void Sema::PopDeclContext() {
1377 assert(CurContext && "DeclContext imbalance!");
1379 CurContext = CurContext->getLexicalParent();
1380 assert(CurContext && "Popped translation unit!");
1383 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1384 Decl *D) {
1385 // Unlike PushDeclContext, the context to which we return is not necessarily
1386 // the containing DC of TD, because the new context will be some pre-existing
1387 // TagDecl definition instead of a fresh one.
1388 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1389 CurContext = cast<TagDecl>(D)->getDefinition();
1390 assert(CurContext && "skipping definition of undefined tag");
1391 // Start lookups from the parent of the current context; we don't want to look
1392 // into the pre-existing complete definition.
1393 S->setEntity(CurContext->getLookupParent());
1394 return Result;
1397 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1398 CurContext = static_cast<decltype(CurContext)>(Context);
1401 /// EnterDeclaratorContext - Used when we must lookup names in the context
1402 /// of a declarator's nested name specifier.
1404 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1405 // C++0x [basic.lookup.unqual]p13:
1406 // A name used in the definition of a static data member of class
1407 // X (after the qualified-id of the static member) is looked up as
1408 // if the name was used in a member function of X.
1409 // C++0x [basic.lookup.unqual]p14:
1410 // If a variable member of a namespace is defined outside of the
1411 // scope of its namespace then any name used in the definition of
1412 // the variable member (after the declarator-id) is looked up as
1413 // if the definition of the variable member occurred in its
1414 // namespace.
1415 // Both of these imply that we should push a scope whose context
1416 // is the semantic context of the declaration. We can't use
1417 // PushDeclContext here because that context is not necessarily
1418 // lexically contained in the current context. Fortunately,
1419 // the containing scope should have the appropriate information.
1421 assert(!S->getEntity() && "scope already has entity");
1423 #ifndef NDEBUG
1424 Scope *Ancestor = S->getParent();
1425 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1426 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1427 #endif
1429 CurContext = DC;
1430 S->setEntity(DC);
1432 if (S->getParent()->isTemplateParamScope()) {
1433 // Also set the corresponding entities for all immediately-enclosing
1434 // template parameter scopes.
1435 EnterTemplatedContext(S->getParent(), DC);
1439 void Sema::ExitDeclaratorContext(Scope *S) {
1440 assert(S->getEntity() == CurContext && "Context imbalance!");
1442 // Switch back to the lexical context. The safety of this is
1443 // enforced by an assert in EnterDeclaratorContext.
1444 Scope *Ancestor = S->getParent();
1445 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1446 CurContext = Ancestor->getEntity();
1448 // We don't need to do anything with the scope, which is going to
1449 // disappear.
1452 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1453 assert(S->isTemplateParamScope() &&
1454 "expected to be initializing a template parameter scope");
1456 // C++20 [temp.local]p7:
1457 // In the definition of a member of a class template that appears outside
1458 // of the class template definition, the name of a member of the class
1459 // template hides the name of a template-parameter of any enclosing class
1460 // templates (but not a template-parameter of the member if the member is a
1461 // class or function template).
1462 // C++20 [temp.local]p9:
1463 // In the definition of a class template or in the definition of a member
1464 // of such a template that appears outside of the template definition, for
1465 // each non-dependent base class (13.8.2.1), if the name of the base class
1466 // or the name of a member of the base class is the same as the name of a
1467 // template-parameter, the base class name or member name hides the
1468 // template-parameter name (6.4.10).
1470 // This means that a template parameter scope should be searched immediately
1471 // after searching the DeclContext for which it is a template parameter
1472 // scope. For example, for
1473 // template<typename T> template<typename U> template<typename V>
1474 // void N::A<T>::B<U>::f(...)
1475 // we search V then B<U> (and base classes) then U then A<T> (and base
1476 // classes) then T then N then ::.
1477 unsigned ScopeDepth = getTemplateDepth(S);
1478 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1479 DeclContext *SearchDCAfterScope = DC;
1480 for (; DC; DC = DC->getLookupParent()) {
1481 if (const TemplateParameterList *TPL =
1482 cast<Decl>(DC)->getDescribedTemplateParams()) {
1483 unsigned DCDepth = TPL->getDepth() + 1;
1484 if (DCDepth > ScopeDepth)
1485 continue;
1486 if (ScopeDepth == DCDepth)
1487 SearchDCAfterScope = DC = DC->getLookupParent();
1488 break;
1491 S->setLookupEntity(SearchDCAfterScope);
1495 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1496 // We assume that the caller has already called
1497 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1498 FunctionDecl *FD = D->getAsFunction();
1499 if (!FD)
1500 return;
1502 // Same implementation as PushDeclContext, but enters the context
1503 // from the lexical parent, rather than the top-level class.
1504 assert(CurContext == FD->getLexicalParent() &&
1505 "The next DeclContext should be lexically contained in the current one.");
1506 CurContext = FD;
1507 S->setEntity(CurContext);
1509 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1510 ParmVarDecl *Param = FD->getParamDecl(P);
1511 // If the parameter has an identifier, then add it to the scope
1512 if (Param->getIdentifier()) {
1513 S->AddDecl(Param);
1514 IdResolver.AddDecl(Param);
1519 void Sema::ActOnExitFunctionContext() {
1520 // Same implementation as PopDeclContext, but returns to the lexical parent,
1521 // rather than the top-level class.
1522 assert(CurContext && "DeclContext imbalance!");
1523 CurContext = CurContext->getLexicalParent();
1524 assert(CurContext && "Popped translation unit!");
1527 /// Determine whether overloading is allowed for a new function
1528 /// declaration considering prior declarations of the same name.
1530 /// This routine determines whether overloading is possible, not
1531 /// whether a new declaration actually overloads a previous one.
1532 /// It will return true in C++ (where overloads are alway permitted)
1533 /// or, as a C extension, when either the new declaration or a
1534 /// previous one is declared with the 'overloadable' attribute.
1535 static bool AllowOverloadingOfFunction(const LookupResult &Previous,
1536 ASTContext &Context,
1537 const FunctionDecl *New) {
1538 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1539 return true;
1541 // Multiversion function declarations are not overloads in the
1542 // usual sense of that term, but lookup will report that an
1543 // overload set was found if more than one multiversion function
1544 // declaration is present for the same name. It is therefore
1545 // inadequate to assume that some prior declaration(s) had
1546 // the overloadable attribute; checking is required. Since one
1547 // declaration is permitted to omit the attribute, it is necessary
1548 // to check at least two; hence the 'any_of' check below. Note that
1549 // the overloadable attribute is implicitly added to declarations
1550 // that were required to have it but did not.
1551 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1552 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1553 return ND->hasAttr<OverloadableAttr>();
1555 } else if (Previous.getResultKind() == LookupResult::Found)
1556 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1558 return false;
1561 /// Add this decl to the scope shadowed decl chains.
1562 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1563 // Move up the scope chain until we find the nearest enclosing
1564 // non-transparent context. The declaration will be introduced into this
1565 // scope.
1566 while (S->getEntity() && S->getEntity()->isTransparentContext())
1567 S = S->getParent();
1569 // Add scoped declarations into their context, so that they can be
1570 // found later. Declarations without a context won't be inserted
1571 // into any context.
1572 if (AddToContext)
1573 CurContext->addDecl(D);
1575 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1576 // are function-local declarations.
1577 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1578 return;
1580 // Template instantiations should also not be pushed into scope.
1581 if (isa<FunctionDecl>(D) &&
1582 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1583 return;
1585 // If this replaces anything in the current scope,
1586 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1587 IEnd = IdResolver.end();
1588 for (; I != IEnd; ++I) {
1589 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1590 S->RemoveDecl(*I);
1591 IdResolver.RemoveDecl(*I);
1593 // Should only need to replace one decl.
1594 break;
1598 S->AddDecl(D);
1600 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1601 // Implicitly-generated labels may end up getting generated in an order that
1602 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1603 // the label at the appropriate place in the identifier chain.
1604 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1605 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1606 if (IDC == CurContext) {
1607 if (!S->isDeclScope(*I))
1608 continue;
1609 } else if (IDC->Encloses(CurContext))
1610 break;
1613 IdResolver.InsertDeclAfter(I, D);
1614 } else {
1615 IdResolver.AddDecl(D);
1617 warnOnReservedIdentifier(D);
1620 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1621 bool AllowInlineNamespace) const {
1622 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1625 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1626 DeclContext *TargetDC = DC->getPrimaryContext();
1627 do {
1628 if (DeclContext *ScopeDC = S->getEntity())
1629 if (ScopeDC->getPrimaryContext() == TargetDC)
1630 return S;
1631 } while ((S = S->getParent()));
1633 return nullptr;
1636 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1637 DeclContext*,
1638 ASTContext&);
1640 /// Filters out lookup results that don't fall within the given scope
1641 /// as determined by isDeclInScope.
1642 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1643 bool ConsiderLinkage,
1644 bool AllowInlineNamespace) {
1645 LookupResult::Filter F = R.makeFilter();
1646 while (F.hasNext()) {
1647 NamedDecl *D = F.next();
1649 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1650 continue;
1652 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1653 continue;
1655 F.erase();
1658 F.done();
1661 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1662 /// have compatible owning modules.
1663 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1664 // [module.interface]p7:
1665 // A declaration is attached to a module as follows:
1666 // - If the declaration is a non-dependent friend declaration that nominates a
1667 // function with a declarator-id that is a qualified-id or template-id or that
1668 // nominates a class other than with an elaborated-type-specifier with neither
1669 // a nested-name-specifier nor a simple-template-id, it is attached to the
1670 // module to which the friend is attached ([basic.link]).
1671 if (New->getFriendObjectKind() &&
1672 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1673 New->setLocalOwningModule(Old->getOwningModule());
1674 makeMergedDefinitionVisible(New);
1675 return false;
1678 Module *NewM = New->getOwningModule();
1679 Module *OldM = Old->getOwningModule();
1681 if (NewM && NewM->isPrivateModule())
1682 NewM = NewM->Parent;
1683 if (OldM && OldM->isPrivateModule())
1684 OldM = OldM->Parent;
1686 if (NewM == OldM)
1687 return false;
1689 if (NewM && OldM) {
1690 // A module implementation unit has visibility of the decls in its
1691 // implicitly imported interface.
1692 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1693 return false;
1695 // Partitions are part of the module, but a partition could import another
1696 // module, so verify that the PMIs agree.
1697 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1698 NewM->getPrimaryModuleInterfaceName() ==
1699 OldM->getPrimaryModuleInterfaceName())
1700 return false;
1703 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1704 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1705 if (NewIsModuleInterface || OldIsModuleInterface) {
1706 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1707 // if a declaration of D [...] appears in the purview of a module, all
1708 // other such declarations shall appear in the purview of the same module
1709 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1710 << New
1711 << NewIsModuleInterface
1712 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1713 << OldIsModuleInterface
1714 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1715 Diag(Old->getLocation(), diag::note_previous_declaration);
1716 New->setInvalidDecl();
1717 return true;
1720 return false;
1723 // [module.interface]p6:
1724 // A redeclaration of an entity X is implicitly exported if X was introduced by
1725 // an exported declaration; otherwise it shall not be exported.
1726 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
1727 // [module.interface]p1:
1728 // An export-declaration shall inhabit a namespace scope.
1730 // So it is meaningless to talk about redeclaration which is not at namespace
1731 // scope.
1732 if (!New->getLexicalDeclContext()
1733 ->getNonTransparentContext()
1734 ->isFileContext() ||
1735 !Old->getLexicalDeclContext()
1736 ->getNonTransparentContext()
1737 ->isFileContext())
1738 return false;
1740 bool IsNewExported = New->isInExportDeclContext();
1741 bool IsOldExported = Old->isInExportDeclContext();
1743 // It should be irrevelant if both of them are not exported.
1744 if (!IsNewExported && !IsOldExported)
1745 return false;
1747 if (IsOldExported)
1748 return false;
1750 assert(IsNewExported);
1752 auto Lk = Old->getFormalLinkage();
1753 int S = 0;
1754 if (Lk == Linkage::Internal)
1755 S = 1;
1756 else if (Lk == Linkage::Module)
1757 S = 2;
1758 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1759 Diag(Old->getLocation(), diag::note_previous_declaration);
1760 return true;
1763 // A wrapper function for checking the semantic restrictions of
1764 // a redeclaration within a module.
1765 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
1766 if (CheckRedeclarationModuleOwnership(New, Old))
1767 return true;
1769 if (CheckRedeclarationExported(New, Old))
1770 return true;
1772 return false;
1775 // Check the redefinition in C++20 Modules.
1777 // [basic.def.odr]p14:
1778 // For any definable item D with definitions in multiple translation units,
1779 // - if D is a non-inline non-templated function or variable, or
1780 // - if the definitions in different translation units do not satisfy the
1781 // following requirements,
1782 // the program is ill-formed; a diagnostic is required only if the definable
1783 // item is attached to a named module and a prior definition is reachable at
1784 // the point where a later definition occurs.
1785 // - Each such definition shall not be attached to a named module
1786 // ([module.unit]).
1787 // - Each such definition shall consist of the same sequence of tokens, ...
1788 // ...
1790 // Return true if the redefinition is not allowed. Return false otherwise.
1791 bool Sema::IsRedefinitionInModule(const NamedDecl *New,
1792 const NamedDecl *Old) const {
1793 assert(getASTContext().isSameEntity(New, Old) &&
1794 "New and Old are not the same definition, we should diagnostic it "
1795 "immediately instead of checking it.");
1796 assert(const_cast<Sema *>(this)->isReachable(New) &&
1797 const_cast<Sema *>(this)->isReachable(Old) &&
1798 "We shouldn't see unreachable definitions here.");
1800 Module *NewM = New->getOwningModule();
1801 Module *OldM = Old->getOwningModule();
1803 // We only checks for named modules here. The header like modules is skipped.
1804 // FIXME: This is not right if we import the header like modules in the module
1805 // purview.
1807 // For example, assuming "header.h" provides definition for `D`.
1808 // ```C++
1809 // //--- M.cppm
1810 // export module M;
1811 // import "header.h"; // or #include "header.h" but import it by clang modules
1812 // actually.
1814 // //--- Use.cpp
1815 // import M;
1816 // import "header.h"; // or uses clang modules.
1817 // ```
1819 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1820 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1821 // reject it. But the current implementation couldn't detect the case since we
1822 // don't record the information about the importee modules.
1824 // But this might not be painful in practice. Since the design of C++20 Named
1825 // Modules suggests us to use headers in global module fragment instead of
1826 // module purview.
1827 if (NewM && NewM->isHeaderLikeModule())
1828 NewM = nullptr;
1829 if (OldM && OldM->isHeaderLikeModule())
1830 OldM = nullptr;
1832 if (!NewM && !OldM)
1833 return true;
1835 // [basic.def.odr]p14.3
1836 // Each such definition shall not be attached to a named module
1837 // ([module.unit]).
1838 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1839 return true;
1841 // Then New and Old lives in the same TU if their share one same module unit.
1842 if (NewM)
1843 NewM = NewM->getTopLevelModule();
1844 if (OldM)
1845 OldM = OldM->getTopLevelModule();
1846 return OldM == NewM;
1849 static bool isUsingDeclNotAtClassScope(NamedDecl *D) {
1850 if (D->getDeclContext()->isFileContext())
1851 return false;
1853 return isa<UsingShadowDecl>(D) ||
1854 isa<UnresolvedUsingTypenameDecl>(D) ||
1855 isa<UnresolvedUsingValueDecl>(D);
1858 /// Removes using shadow declarations not at class scope from the lookup
1859 /// results.
1860 static void RemoveUsingDecls(LookupResult &R) {
1861 LookupResult::Filter F = R.makeFilter();
1862 while (F.hasNext())
1863 if (isUsingDeclNotAtClassScope(F.next()))
1864 F.erase();
1866 F.done();
1869 /// Check for this common pattern:
1870 /// @code
1871 /// class S {
1872 /// S(const S&); // DO NOT IMPLEMENT
1873 /// void operator=(const S&); // DO NOT IMPLEMENT
1874 /// };
1875 /// @endcode
1876 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1877 // FIXME: Should check for private access too but access is set after we get
1878 // the decl here.
1879 if (D->doesThisDeclarationHaveABody())
1880 return false;
1882 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1883 return CD->isCopyConstructor();
1884 return D->isCopyAssignmentOperator();
1887 // We need this to handle
1889 // typedef struct {
1890 // void *foo() { return 0; }
1891 // } A;
1893 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1894 // for example. If 'A', foo will have external linkage. If we have '*A',
1895 // foo will have no linkage. Since we can't know until we get to the end
1896 // of the typedef, this function finds out if D might have non-external linkage.
1897 // Callers should verify at the end of the TU if it D has external linkage or
1898 // not.
1899 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1900 const DeclContext *DC = D->getDeclContext();
1901 while (!DC->isTranslationUnit()) {
1902 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1903 if (!RD->hasNameForLinkage())
1904 return true;
1906 DC = DC->getParent();
1909 return !D->isExternallyVisible();
1912 // FIXME: This needs to be refactored; some other isInMainFile users want
1913 // these semantics.
1914 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1915 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
1916 return false;
1917 return S.SourceMgr.isInMainFile(Loc);
1920 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1921 assert(D);
1923 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1924 return false;
1926 // Ignore all entities declared within templates, and out-of-line definitions
1927 // of members of class templates.
1928 if (D->getDeclContext()->isDependentContext() ||
1929 D->getLexicalDeclContext()->isDependentContext())
1930 return false;
1932 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1933 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1934 return false;
1935 // A non-out-of-line declaration of a member specialization was implicitly
1936 // instantiated; it's the out-of-line declaration that we're interested in.
1937 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1938 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1939 return false;
1941 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1942 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1943 return false;
1944 } else {
1945 // 'static inline' functions are defined in headers; don't warn.
1946 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1947 return false;
1950 if (FD->doesThisDeclarationHaveABody() &&
1951 Context.DeclMustBeEmitted(FD))
1952 return false;
1953 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1954 // Constants and utility variables are defined in headers with internal
1955 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1956 // like "inline".)
1957 if (!isMainFileLoc(*this, VD->getLocation()))
1958 return false;
1960 if (Context.DeclMustBeEmitted(VD))
1961 return false;
1963 if (VD->isStaticDataMember() &&
1964 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1965 return false;
1966 if (VD->isStaticDataMember() &&
1967 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1968 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1969 return false;
1971 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1972 return false;
1973 } else {
1974 return false;
1977 // Only warn for unused decls internal to the translation unit.
1978 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1979 // for inline functions defined in the main source file, for instance.
1980 return mightHaveNonExternalLinkage(D);
1983 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1984 if (!D)
1985 return;
1987 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1988 const FunctionDecl *First = FD->getFirstDecl();
1989 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1990 return; // First should already be in the vector.
1993 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1994 const VarDecl *First = VD->getFirstDecl();
1995 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1996 return; // First should already be in the vector.
1999 if (ShouldWarnIfUnusedFileScopedDecl(D))
2000 UnusedFileScopedDecls.push_back(D);
2003 static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2004 const NamedDecl *D) {
2005 if (D->isInvalidDecl())
2006 return false;
2008 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2009 // For a decomposition declaration, warn if none of the bindings are
2010 // referenced, instead of if the variable itself is referenced (which
2011 // it is, by the bindings' expressions).
2012 bool IsAllPlaceholders = true;
2013 for (const auto *BD : DD->bindings()) {
2014 if (BD->isReferenced())
2015 return false;
2016 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
2018 if (IsAllPlaceholders)
2019 return false;
2020 } else if (!D->getDeclName()) {
2021 return false;
2022 } else if (D->isReferenced() || D->isUsed()) {
2023 return false;
2026 if (D->isPlaceholderVar(LangOpts))
2027 return false;
2029 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2030 D->hasAttr<CleanupAttr>())
2031 return false;
2033 if (isa<LabelDecl>(D))
2034 return true;
2036 // Except for labels, we only care about unused decls that are local to
2037 // functions.
2038 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2039 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2040 // For dependent types, the diagnostic is deferred.
2041 WithinFunction =
2042 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2043 if (!WithinFunction)
2044 return false;
2046 if (isa<TypedefNameDecl>(D))
2047 return true;
2049 // White-list anything that isn't a local variable.
2050 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
2051 return false;
2053 // Types of valid local variables should be complete, so this should succeed.
2054 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2056 const Expr *Init = VD->getInit();
2057 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2058 Init = Cleanups->getSubExpr();
2060 const auto *Ty = VD->getType().getTypePtr();
2062 // Only look at the outermost level of typedef.
2063 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2064 // Allow anything marked with __attribute__((unused)).
2065 if (TT->getDecl()->hasAttr<UnusedAttr>())
2066 return false;
2069 // Warn for reference variables whose initializtion performs lifetime
2070 // extension.
2071 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2072 MTE && MTE->getExtendingDecl()) {
2073 Ty = VD->getType().getNonReferenceType().getTypePtr();
2074 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2077 // If we failed to complete the type for some reason, or if the type is
2078 // dependent, don't diagnose the variable.
2079 if (Ty->isIncompleteType() || Ty->isDependentType())
2080 return false;
2082 // Look at the element type to ensure that the warning behaviour is
2083 // consistent for both scalars and arrays.
2084 Ty = Ty->getBaseElementTypeUnsafe();
2086 if (const TagType *TT = Ty->getAs<TagType>()) {
2087 const TagDecl *Tag = TT->getDecl();
2088 if (Tag->hasAttr<UnusedAttr>())
2089 return false;
2091 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2092 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2093 return false;
2095 if (Init) {
2096 const auto *Construct = dyn_cast<CXXConstructExpr>(Init);
2097 if (Construct && !Construct->isElidable()) {
2098 const CXXConstructorDecl *CD = Construct->getConstructor();
2099 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2100 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2101 return false;
2104 // Suppress the warning if we don't know how this is constructed, and
2105 // it could possibly be non-trivial constructor.
2106 if (Init->isTypeDependent()) {
2107 for (const CXXConstructorDecl *Ctor : RD->ctors())
2108 if (!Ctor->isTrivial())
2109 return false;
2112 // Suppress the warning if the constructor is unresolved because
2113 // its arguments are dependent.
2114 if (isa<CXXUnresolvedConstructExpr>(Init))
2115 return false;
2120 // TODO: __attribute__((unused)) templates?
2123 return true;
2126 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
2127 FixItHint &Hint) {
2128 if (isa<LabelDecl>(D)) {
2129 SourceLocation AfterColon = Lexer::findLocationAfterToken(
2130 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2131 /*SkipTrailingWhitespaceAndNewline=*/false);
2132 if (AfterColon.isInvalid())
2133 return;
2134 Hint = FixItHint::CreateRemoval(
2135 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2139 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
2140 DiagnoseUnusedNestedTypedefs(
2141 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2144 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
2145 DiagReceiverTy DiagReceiver) {
2146 if (D->getTypeForDecl()->isDependentType())
2147 return;
2149 for (auto *TmpD : D->decls()) {
2150 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2151 DiagnoseUnusedDecl(T, DiagReceiver);
2152 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2153 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2157 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
2158 DiagnoseUnusedDecl(
2159 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2162 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
2163 /// unless they are marked attr(unused).
2164 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
2165 if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D))
2166 return;
2168 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2169 // typedefs can be referenced later on, so the diagnostics are emitted
2170 // at end-of-translation-unit.
2171 UnusedLocalTypedefNameCandidates.insert(TD);
2172 return;
2175 FixItHint Hint;
2176 GenerateFixForUnusedDecl(D, Context, Hint);
2178 unsigned DiagID;
2179 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2180 DiagID = diag::warn_unused_exception_param;
2181 else if (isa<LabelDecl>(D))
2182 DiagID = diag::warn_unused_label;
2183 else
2184 DiagID = diag::warn_unused_variable;
2186 SourceLocation DiagLoc = D->getLocation();
2187 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2190 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
2191 DiagReceiverTy DiagReceiver) {
2192 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2193 // it's not really unused.
2194 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2195 return;
2197 // In C++, `_` variables behave as if they were maybe_unused
2198 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2199 return;
2201 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2203 if (Ty->isReferenceType() || Ty->isDependentType())
2204 return;
2206 if (const TagType *TT = Ty->getAs<TagType>()) {
2207 const TagDecl *Tag = TT->getDecl();
2208 if (Tag->hasAttr<UnusedAttr>())
2209 return;
2210 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2211 // mimic gcc's behavior.
2212 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2213 RD && !RD->hasAttr<WarnUnusedAttr>())
2214 return;
2217 // Don't warn about __block Objective-C pointer variables, as they might
2218 // be assigned in the block but not used elsewhere for the purpose of lifetime
2219 // extension.
2220 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2221 return;
2223 // Don't warn about Objective-C pointer variables with precise lifetime
2224 // semantics; they can be used to ensure ARC releases the object at a known
2225 // time, which may mean assignment but no other references.
2226 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2227 return;
2229 auto iter = RefsMinusAssignments.find(VD);
2230 if (iter == RefsMinusAssignments.end())
2231 return;
2233 assert(iter->getSecond() >= 0 &&
2234 "Found a negative number of references to a VarDecl");
2235 if (iter->getSecond() != 0)
2236 return;
2237 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2238 : diag::warn_unused_but_set_variable;
2239 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2242 static void CheckPoppedLabel(LabelDecl *L, Sema &S,
2243 Sema::DiagReceiverTy DiagReceiver) {
2244 // Verify that we have no forward references left. If so, there was a goto
2245 // or address of a label taken, but no definition of it. Label fwd
2246 // definitions are indicated with a null substmt which is also not a resolved
2247 // MS inline assembly label name.
2248 bool Diagnose = false;
2249 if (L->isMSAsmLabel())
2250 Diagnose = !L->isResolvedMSAsmLabel();
2251 else
2252 Diagnose = L->getStmt() == nullptr;
2253 if (Diagnose)
2254 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2255 << L);
2258 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
2259 S->applyNRVO();
2261 if (S->decl_empty()) return;
2262 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2263 "Scope shouldn't contain decls!");
2265 /// We visit the decls in non-deterministic order, but we want diagnostics
2266 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2267 /// and sort the diagnostics before emitting them, after we visited all decls.
2268 struct LocAndDiag {
2269 SourceLocation Loc;
2270 std::optional<SourceLocation> PreviousDeclLoc;
2271 PartialDiagnostic PD;
2273 SmallVector<LocAndDiag, 16> DeclDiags;
2274 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2275 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2277 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2278 SourceLocation PreviousDeclLoc,
2279 PartialDiagnostic PD) {
2280 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2283 for (auto *TmpD : S->decls()) {
2284 assert(TmpD && "This decl didn't get pushed??");
2286 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2287 NamedDecl *D = cast<NamedDecl>(TmpD);
2289 // Diagnose unused variables in this scope.
2290 if (!S->hasUnrecoverableErrorOccurred()) {
2291 DiagnoseUnusedDecl(D, addDiag);
2292 if (const auto *RD = dyn_cast<RecordDecl>(D))
2293 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2294 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2295 DiagnoseUnusedButSetDecl(VD, addDiag);
2296 RefsMinusAssignments.erase(VD);
2300 if (!D->getDeclName()) continue;
2302 // If this was a forward reference to a label, verify it was defined.
2303 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2304 CheckPoppedLabel(LD, *this, addDiag);
2306 // Remove this name from our lexical scope, and warn on it if we haven't
2307 // already.
2308 IdResolver.RemoveDecl(D);
2309 auto ShadowI = ShadowingDecls.find(D);
2310 if (ShadowI != ShadowingDecls.end()) {
2311 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2312 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2313 PDiag(diag::warn_ctor_parm_shadows_field)
2314 << D << FD << FD->getParent());
2316 ShadowingDecls.erase(ShadowI);
2320 llvm::sort(DeclDiags,
2321 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2322 // The particular order for diagnostics is not important, as long
2323 // as the order is deterministic. Using the raw location is going
2324 // to generally be in source order unless there are macro
2325 // expansions involved.
2326 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2328 for (const LocAndDiag &D : DeclDiags) {
2329 Diag(D.Loc, D.PD);
2330 if (D.PreviousDeclLoc)
2331 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2335 /// Look for an Objective-C class in the translation unit.
2337 /// \param Id The name of the Objective-C class we're looking for. If
2338 /// typo-correction fixes this name, the Id will be updated
2339 /// to the fixed name.
2341 /// \param IdLoc The location of the name in the translation unit.
2343 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2344 /// if there is no class with the given name.
2346 /// \returns The declaration of the named Objective-C class, or NULL if the
2347 /// class could not be found.
2348 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2349 SourceLocation IdLoc,
2350 bool DoTypoCorrection) {
2351 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2352 // creation from this context.
2353 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2355 if (!IDecl && DoTypoCorrection) {
2356 // Perform typo correction at the given location, but only if we
2357 // find an Objective-C class name.
2358 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2359 if (TypoCorrection C =
2360 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2361 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2362 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2363 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2364 Id = IDecl->getIdentifier();
2367 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2368 // This routine must always return a class definition, if any.
2369 if (Def && Def->getDefinition())
2370 Def = Def->getDefinition();
2371 return Def;
2374 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2375 /// from S, where a non-field would be declared. This routine copes
2376 /// with the difference between C and C++ scoping rules in structs and
2377 /// unions. For example, the following code is well-formed in C but
2378 /// ill-formed in C++:
2379 /// @code
2380 /// struct S6 {
2381 /// enum { BAR } e;
2382 /// };
2384 /// void test_S6() {
2385 /// struct S6 a;
2386 /// a.e = BAR;
2387 /// }
2388 /// @endcode
2389 /// For the declaration of BAR, this routine will return a different
2390 /// scope. The scope S will be the scope of the unnamed enumeration
2391 /// within S6. In C++, this routine will return the scope associated
2392 /// with S6, because the enumeration's scope is a transparent
2393 /// context but structures can contain non-field names. In C, this
2394 /// routine will return the translation unit scope, since the
2395 /// enumeration's scope is a transparent context and structures cannot
2396 /// contain non-field names.
2397 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2398 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2399 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2400 (S->isClassScope() && !getLangOpts().CPlusPlus))
2401 S = S->getParent();
2402 return S;
2405 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2406 ASTContext::GetBuiltinTypeError Error) {
2407 switch (Error) {
2408 case ASTContext::GE_None:
2409 return "";
2410 case ASTContext::GE_Missing_type:
2411 return BuiltinInfo.getHeaderName(ID);
2412 case ASTContext::GE_Missing_stdio:
2413 return "stdio.h";
2414 case ASTContext::GE_Missing_setjmp:
2415 return "setjmp.h";
2416 case ASTContext::GE_Missing_ucontext:
2417 return "ucontext.h";
2419 llvm_unreachable("unhandled error kind");
2422 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2423 unsigned ID, SourceLocation Loc) {
2424 DeclContext *Parent = Context.getTranslationUnitDecl();
2426 if (getLangOpts().CPlusPlus) {
2427 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2428 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2429 CLinkageDecl->setImplicit();
2430 Parent->addDecl(CLinkageDecl);
2431 Parent = CLinkageDecl;
2434 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2435 /*TInfo=*/nullptr, SC_Extern,
2436 getCurFPFeatures().isFPConstrained(),
2437 false, Type->isFunctionProtoType());
2438 New->setImplicit();
2439 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2441 // Create Decl objects for each parameter, adding them to the
2442 // FunctionDecl.
2443 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2444 SmallVector<ParmVarDecl *, 16> Params;
2445 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2446 ParmVarDecl *parm = ParmVarDecl::Create(
2447 Context, New, SourceLocation(), SourceLocation(), nullptr,
2448 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2449 parm->setScopeInfo(0, i);
2450 Params.push_back(parm);
2452 New->setParams(Params);
2455 AddKnownFunctionAttributes(New);
2456 return New;
2459 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2460 /// file scope. lazily create a decl for it. ForRedeclaration is true
2461 /// if we're creating this built-in in anticipation of redeclaring the
2462 /// built-in.
2463 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2464 Scope *S, bool ForRedeclaration,
2465 SourceLocation Loc) {
2466 LookupNecessaryTypesForBuiltin(S, ID);
2468 ASTContext::GetBuiltinTypeError Error;
2469 QualType R = Context.GetBuiltinType(ID, Error);
2470 if (Error) {
2471 if (!ForRedeclaration)
2472 return nullptr;
2474 // If we have a builtin without an associated type we should not emit a
2475 // warning when we were not able to find a type for it.
2476 if (Error == ASTContext::GE_Missing_type ||
2477 Context.BuiltinInfo.allowTypeMismatch(ID))
2478 return nullptr;
2480 // If we could not find a type for setjmp it is because the jmp_buf type was
2481 // not defined prior to the setjmp declaration.
2482 if (Error == ASTContext::GE_Missing_setjmp) {
2483 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2484 << Context.BuiltinInfo.getName(ID);
2485 return nullptr;
2488 // Generally, we emit a warning that the declaration requires the
2489 // appropriate header.
2490 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2491 << getHeaderName(Context.BuiltinInfo, ID, Error)
2492 << Context.BuiltinInfo.getName(ID);
2493 return nullptr;
2496 if (!ForRedeclaration &&
2497 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2498 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2499 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2500 : diag::ext_implicit_lib_function_decl)
2501 << Context.BuiltinInfo.getName(ID) << R;
2502 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2503 Diag(Loc, diag::note_include_header_or_declare)
2504 << Header << Context.BuiltinInfo.getName(ID);
2507 if (R.isNull())
2508 return nullptr;
2510 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2511 RegisterLocallyScopedExternCDecl(New, S);
2513 // TUScope is the translation-unit scope to insert this function into.
2514 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2515 // relate Scopes to DeclContexts, and probably eliminate CurContext
2516 // entirely, but we're not there yet.
2517 DeclContext *SavedContext = CurContext;
2518 CurContext = New->getDeclContext();
2519 PushOnScopeChains(New, TUScope);
2520 CurContext = SavedContext;
2521 return New;
2524 /// Typedef declarations don't have linkage, but they still denote the same
2525 /// entity if their types are the same.
2526 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2527 /// isSameEntity.
2528 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2529 TypedefNameDecl *Decl,
2530 LookupResult &Previous) {
2531 // This is only interesting when modules are enabled.
2532 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2533 return;
2535 // Empty sets are uninteresting.
2536 if (Previous.empty())
2537 return;
2539 LookupResult::Filter Filter = Previous.makeFilter();
2540 while (Filter.hasNext()) {
2541 NamedDecl *Old = Filter.next();
2543 // Non-hidden declarations are never ignored.
2544 if (S.isVisible(Old))
2545 continue;
2547 // Declarations of the same entity are not ignored, even if they have
2548 // different linkages.
2549 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2550 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2551 Decl->getUnderlyingType()))
2552 continue;
2554 // If both declarations give a tag declaration a typedef name for linkage
2555 // purposes, then they declare the same entity.
2556 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2557 Decl->getAnonDeclWithTypedefName())
2558 continue;
2561 Filter.erase();
2564 Filter.done();
2567 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2568 QualType OldType;
2569 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2570 OldType = OldTypedef->getUnderlyingType();
2571 else
2572 OldType = Context.getTypeDeclType(Old);
2573 QualType NewType = New->getUnderlyingType();
2575 if (NewType->isVariablyModifiedType()) {
2576 // Must not redefine a typedef with a variably-modified type.
2577 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2578 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2579 << Kind << NewType;
2580 if (Old->getLocation().isValid())
2581 notePreviousDefinition(Old, New->getLocation());
2582 New->setInvalidDecl();
2583 return true;
2586 if (OldType != NewType &&
2587 !OldType->isDependentType() &&
2588 !NewType->isDependentType() &&
2589 !Context.hasSameType(OldType, NewType)) {
2590 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2591 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2592 << Kind << NewType << OldType;
2593 if (Old->getLocation().isValid())
2594 notePreviousDefinition(Old, New->getLocation());
2595 New->setInvalidDecl();
2596 return true;
2598 return false;
2601 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2602 /// same name and scope as a previous declaration 'Old'. Figure out
2603 /// how to resolve this situation, merging decls or emitting
2604 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2606 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2607 LookupResult &OldDecls) {
2608 // If the new decl is known invalid already, don't bother doing any
2609 // merging checks.
2610 if (New->isInvalidDecl()) return;
2612 // Allow multiple definitions for ObjC built-in typedefs.
2613 // FIXME: Verify the underlying types are equivalent!
2614 if (getLangOpts().ObjC) {
2615 const IdentifierInfo *TypeID = New->getIdentifier();
2616 switch (TypeID->getLength()) {
2617 default: break;
2618 case 2:
2620 if (!TypeID->isStr("id"))
2621 break;
2622 QualType T = New->getUnderlyingType();
2623 if (!T->isPointerType())
2624 break;
2625 if (!T->isVoidPointerType()) {
2626 QualType PT = T->castAs<PointerType>()->getPointeeType();
2627 if (!PT->isStructureType())
2628 break;
2630 Context.setObjCIdRedefinitionType(T);
2631 // Install the built-in type for 'id', ignoring the current definition.
2632 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2633 return;
2635 case 5:
2636 if (!TypeID->isStr("Class"))
2637 break;
2638 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2639 // Install the built-in type for 'Class', ignoring the current definition.
2640 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2641 return;
2642 case 3:
2643 if (!TypeID->isStr("SEL"))
2644 break;
2645 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2646 // Install the built-in type for 'SEL', ignoring the current definition.
2647 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2648 return;
2650 // Fall through - the typedef name was not a builtin type.
2653 // Verify the old decl was also a type.
2654 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2655 if (!Old) {
2656 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2657 << New->getDeclName();
2659 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2660 if (OldD->getLocation().isValid())
2661 notePreviousDefinition(OldD, New->getLocation());
2663 return New->setInvalidDecl();
2666 // If the old declaration is invalid, just give up here.
2667 if (Old->isInvalidDecl())
2668 return New->setInvalidDecl();
2670 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2671 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2672 auto *NewTag = New->getAnonDeclWithTypedefName();
2673 NamedDecl *Hidden = nullptr;
2674 if (OldTag && NewTag &&
2675 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2676 !hasVisibleDefinition(OldTag, &Hidden)) {
2677 // There is a definition of this tag, but it is not visible. Use it
2678 // instead of our tag.
2679 New->setTypeForDecl(OldTD->getTypeForDecl());
2680 if (OldTD->isModed())
2681 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2682 OldTD->getUnderlyingType());
2683 else
2684 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2686 // Make the old tag definition visible.
2687 makeMergedDefinitionVisible(Hidden);
2689 // If this was an unscoped enumeration, yank all of its enumerators
2690 // out of the scope.
2691 if (isa<EnumDecl>(NewTag)) {
2692 Scope *EnumScope = getNonFieldDeclScope(S);
2693 for (auto *D : NewTag->decls()) {
2694 auto *ED = cast<EnumConstantDecl>(D);
2695 assert(EnumScope->isDeclScope(ED));
2696 EnumScope->RemoveDecl(ED);
2697 IdResolver.RemoveDecl(ED);
2698 ED->getLexicalDeclContext()->removeDecl(ED);
2704 // If the typedef types are not identical, reject them in all languages and
2705 // with any extensions enabled.
2706 if (isIncompatibleTypedef(Old, New))
2707 return;
2709 // The types match. Link up the redeclaration chain and merge attributes if
2710 // the old declaration was a typedef.
2711 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2712 New->setPreviousDecl(Typedef);
2713 mergeDeclAttributes(New, Old);
2716 if (getLangOpts().MicrosoftExt)
2717 return;
2719 if (getLangOpts().CPlusPlus) {
2720 // C++ [dcl.typedef]p2:
2721 // In a given non-class scope, a typedef specifier can be used to
2722 // redefine the name of any type declared in that scope to refer
2723 // to the type to which it already refers.
2724 if (!isa<CXXRecordDecl>(CurContext))
2725 return;
2727 // C++0x [dcl.typedef]p4:
2728 // In a given class scope, a typedef specifier can be used to redefine
2729 // any class-name declared in that scope that is not also a typedef-name
2730 // to refer to the type to which it already refers.
2732 // This wording came in via DR424, which was a correction to the
2733 // wording in DR56, which accidentally banned code like:
2735 // struct S {
2736 // typedef struct A { } A;
2737 // };
2739 // in the C++03 standard. We implement the C++0x semantics, which
2740 // allow the above but disallow
2742 // struct S {
2743 // typedef int I;
2744 // typedef int I;
2745 // };
2747 // since that was the intent of DR56.
2748 if (!isa<TypedefNameDecl>(Old))
2749 return;
2751 Diag(New->getLocation(), diag::err_redefinition)
2752 << New->getDeclName();
2753 notePreviousDefinition(Old, New->getLocation());
2754 return New->setInvalidDecl();
2757 // Modules always permit redefinition of typedefs, as does C11.
2758 if (getLangOpts().Modules || getLangOpts().C11)
2759 return;
2761 // If we have a redefinition of a typedef in C, emit a warning. This warning
2762 // is normally mapped to an error, but can be controlled with
2763 // -Wtypedef-redefinition. If either the original or the redefinition is
2764 // in a system header, don't emit this for compatibility with GCC.
2765 if (getDiagnostics().getSuppressSystemWarnings() &&
2766 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2767 (Old->isImplicit() ||
2768 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2769 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2770 return;
2772 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2773 << New->getDeclName();
2774 notePreviousDefinition(Old, New->getLocation());
2777 /// DeclhasAttr - returns true if decl Declaration already has the target
2778 /// attribute.
2779 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2780 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2781 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2782 for (const auto *i : D->attrs())
2783 if (i->getKind() == A->getKind()) {
2784 if (Ann) {
2785 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2786 return true;
2787 continue;
2789 // FIXME: Don't hardcode this check
2790 if (OA && isa<OwnershipAttr>(i))
2791 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2792 return true;
2795 return false;
2798 static bool isAttributeTargetADefinition(Decl *D) {
2799 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2800 return VD->isThisDeclarationADefinition();
2801 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2802 return TD->isCompleteDefinition() || TD->isBeingDefined();
2803 return true;
2806 /// Merge alignment attributes from \p Old to \p New, taking into account the
2807 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2809 /// \return \c true if any attributes were added to \p New.
2810 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2811 // Look for alignas attributes on Old, and pick out whichever attribute
2812 // specifies the strictest alignment requirement.
2813 AlignedAttr *OldAlignasAttr = nullptr;
2814 AlignedAttr *OldStrictestAlignAttr = nullptr;
2815 unsigned OldAlign = 0;
2816 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2817 // FIXME: We have no way of representing inherited dependent alignments
2818 // in a case like:
2819 // template<int A, int B> struct alignas(A) X;
2820 // template<int A, int B> struct alignas(B) X {};
2821 // For now, we just ignore any alignas attributes which are not on the
2822 // definition in such a case.
2823 if (I->isAlignmentDependent())
2824 return false;
2826 if (I->isAlignas())
2827 OldAlignasAttr = I;
2829 unsigned Align = I->getAlignment(S.Context);
2830 if (Align > OldAlign) {
2831 OldAlign = Align;
2832 OldStrictestAlignAttr = I;
2836 // Look for alignas attributes on New.
2837 AlignedAttr *NewAlignasAttr = nullptr;
2838 unsigned NewAlign = 0;
2839 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2840 if (I->isAlignmentDependent())
2841 return false;
2843 if (I->isAlignas())
2844 NewAlignasAttr = I;
2846 unsigned Align = I->getAlignment(S.Context);
2847 if (Align > NewAlign)
2848 NewAlign = Align;
2851 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2852 // Both declarations have 'alignas' attributes. We require them to match.
2853 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2854 // fall short. (If two declarations both have alignas, they must both match
2855 // every definition, and so must match each other if there is a definition.)
2857 // If either declaration only contains 'alignas(0)' specifiers, then it
2858 // specifies the natural alignment for the type.
2859 if (OldAlign == 0 || NewAlign == 0) {
2860 QualType Ty;
2861 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2862 Ty = VD->getType();
2863 else
2864 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2866 if (OldAlign == 0)
2867 OldAlign = S.Context.getTypeAlign(Ty);
2868 if (NewAlign == 0)
2869 NewAlign = S.Context.getTypeAlign(Ty);
2872 if (OldAlign != NewAlign) {
2873 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2874 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2875 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2876 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2880 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2881 // C++11 [dcl.align]p6:
2882 // if any declaration of an entity has an alignment-specifier,
2883 // every defining declaration of that entity shall specify an
2884 // equivalent alignment.
2885 // C11 6.7.5/7:
2886 // If the definition of an object does not have an alignment
2887 // specifier, any other declaration of that object shall also
2888 // have no alignment specifier.
2889 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2890 << OldAlignasAttr;
2891 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2892 << OldAlignasAttr;
2895 bool AnyAdded = false;
2897 // Ensure we have an attribute representing the strictest alignment.
2898 if (OldAlign > NewAlign) {
2899 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2900 Clone->setInherited(true);
2901 New->addAttr(Clone);
2902 AnyAdded = true;
2905 // Ensure we have an alignas attribute if the old declaration had one.
2906 if (OldAlignasAttr && !NewAlignasAttr &&
2907 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2908 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2909 Clone->setInherited(true);
2910 New->addAttr(Clone);
2911 AnyAdded = true;
2914 return AnyAdded;
2917 #define WANT_DECL_MERGE_LOGIC
2918 #include "clang/Sema/AttrParsedAttrImpl.inc"
2919 #undef WANT_DECL_MERGE_LOGIC
2921 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2922 const InheritableAttr *Attr,
2923 Sema::AvailabilityMergeKind AMK) {
2924 // Diagnose any mutual exclusions between the attribute that we want to add
2925 // and attributes that already exist on the declaration.
2926 if (!DiagnoseMutualExclusions(S, D, Attr))
2927 return false;
2929 // This function copies an attribute Attr from a previous declaration to the
2930 // new declaration D if the new declaration doesn't itself have that attribute
2931 // yet or if that attribute allows duplicates.
2932 // If you're adding a new attribute that requires logic different from
2933 // "use explicit attribute on decl if present, else use attribute from
2934 // previous decl", for example if the attribute needs to be consistent
2935 // between redeclarations, you need to call a custom merge function here.
2936 InheritableAttr *NewAttr = nullptr;
2937 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2938 NewAttr = S.mergeAvailabilityAttr(
2939 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2940 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2941 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2942 AA->getPriority());
2943 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2944 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2945 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2946 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2947 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2948 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2949 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2950 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2951 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2952 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2953 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2954 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2955 FA->getFirstArg());
2956 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2957 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2958 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2959 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2960 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2961 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2962 IA->getInheritanceModel());
2963 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2964 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2965 &S.Context.Idents.get(AA->getSpelling()));
2966 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2967 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2968 isa<CUDAGlobalAttr>(Attr))) {
2969 // CUDA target attributes are part of function signature for
2970 // overloading purposes and must not be merged.
2971 return false;
2972 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2973 NewAttr = S.mergeMinSizeAttr(D, *MA);
2974 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2975 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2976 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2977 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2978 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2979 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2980 else if (isa<AlignedAttr>(Attr))
2981 // AlignedAttrs are handled separately, because we need to handle all
2982 // such attributes on a declaration at the same time.
2983 NewAttr = nullptr;
2984 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2985 (AMK == Sema::AMK_Override ||
2986 AMK == Sema::AMK_ProtocolImplementation ||
2987 AMK == Sema::AMK_OptionalProtocolImplementation))
2988 NewAttr = nullptr;
2989 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2990 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2991 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2992 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2993 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2994 NewAttr = S.mergeImportNameAttr(D, *INA);
2995 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2996 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2997 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2998 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2999 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
3000 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
3001 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
3002 NewAttr =
3003 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
3004 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
3005 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
3006 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
3007 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
3009 if (NewAttr) {
3010 NewAttr->setInherited(true);
3011 D->addAttr(NewAttr);
3012 if (isa<MSInheritanceAttr>(NewAttr))
3013 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
3014 return true;
3017 return false;
3020 static const NamedDecl *getDefinition(const Decl *D) {
3021 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
3022 return TD->getDefinition();
3023 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3024 const VarDecl *Def = VD->getDefinition();
3025 if (Def)
3026 return Def;
3027 return VD->getActingDefinition();
3029 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3030 const FunctionDecl *Def = nullptr;
3031 if (FD->isDefined(Def, true))
3032 return Def;
3034 return nullptr;
3037 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3038 for (const auto *Attribute : D->attrs())
3039 if (Attribute->getKind() == Kind)
3040 return true;
3041 return false;
3044 /// checkNewAttributesAfterDef - If we already have a definition, check that
3045 /// there are no new attributes in this declaration.
3046 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3047 if (!New->hasAttrs())
3048 return;
3050 const NamedDecl *Def = getDefinition(Old);
3051 if (!Def || Def == New)
3052 return;
3054 AttrVec &NewAttributes = New->getAttrs();
3055 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3056 const Attr *NewAttribute = NewAttributes[I];
3058 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3059 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3060 Sema::SkipBodyInfo SkipBody;
3061 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3063 // If we're skipping this definition, drop the "alias" attribute.
3064 if (SkipBody.ShouldSkip) {
3065 NewAttributes.erase(NewAttributes.begin() + I);
3066 --E;
3067 continue;
3069 } else {
3070 VarDecl *VD = cast<VarDecl>(New);
3071 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3072 VarDecl::TentativeDefinition
3073 ? diag::err_alias_after_tentative
3074 : diag::err_redefinition;
3075 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3076 if (Diag == diag::err_redefinition)
3077 S.notePreviousDefinition(Def, VD->getLocation());
3078 else
3079 S.Diag(Def->getLocation(), diag::note_previous_definition);
3080 VD->setInvalidDecl();
3082 ++I;
3083 continue;
3086 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3087 // Tentative definitions are only interesting for the alias check above.
3088 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3089 ++I;
3090 continue;
3094 if (hasAttribute(Def, NewAttribute->getKind())) {
3095 ++I;
3096 continue; // regular attr merging will take care of validating this.
3099 if (isa<C11NoReturnAttr>(NewAttribute)) {
3100 // C's _Noreturn is allowed to be added to a function after it is defined.
3101 ++I;
3102 continue;
3103 } else if (isa<UuidAttr>(NewAttribute)) {
3104 // msvc will allow a subsequent definition to add an uuid to a class
3105 ++I;
3106 continue;
3107 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3108 if (AA->isAlignas()) {
3109 // C++11 [dcl.align]p6:
3110 // if any declaration of an entity has an alignment-specifier,
3111 // every defining declaration of that entity shall specify an
3112 // equivalent alignment.
3113 // C11 6.7.5/7:
3114 // If the definition of an object does not have an alignment
3115 // specifier, any other declaration of that object shall also
3116 // have no alignment specifier.
3117 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3118 << AA;
3119 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3120 << AA;
3121 NewAttributes.erase(NewAttributes.begin() + I);
3122 --E;
3123 continue;
3125 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3126 // If there is a C definition followed by a redeclaration with this
3127 // attribute then there are two different definitions. In C++, prefer the
3128 // standard diagnostics.
3129 if (!S.getLangOpts().CPlusPlus) {
3130 S.Diag(NewAttribute->getLocation(),
3131 diag::err_loader_uninitialized_redeclaration);
3132 S.Diag(Def->getLocation(), diag::note_previous_definition);
3133 NewAttributes.erase(NewAttributes.begin() + I);
3134 --E;
3135 continue;
3137 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3138 cast<VarDecl>(New)->isInline() &&
3139 !cast<VarDecl>(New)->isInlineSpecified()) {
3140 // Don't warn about applying selectany to implicitly inline variables.
3141 // Older compilers and language modes would require the use of selectany
3142 // to make such variables inline, and it would have no effect if we
3143 // honored it.
3144 ++I;
3145 continue;
3146 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3147 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3148 // declarations after definitions.
3149 ++I;
3150 continue;
3153 S.Diag(NewAttribute->getLocation(),
3154 diag::warn_attribute_precede_definition);
3155 S.Diag(Def->getLocation(), diag::note_previous_definition);
3156 NewAttributes.erase(NewAttributes.begin() + I);
3157 --E;
3161 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3162 const ConstInitAttr *CIAttr,
3163 bool AttrBeforeInit) {
3164 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3166 // Figure out a good way to write this specifier on the old declaration.
3167 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3168 // enough of the attribute list spelling information to extract that without
3169 // heroics.
3170 std::string SuitableSpelling;
3171 if (S.getLangOpts().CPlusPlus20)
3172 SuitableSpelling = std::string(
3173 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3174 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3175 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3176 InsertLoc, {tok::l_square, tok::l_square,
3177 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3178 S.PP.getIdentifierInfo("require_constant_initialization"),
3179 tok::r_square, tok::r_square}));
3180 if (SuitableSpelling.empty())
3181 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3182 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3183 S.PP.getIdentifierInfo("require_constant_initialization"),
3184 tok::r_paren, tok::r_paren}));
3185 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3186 SuitableSpelling = "constinit";
3187 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3188 SuitableSpelling = "[[clang::require_constant_initialization]]";
3189 if (SuitableSpelling.empty())
3190 SuitableSpelling = "__attribute__((require_constant_initialization))";
3191 SuitableSpelling += " ";
3193 if (AttrBeforeInit) {
3194 // extern constinit int a;
3195 // int a = 0; // error (missing 'constinit'), accepted as extension
3196 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3197 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3198 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3199 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3200 } else {
3201 // int a = 0;
3202 // constinit extern int a; // error (missing 'constinit')
3203 S.Diag(CIAttr->getLocation(),
3204 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3205 : diag::warn_require_const_init_added_too_late)
3206 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3207 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3208 << CIAttr->isConstinit()
3209 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3213 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3214 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
3215 AvailabilityMergeKind AMK) {
3216 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3217 UsedAttr *NewAttr = OldAttr->clone(Context);
3218 NewAttr->setInherited(true);
3219 New->addAttr(NewAttr);
3221 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3222 RetainAttr *NewAttr = OldAttr->clone(Context);
3223 NewAttr->setInherited(true);
3224 New->addAttr(NewAttr);
3227 if (!Old->hasAttrs() && !New->hasAttrs())
3228 return;
3230 // [dcl.constinit]p1:
3231 // If the [constinit] specifier is applied to any declaration of a
3232 // variable, it shall be applied to the initializing declaration.
3233 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3234 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3235 if (bool(OldConstInit) != bool(NewConstInit)) {
3236 const auto *OldVD = cast<VarDecl>(Old);
3237 auto *NewVD = cast<VarDecl>(New);
3239 // Find the initializing declaration. Note that we might not have linked
3240 // the new declaration into the redeclaration chain yet.
3241 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3242 if (!InitDecl &&
3243 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3244 InitDecl = NewVD;
3246 if (InitDecl == NewVD) {
3247 // This is the initializing declaration. If it would inherit 'constinit',
3248 // that's ill-formed. (Note that we do not apply this to the attribute
3249 // form).
3250 if (OldConstInit && OldConstInit->isConstinit())
3251 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3252 /*AttrBeforeInit=*/true);
3253 } else if (NewConstInit) {
3254 // This is the first time we've been told that this declaration should
3255 // have a constant initializer. If we already saw the initializing
3256 // declaration, this is too late.
3257 if (InitDecl && InitDecl != NewVD) {
3258 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3259 /*AttrBeforeInit=*/false);
3260 NewVD->dropAttr<ConstInitAttr>();
3265 // Attributes declared post-definition are currently ignored.
3266 checkNewAttributesAfterDef(*this, New, Old);
3268 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3269 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3270 if (!OldA->isEquivalent(NewA)) {
3271 // This redeclaration changes __asm__ label.
3272 Diag(New->getLocation(), diag::err_different_asm_label);
3273 Diag(OldA->getLocation(), diag::note_previous_declaration);
3275 } else if (Old->isUsed()) {
3276 // This redeclaration adds an __asm__ label to a declaration that has
3277 // already been ODR-used.
3278 Diag(New->getLocation(), diag::err_late_asm_label_name)
3279 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3283 // Re-declaration cannot add abi_tag's.
3284 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3285 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3286 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3287 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3288 Diag(NewAbiTagAttr->getLocation(),
3289 diag::err_new_abi_tag_on_redeclaration)
3290 << NewTag;
3291 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3294 } else {
3295 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3296 Diag(Old->getLocation(), diag::note_previous_declaration);
3300 // This redeclaration adds a section attribute.
3301 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3302 if (auto *VD = dyn_cast<VarDecl>(New)) {
3303 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3304 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3305 Diag(Old->getLocation(), diag::note_previous_declaration);
3310 // Redeclaration adds code-seg attribute.
3311 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3312 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3313 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3314 Diag(New->getLocation(), diag::warn_mismatched_section)
3315 << 0 /*codeseg*/;
3316 Diag(Old->getLocation(), diag::note_previous_declaration);
3319 if (!Old->hasAttrs())
3320 return;
3322 bool foundAny = New->hasAttrs();
3324 // Ensure that any moving of objects within the allocated map is done before
3325 // we process them.
3326 if (!foundAny) New->setAttrs(AttrVec());
3328 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3329 // Ignore deprecated/unavailable/availability attributes if requested.
3330 AvailabilityMergeKind LocalAMK = AMK_None;
3331 if (isa<DeprecatedAttr>(I) ||
3332 isa<UnavailableAttr>(I) ||
3333 isa<AvailabilityAttr>(I)) {
3334 switch (AMK) {
3335 case AMK_None:
3336 continue;
3338 case AMK_Redeclaration:
3339 case AMK_Override:
3340 case AMK_ProtocolImplementation:
3341 case AMK_OptionalProtocolImplementation:
3342 LocalAMK = AMK;
3343 break;
3347 // Already handled.
3348 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3349 continue;
3351 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3352 foundAny = true;
3355 if (mergeAlignedAttrs(*this, New, Old))
3356 foundAny = true;
3358 if (!foundAny) New->dropAttrs();
3361 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3362 /// to the new one.
3363 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3364 const ParmVarDecl *oldDecl,
3365 Sema &S) {
3366 // C++11 [dcl.attr.depend]p2:
3367 // The first declaration of a function shall specify the
3368 // carries_dependency attribute for its declarator-id if any declaration
3369 // of the function specifies the carries_dependency attribute.
3370 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3371 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3372 S.Diag(CDA->getLocation(),
3373 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3374 // Find the first declaration of the parameter.
3375 // FIXME: Should we build redeclaration chains for function parameters?
3376 const FunctionDecl *FirstFD =
3377 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3378 const ParmVarDecl *FirstVD =
3379 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3380 S.Diag(FirstVD->getLocation(),
3381 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3384 // HLSL parameter declarations for inout and out must match between
3385 // declarations. In HLSL inout and out are ambiguous at the call site, but
3386 // have different calling behavior, so you cannot overload a method based on a
3387 // difference between inout and out annotations.
3388 if (S.getLangOpts().HLSL) {
3389 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3390 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3391 // We don't need to cover the case where one declaration doesn't have an
3392 // attribute. The only possible case there is if one declaration has an `in`
3393 // attribute and the other declaration has no attribute. This case is
3394 // allowed since parameters are `in` by default.
3395 if (NDAttr && ODAttr &&
3396 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3397 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3398 << NDAttr << newDecl;
3399 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3400 << ODAttr;
3404 if (!oldDecl->hasAttrs())
3405 return;
3407 bool foundAny = newDecl->hasAttrs();
3409 // Ensure that any moving of objects within the allocated map is
3410 // done before we process them.
3411 if (!foundAny) newDecl->setAttrs(AttrVec());
3413 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3414 if (!DeclHasAttr(newDecl, I)) {
3415 InheritableAttr *newAttr =
3416 cast<InheritableParamAttr>(I->clone(S.Context));
3417 newAttr->setInherited(true);
3418 newDecl->addAttr(newAttr);
3419 foundAny = true;
3423 if (!foundAny) newDecl->dropAttrs();
3426 static bool EquivalentArrayTypes(QualType Old, QualType New,
3427 const ASTContext &Ctx) {
3429 auto NoSizeInfo = [&Ctx](QualType Ty) {
3430 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3431 return true;
3432 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3433 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3434 return false;
3437 // `type[]` is equivalent to `type *` and `type[*]`.
3438 if (NoSizeInfo(Old) && NoSizeInfo(New))
3439 return true;
3441 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3442 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3443 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3444 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3445 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3446 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3447 return false;
3448 return true;
3451 // Only compare size, ignore Size modifiers and CVR.
3452 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3453 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3454 Ctx.getAsConstantArrayType(New)->getSize();
3457 // Don't try to compare dependent sized array
3458 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3459 return true;
3462 return Old == New;
3465 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3466 const ParmVarDecl *OldParam,
3467 Sema &S) {
3468 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3469 if (auto Newnullability = NewParam->getType()->getNullability()) {
3470 if (*Oldnullability != *Newnullability) {
3471 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3472 << DiagNullabilityKind(
3473 *Newnullability,
3474 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3475 != 0))
3476 << DiagNullabilityKind(
3477 *Oldnullability,
3478 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3479 != 0));
3480 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3482 } else {
3483 QualType NewT = NewParam->getType();
3484 NewT = S.Context.getAttributedType(
3485 AttributedType::getNullabilityAttrKind(*Oldnullability),
3486 NewT, NewT);
3487 NewParam->setType(NewT);
3490 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3491 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3492 if (OldParamDT && NewParamDT &&
3493 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3494 QualType OldParamOT = OldParamDT->getOriginalType();
3495 QualType NewParamOT = NewParamDT->getOriginalType();
3496 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3497 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3498 << NewParam << NewParamOT;
3499 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3500 << OldParamOT;
3505 namespace {
3507 /// Used in MergeFunctionDecl to keep track of function parameters in
3508 /// C.
3509 struct GNUCompatibleParamWarning {
3510 ParmVarDecl *OldParm;
3511 ParmVarDecl *NewParm;
3512 QualType PromotedType;
3515 } // end anonymous namespace
3517 // Determine whether the previous declaration was a definition, implicit
3518 // declaration, or a declaration.
3519 template <typename T>
3520 static std::pair<diag::kind, SourceLocation>
3521 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3522 diag::kind PrevDiag;
3523 SourceLocation OldLocation = Old->getLocation();
3524 if (Old->isThisDeclarationADefinition())
3525 PrevDiag = diag::note_previous_definition;
3526 else if (Old->isImplicit()) {
3527 PrevDiag = diag::note_previous_implicit_declaration;
3528 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3529 if (FD->getBuiltinID())
3530 PrevDiag = diag::note_previous_builtin_declaration;
3532 if (OldLocation.isInvalid())
3533 OldLocation = New->getLocation();
3534 } else
3535 PrevDiag = diag::note_previous_declaration;
3536 return std::make_pair(PrevDiag, OldLocation);
3539 /// canRedefineFunction - checks if a function can be redefined. Currently,
3540 /// only extern inline functions can be redefined, and even then only in
3541 /// GNU89 mode.
3542 static bool canRedefineFunction(const FunctionDecl *FD,
3543 const LangOptions& LangOpts) {
3544 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3545 !LangOpts.CPlusPlus &&
3546 FD->isInlineSpecified() &&
3547 FD->getStorageClass() == SC_Extern);
3550 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3551 const AttributedType *AT = T->getAs<AttributedType>();
3552 while (AT && !AT->isCallingConv())
3553 AT = AT->getModifiedType()->getAs<AttributedType>();
3554 return AT;
3557 template <typename T>
3558 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3559 const DeclContext *DC = Old->getDeclContext();
3560 if (DC->isRecord())
3561 return false;
3563 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3564 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3565 return true;
3566 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3567 return true;
3568 return false;
3571 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3572 static bool isExternC(VarTemplateDecl *) { return false; }
3573 static bool isExternC(FunctionTemplateDecl *) { return false; }
3575 /// Check whether a redeclaration of an entity introduced by a
3576 /// using-declaration is valid, given that we know it's not an overload
3577 /// (nor a hidden tag declaration).
3578 template<typename ExpectedDecl>
3579 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3580 ExpectedDecl *New) {
3581 // C++11 [basic.scope.declarative]p4:
3582 // Given a set of declarations in a single declarative region, each of
3583 // which specifies the same unqualified name,
3584 // -- they shall all refer to the same entity, or all refer to functions
3585 // and function templates; or
3586 // -- exactly one declaration shall declare a class name or enumeration
3587 // name that is not a typedef name and the other declarations shall all
3588 // refer to the same variable or enumerator, or all refer to functions
3589 // and function templates; in this case the class name or enumeration
3590 // name is hidden (3.3.10).
3592 // C++11 [namespace.udecl]p14:
3593 // If a function declaration in namespace scope or block scope has the
3594 // same name and the same parameter-type-list as a function introduced
3595 // by a using-declaration, and the declarations do not declare the same
3596 // function, the program is ill-formed.
3598 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3599 if (Old &&
3600 !Old->getDeclContext()->getRedeclContext()->Equals(
3601 New->getDeclContext()->getRedeclContext()) &&
3602 !(isExternC(Old) && isExternC(New)))
3603 Old = nullptr;
3605 if (!Old) {
3606 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3607 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3608 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3609 return true;
3611 return false;
3614 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3615 const FunctionDecl *B) {
3616 assert(A->getNumParams() == B->getNumParams());
3618 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3619 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3620 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3621 if (AttrA == AttrB)
3622 return true;
3623 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3624 AttrA->isDynamic() == AttrB->isDynamic();
3627 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3630 /// If necessary, adjust the semantic declaration context for a qualified
3631 /// declaration to name the correct inline namespace within the qualifier.
3632 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3633 DeclaratorDecl *OldD) {
3634 // The only case where we need to update the DeclContext is when
3635 // redeclaration lookup for a qualified name finds a declaration
3636 // in an inline namespace within the context named by the qualifier:
3638 // inline namespace N { int f(); }
3639 // int ::f(); // Sema DC needs adjusting from :: to N::.
3641 // For unqualified declarations, the semantic context *can* change
3642 // along the redeclaration chain (for local extern declarations,
3643 // extern "C" declarations, and friend declarations in particular).
3644 if (!NewD->getQualifier())
3645 return;
3647 // NewD is probably already in the right context.
3648 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3649 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3650 if (NamedDC->Equals(SemaDC))
3651 return;
3653 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3654 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3655 "unexpected context for redeclaration");
3657 auto *LexDC = NewD->getLexicalDeclContext();
3658 auto FixSemaDC = [=](NamedDecl *D) {
3659 if (!D)
3660 return;
3661 D->setDeclContext(SemaDC);
3662 D->setLexicalDeclContext(LexDC);
3665 FixSemaDC(NewD);
3666 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3667 FixSemaDC(FD->getDescribedFunctionTemplate());
3668 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3669 FixSemaDC(VD->getDescribedVarTemplate());
3672 /// MergeFunctionDecl - We just parsed a function 'New' from
3673 /// declarator D which has the same name and scope as a previous
3674 /// declaration 'Old'. Figure out how to resolve this situation,
3675 /// merging decls or emitting diagnostics as appropriate.
3677 /// In C++, New and Old must be declarations that are not
3678 /// overloaded. Use IsOverload to determine whether New and Old are
3679 /// overloaded, and to select the Old declaration that New should be
3680 /// merged with.
3682 /// Returns true if there was an error, false otherwise.
3683 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
3684 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3685 // Verify the old decl was also a function.
3686 FunctionDecl *Old = OldD->getAsFunction();
3687 if (!Old) {
3688 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3689 if (New->getFriendObjectKind()) {
3690 Diag(New->getLocation(), diag::err_using_decl_friend);
3691 Diag(Shadow->getTargetDecl()->getLocation(),
3692 diag::note_using_decl_target);
3693 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3694 << 0;
3695 return true;
3698 // Check whether the two declarations might declare the same function or
3699 // function template.
3700 if (FunctionTemplateDecl *NewTemplate =
3701 New->getDescribedFunctionTemplate()) {
3702 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3703 NewTemplate))
3704 return true;
3705 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3706 ->getAsFunction();
3707 } else {
3708 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3709 return true;
3710 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3712 } else {
3713 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3714 << New->getDeclName();
3715 notePreviousDefinition(OldD, New->getLocation());
3716 return true;
3720 // If the old declaration was found in an inline namespace and the new
3721 // declaration was qualified, update the DeclContext to match.
3722 adjustDeclContextForDeclaratorDecl(New, Old);
3724 // If the old declaration is invalid, just give up here.
3725 if (Old->isInvalidDecl())
3726 return true;
3728 // Disallow redeclaration of some builtins.
3729 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3730 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3731 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3732 << Old << Old->getType();
3733 return true;
3736 diag::kind PrevDiag;
3737 SourceLocation OldLocation;
3738 std::tie(PrevDiag, OldLocation) =
3739 getNoteDiagForInvalidRedeclaration(Old, New);
3741 // Don't complain about this if we're in GNU89 mode and the old function
3742 // is an extern inline function.
3743 // Don't complain about specializations. They are not supposed to have
3744 // storage classes.
3745 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3746 New->getStorageClass() == SC_Static &&
3747 Old->hasExternalFormalLinkage() &&
3748 !New->getTemplateSpecializationInfo() &&
3749 !canRedefineFunction(Old, getLangOpts())) {
3750 if (getLangOpts().MicrosoftExt) {
3751 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3752 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3753 } else {
3754 Diag(New->getLocation(), diag::err_static_non_static) << New;
3755 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3756 return true;
3760 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3761 if (!Old->hasAttr<InternalLinkageAttr>()) {
3762 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3763 << ILA;
3764 Diag(Old->getLocation(), diag::note_previous_declaration);
3765 New->dropAttr<InternalLinkageAttr>();
3768 if (auto *EA = New->getAttr<ErrorAttr>()) {
3769 if (!Old->hasAttr<ErrorAttr>()) {
3770 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3771 Diag(Old->getLocation(), diag::note_previous_declaration);
3772 New->dropAttr<ErrorAttr>();
3776 if (CheckRedeclarationInModule(New, Old))
3777 return true;
3779 if (!getLangOpts().CPlusPlus) {
3780 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3781 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3782 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3783 << New << OldOvl;
3785 // Try our best to find a decl that actually has the overloadable
3786 // attribute for the note. In most cases (e.g. programs with only one
3787 // broken declaration/definition), this won't matter.
3789 // FIXME: We could do this if we juggled some extra state in
3790 // OverloadableAttr, rather than just removing it.
3791 const Decl *DiagOld = Old;
3792 if (OldOvl) {
3793 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3794 const auto *A = D->getAttr<OverloadableAttr>();
3795 return A && !A->isImplicit();
3797 // If we've implicitly added *all* of the overloadable attrs to this
3798 // chain, emitting a "previous redecl" note is pointless.
3799 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3802 if (DiagOld)
3803 Diag(DiagOld->getLocation(),
3804 diag::note_attribute_overloadable_prev_overload)
3805 << OldOvl;
3807 if (OldOvl)
3808 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3809 else
3810 New->dropAttr<OverloadableAttr>();
3814 // It is not permitted to redeclare an SME function with different SME
3815 // attributes.
3816 if (IsInvalidSMECallConversion(Old->getType(), New->getType(),
3817 AArch64SMECallConversionKind::MatchExactly)) {
3818 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3819 << New->getType() << Old->getType();
3820 Diag(OldLocation, diag::note_previous_declaration);
3821 return true;
3824 // If a function is first declared with a calling convention, but is later
3825 // declared or defined without one, all following decls assume the calling
3826 // convention of the first.
3828 // It's OK if a function is first declared without a calling convention,
3829 // but is later declared or defined with the default calling convention.
3831 // To test if either decl has an explicit calling convention, we look for
3832 // AttributedType sugar nodes on the type as written. If they are missing or
3833 // were canonicalized away, we assume the calling convention was implicit.
3835 // Note also that we DO NOT return at this point, because we still have
3836 // other tests to run.
3837 QualType OldQType = Context.getCanonicalType(Old->getType());
3838 QualType NewQType = Context.getCanonicalType(New->getType());
3839 const FunctionType *OldType = cast<FunctionType>(OldQType);
3840 const FunctionType *NewType = cast<FunctionType>(NewQType);
3841 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3842 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3843 bool RequiresAdjustment = false;
3845 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3846 FunctionDecl *First = Old->getFirstDecl();
3847 const FunctionType *FT =
3848 First->getType().getCanonicalType()->castAs<FunctionType>();
3849 FunctionType::ExtInfo FI = FT->getExtInfo();
3850 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3851 if (!NewCCExplicit) {
3852 // Inherit the CC from the previous declaration if it was specified
3853 // there but not here.
3854 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3855 RequiresAdjustment = true;
3856 } else if (Old->getBuiltinID()) {
3857 // Builtin attribute isn't propagated to the new one yet at this point,
3858 // so we check if the old one is a builtin.
3860 // Calling Conventions on a Builtin aren't really useful and setting a
3861 // default calling convention and cdecl'ing some builtin redeclarations is
3862 // common, so warn and ignore the calling convention on the redeclaration.
3863 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3864 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3865 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3866 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3867 RequiresAdjustment = true;
3868 } else {
3869 // Calling conventions aren't compatible, so complain.
3870 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3871 Diag(New->getLocation(), diag::err_cconv_change)
3872 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3873 << !FirstCCExplicit
3874 << (!FirstCCExplicit ? "" :
3875 FunctionType::getNameForCallConv(FI.getCC()));
3877 // Put the note on the first decl, since it is the one that matters.
3878 Diag(First->getLocation(), diag::note_previous_declaration);
3879 return true;
3883 // FIXME: diagnose the other way around?
3884 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3885 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3886 RequiresAdjustment = true;
3889 // Merge regparm attribute.
3890 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3891 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3892 if (NewTypeInfo.getHasRegParm()) {
3893 Diag(New->getLocation(), diag::err_regparm_mismatch)
3894 << NewType->getRegParmType()
3895 << OldType->getRegParmType();
3896 Diag(OldLocation, diag::note_previous_declaration);
3897 return true;
3900 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3901 RequiresAdjustment = true;
3904 // Merge ns_returns_retained attribute.
3905 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3906 if (NewTypeInfo.getProducesResult()) {
3907 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3908 << "'ns_returns_retained'";
3909 Diag(OldLocation, diag::note_previous_declaration);
3910 return true;
3913 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3914 RequiresAdjustment = true;
3917 if (OldTypeInfo.getNoCallerSavedRegs() !=
3918 NewTypeInfo.getNoCallerSavedRegs()) {
3919 if (NewTypeInfo.getNoCallerSavedRegs()) {
3920 AnyX86NoCallerSavedRegistersAttr *Attr =
3921 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3922 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3923 Diag(OldLocation, diag::note_previous_declaration);
3924 return true;
3927 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3928 RequiresAdjustment = true;
3931 if (RequiresAdjustment) {
3932 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3933 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3934 New->setType(QualType(AdjustedType, 0));
3935 NewQType = Context.getCanonicalType(New->getType());
3938 // If this redeclaration makes the function inline, we may need to add it to
3939 // UndefinedButUsed.
3940 if (!Old->isInlined() && New->isInlined() &&
3941 !New->hasAttr<GNUInlineAttr>() &&
3942 !getLangOpts().GNUInline &&
3943 Old->isUsed(false) &&
3944 !Old->isDefined() && !New->isThisDeclarationADefinition())
3945 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3946 SourceLocation()));
3948 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3949 // about it.
3950 if (New->hasAttr<GNUInlineAttr>() &&
3951 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3952 UndefinedButUsed.erase(Old->getCanonicalDecl());
3955 // If pass_object_size params don't match up perfectly, this isn't a valid
3956 // redeclaration.
3957 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3958 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3959 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3960 << New->getDeclName();
3961 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3962 return true;
3965 if (getLangOpts().CPlusPlus) {
3966 OldQType = Context.getCanonicalType(Old->getType());
3967 NewQType = Context.getCanonicalType(New->getType());
3969 // Go back to the type source info to compare the declared return types,
3970 // per C++1y [dcl.type.auto]p13:
3971 // Redeclarations or specializations of a function or function template
3972 // with a declared return type that uses a placeholder type shall also
3973 // use that placeholder, not a deduced type.
3974 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3975 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3976 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3977 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3978 OldDeclaredReturnType)) {
3979 QualType ResQT;
3980 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3981 OldDeclaredReturnType->isObjCObjectPointerType())
3982 // FIXME: This does the wrong thing for a deduced return type.
3983 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3984 if (ResQT.isNull()) {
3985 if (New->isCXXClassMember() && New->isOutOfLine())
3986 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3987 << New << New->getReturnTypeSourceRange();
3988 else
3989 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3990 << New->getReturnTypeSourceRange();
3991 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3992 << Old->getReturnTypeSourceRange();
3993 return true;
3995 else
3996 NewQType = ResQT;
3999 QualType OldReturnType = OldType->getReturnType();
4000 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4001 if (OldReturnType != NewReturnType) {
4002 // If this function has a deduced return type and has already been
4003 // defined, copy the deduced value from the old declaration.
4004 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4005 if (OldAT && OldAT->isDeduced()) {
4006 QualType DT = OldAT->getDeducedType();
4007 if (DT.isNull()) {
4008 New->setType(SubstAutoTypeDependent(New->getType()));
4009 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4010 } else {
4011 New->setType(SubstAutoType(New->getType(), DT));
4012 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4017 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4018 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4019 if (OldMethod && NewMethod) {
4020 // Preserve triviality.
4021 NewMethod->setTrivial(OldMethod->isTrivial());
4023 // MSVC allows explicit template specialization at class scope:
4024 // 2 CXXMethodDecls referring to the same function will be injected.
4025 // We don't want a redeclaration error.
4026 bool IsClassScopeExplicitSpecialization =
4027 OldMethod->isFunctionTemplateSpecialization() &&
4028 NewMethod->isFunctionTemplateSpecialization();
4029 bool isFriend = NewMethod->getFriendObjectKind();
4031 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4032 !IsClassScopeExplicitSpecialization) {
4033 // -- Member function declarations with the same name and the
4034 // same parameter types cannot be overloaded if any of them
4035 // is a static member function declaration.
4036 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4037 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4038 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4039 return true;
4042 // C++ [class.mem]p1:
4043 // [...] A member shall not be declared twice in the
4044 // member-specification, except that a nested class or member
4045 // class template can be declared and then later defined.
4046 if (!inTemplateInstantiation()) {
4047 unsigned NewDiag;
4048 if (isa<CXXConstructorDecl>(OldMethod))
4049 NewDiag = diag::err_constructor_redeclared;
4050 else if (isa<CXXDestructorDecl>(NewMethod))
4051 NewDiag = diag::err_destructor_redeclared;
4052 else if (isa<CXXConversionDecl>(NewMethod))
4053 NewDiag = diag::err_conv_function_redeclared;
4054 else
4055 NewDiag = diag::err_member_redeclared;
4057 Diag(New->getLocation(), NewDiag);
4058 } else {
4059 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4060 << New << New->getType();
4062 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4063 return true;
4065 // Complain if this is an explicit declaration of a special
4066 // member that was initially declared implicitly.
4068 // As an exception, it's okay to befriend such methods in order
4069 // to permit the implicit constructor/destructor/operator calls.
4070 } else if (OldMethod->isImplicit()) {
4071 if (isFriend) {
4072 NewMethod->setImplicit();
4073 } else {
4074 Diag(NewMethod->getLocation(),
4075 diag::err_definition_of_implicitly_declared_member)
4076 << New << getSpecialMember(OldMethod);
4077 return true;
4079 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4080 Diag(NewMethod->getLocation(),
4081 diag::err_definition_of_explicitly_defaulted_member)
4082 << getSpecialMember(OldMethod);
4083 return true;
4087 // C++1z [over.load]p2
4088 // Certain function declarations cannot be overloaded:
4089 // -- Function declarations that differ only in the return type,
4090 // the exception specification, or both cannot be overloaded.
4092 // Check the exception specifications match. This may recompute the type of
4093 // both Old and New if it resolved exception specifications, so grab the
4094 // types again after this. Because this updates the type, we do this before
4095 // any of the other checks below, which may update the "de facto" NewQType
4096 // but do not necessarily update the type of New.
4097 if (CheckEquivalentExceptionSpec(Old, New))
4098 return true;
4100 // C++11 [dcl.attr.noreturn]p1:
4101 // The first declaration of a function shall specify the noreturn
4102 // attribute if any declaration of that function specifies the noreturn
4103 // attribute.
4104 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4105 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4106 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4107 << NRA;
4108 Diag(Old->getLocation(), diag::note_previous_declaration);
4111 // C++11 [dcl.attr.depend]p2:
4112 // The first declaration of a function shall specify the
4113 // carries_dependency attribute for its declarator-id if any declaration
4114 // of the function specifies the carries_dependency attribute.
4115 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4116 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4117 Diag(CDA->getLocation(),
4118 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4119 Diag(Old->getFirstDecl()->getLocation(),
4120 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4123 // (C++98 8.3.5p3):
4124 // All declarations for a function shall agree exactly in both the
4125 // return type and the parameter-type-list.
4126 // We also want to respect all the extended bits except noreturn.
4128 // noreturn should now match unless the old type info didn't have it.
4129 QualType OldQTypeForComparison = OldQType;
4130 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4131 auto *OldType = OldQType->castAs<FunctionProtoType>();
4132 const FunctionType *OldTypeForComparison
4133 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4134 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4135 assert(OldQTypeForComparison.isCanonical());
4138 if (haveIncompatibleLanguageLinkages(Old, New)) {
4139 // As a special case, retain the language linkage from previous
4140 // declarations of a friend function as an extension.
4142 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4143 // and is useful because there's otherwise no way to specify language
4144 // linkage within class scope.
4146 // Check cautiously as the friend object kind isn't yet complete.
4147 if (New->getFriendObjectKind() != Decl::FOK_None) {
4148 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4149 Diag(OldLocation, PrevDiag);
4150 } else {
4151 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4152 Diag(OldLocation, PrevDiag);
4153 return true;
4157 // If the function types are compatible, merge the declarations. Ignore the
4158 // exception specifier because it was already checked above in
4159 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4160 // about incompatible types under -fms-compatibility.
4161 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4162 NewQType))
4163 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4165 // If the types are imprecise (due to dependent constructs in friends or
4166 // local extern declarations), it's OK if they differ. We'll check again
4167 // during instantiation.
4168 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4169 return false;
4171 // Fall through for conflicting redeclarations and redefinitions.
4174 // C: Function types need to be compatible, not identical. This handles
4175 // duplicate function decls like "void f(int); void f(enum X);" properly.
4176 if (!getLangOpts().CPlusPlus) {
4177 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4178 // type is specified by a function definition that contains a (possibly
4179 // empty) identifier list, both shall agree in the number of parameters
4180 // and the type of each parameter shall be compatible with the type that
4181 // results from the application of default argument promotions to the
4182 // type of the corresponding identifier. ...
4183 // This cannot be handled by ASTContext::typesAreCompatible() because that
4184 // doesn't know whether the function type is for a definition or not when
4185 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4186 // we need to cover here is that the number of arguments agree as the
4187 // default argument promotion rules were already checked by
4188 // ASTContext::typesAreCompatible().
4189 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4190 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4191 if (Old->hasInheritedPrototype())
4192 Old = Old->getCanonicalDecl();
4193 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4194 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4195 return true;
4198 // If we are merging two functions where only one of them has a prototype,
4199 // we may have enough information to decide to issue a diagnostic that the
4200 // function without a protoype will change behavior in C23. This handles
4201 // cases like:
4202 // void i(); void i(int j);
4203 // void i(int j); void i();
4204 // void i(); void i(int j) {}
4205 // See ActOnFinishFunctionBody() for other cases of the behavior change
4206 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4207 // type without a prototype.
4208 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4209 !New->isImplicit() && !Old->isImplicit()) {
4210 const FunctionDecl *WithProto, *WithoutProto;
4211 if (New->hasWrittenPrototype()) {
4212 WithProto = New;
4213 WithoutProto = Old;
4214 } else {
4215 WithProto = Old;
4216 WithoutProto = New;
4219 if (WithProto->getNumParams() != 0) {
4220 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4221 // The one without the prototype will be changing behavior in C23, so
4222 // warn about that one so long as it's a user-visible declaration.
4223 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4224 if (WithoutProto == New)
4225 IsWithoutProtoADef = NewDeclIsDefn;
4226 else
4227 IsWithProtoADef = NewDeclIsDefn;
4228 Diag(WithoutProto->getLocation(),
4229 diag::warn_non_prototype_changes_behavior)
4230 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4231 << (WithoutProto == Old) << IsWithProtoADef;
4233 // The reason the one without the prototype will be changing behavior
4234 // is because of the one with the prototype, so note that so long as
4235 // it's a user-visible declaration. There is one exception to this:
4236 // when the new declaration is a definition without a prototype, the
4237 // old declaration with a prototype is not the cause of the issue,
4238 // and that does not need to be noted because the one with a
4239 // prototype will not change behavior in C23.
4240 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4241 !IsWithoutProtoADef)
4242 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4247 if (Context.typesAreCompatible(OldQType, NewQType)) {
4248 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4249 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4250 const FunctionProtoType *OldProto = nullptr;
4251 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4252 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4253 // The old declaration provided a function prototype, but the
4254 // new declaration does not. Merge in the prototype.
4255 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4256 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4257 OldProto->getParamTypes(),
4258 OldProto->getExtProtoInfo());
4259 New->setType(NewQType);
4260 New->setHasInheritedPrototype();
4262 // Synthesize parameters with the same types.
4263 SmallVector<ParmVarDecl *, 16> Params;
4264 for (const auto &ParamType : OldProto->param_types()) {
4265 ParmVarDecl *Param = ParmVarDecl::Create(
4266 Context, New, SourceLocation(), SourceLocation(), nullptr,
4267 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4268 Param->setScopeInfo(0, Params.size());
4269 Param->setImplicit();
4270 Params.push_back(Param);
4273 New->setParams(Params);
4276 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4280 // Check if the function types are compatible when pointer size address
4281 // spaces are ignored.
4282 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4283 return false;
4285 // GNU C permits a K&R definition to follow a prototype declaration
4286 // if the declared types of the parameters in the K&R definition
4287 // match the types in the prototype declaration, even when the
4288 // promoted types of the parameters from the K&R definition differ
4289 // from the types in the prototype. GCC then keeps the types from
4290 // the prototype.
4292 // If a variadic prototype is followed by a non-variadic K&R definition,
4293 // the K&R definition becomes variadic. This is sort of an edge case, but
4294 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4295 // C99 6.9.1p8.
4296 if (!getLangOpts().CPlusPlus &&
4297 Old->hasPrototype() && !New->hasPrototype() &&
4298 New->getType()->getAs<FunctionProtoType>() &&
4299 Old->getNumParams() == New->getNumParams()) {
4300 SmallVector<QualType, 16> ArgTypes;
4301 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
4302 const FunctionProtoType *OldProto
4303 = Old->getType()->getAs<FunctionProtoType>();
4304 const FunctionProtoType *NewProto
4305 = New->getType()->getAs<FunctionProtoType>();
4307 // Determine whether this is the GNU C extension.
4308 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4309 NewProto->getReturnType());
4310 bool LooseCompatible = !MergedReturn.isNull();
4311 for (unsigned Idx = 0, End = Old->getNumParams();
4312 LooseCompatible && Idx != End; ++Idx) {
4313 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4314 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4315 if (Context.typesAreCompatible(OldParm->getType(),
4316 NewProto->getParamType(Idx))) {
4317 ArgTypes.push_back(NewParm->getType());
4318 } else if (Context.typesAreCompatible(OldParm->getType(),
4319 NewParm->getType(),
4320 /*CompareUnqualified=*/true)) {
4321 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4322 NewProto->getParamType(Idx) };
4323 Warnings.push_back(Warn);
4324 ArgTypes.push_back(NewParm->getType());
4325 } else
4326 LooseCompatible = false;
4329 if (LooseCompatible) {
4330 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4331 Diag(Warnings[Warn].NewParm->getLocation(),
4332 diag::ext_param_promoted_not_compatible_with_prototype)
4333 << Warnings[Warn].PromotedType
4334 << Warnings[Warn].OldParm->getType();
4335 if (Warnings[Warn].OldParm->getLocation().isValid())
4336 Diag(Warnings[Warn].OldParm->getLocation(),
4337 diag::note_previous_declaration);
4340 if (MergeTypeWithOld)
4341 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4342 OldProto->getExtProtoInfo()));
4343 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4346 // Fall through to diagnose conflicting types.
4349 // A function that has already been declared has been redeclared or
4350 // defined with a different type; show an appropriate diagnostic.
4352 // If the previous declaration was an implicitly-generated builtin
4353 // declaration, then at the very least we should use a specialized note.
4354 unsigned BuiltinID;
4355 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4356 // If it's actually a library-defined builtin function like 'malloc'
4357 // or 'printf', just warn about the incompatible redeclaration.
4358 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4359 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4360 Diag(OldLocation, diag::note_previous_builtin_declaration)
4361 << Old << Old->getType();
4362 return false;
4365 PrevDiag = diag::note_previous_builtin_declaration;
4368 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4369 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4370 return true;
4373 /// Completes the merge of two function declarations that are
4374 /// known to be compatible.
4376 /// This routine handles the merging of attributes and other
4377 /// properties of function declarations from the old declaration to
4378 /// the new declaration, once we know that New is in fact a
4379 /// redeclaration of Old.
4381 /// \returns false
4382 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4383 Scope *S, bool MergeTypeWithOld) {
4384 // Merge the attributes
4385 mergeDeclAttributes(New, Old);
4387 // Merge "pure" flag.
4388 if (Old->isPure())
4389 New->setPure();
4391 // Merge "used" flag.
4392 if (Old->getMostRecentDecl()->isUsed(false))
4393 New->setIsUsed();
4395 // Merge attributes from the parameters. These can mismatch with K&R
4396 // declarations.
4397 if (New->getNumParams() == Old->getNumParams())
4398 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4399 ParmVarDecl *NewParam = New->getParamDecl(i);
4400 ParmVarDecl *OldParam = Old->getParamDecl(i);
4401 mergeParamDeclAttributes(NewParam, OldParam, *this);
4402 mergeParamDeclTypes(NewParam, OldParam, *this);
4405 if (getLangOpts().CPlusPlus)
4406 return MergeCXXFunctionDecl(New, Old, S);
4408 // Merge the function types so the we get the composite types for the return
4409 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4410 // was visible.
4411 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4412 if (!Merged.isNull() && MergeTypeWithOld)
4413 New->setType(Merged);
4415 return false;
4418 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
4419 ObjCMethodDecl *oldMethod) {
4420 // Merge the attributes, including deprecated/unavailable
4421 AvailabilityMergeKind MergeKind =
4422 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4423 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4424 : AMK_ProtocolImplementation)
4425 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4426 : AMK_Override;
4428 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4430 // Merge attributes from the parameters.
4431 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
4432 oe = oldMethod->param_end();
4433 for (ObjCMethodDecl::param_iterator
4434 ni = newMethod->param_begin(), ne = newMethod->param_end();
4435 ni != ne && oi != oe; ++ni, ++oi)
4436 mergeParamDeclAttributes(*ni, *oi, *this);
4438 CheckObjCMethodOverride(newMethod, oldMethod);
4441 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4442 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4444 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4445 ? diag::err_redefinition_different_type
4446 : diag::err_redeclaration_different_type)
4447 << New->getDeclName() << New->getType() << Old->getType();
4449 diag::kind PrevDiag;
4450 SourceLocation OldLocation;
4451 std::tie(PrevDiag, OldLocation)
4452 = getNoteDiagForInvalidRedeclaration(Old, New);
4453 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4454 New->setInvalidDecl();
4457 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4458 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
4459 /// emitting diagnostics as appropriate.
4461 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4462 /// to here in AddInitializerToDecl. We can't check them before the initializer
4463 /// is attached.
4464 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
4465 bool MergeTypeWithOld) {
4466 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4467 return;
4469 QualType MergedT;
4470 if (getLangOpts().CPlusPlus) {
4471 if (New->getType()->isUndeducedType()) {
4472 // We don't know what the new type is until the initializer is attached.
4473 return;
4474 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4475 // These could still be something that needs exception specs checked.
4476 return MergeVarDeclExceptionSpecs(New, Old);
4478 // C++ [basic.link]p10:
4479 // [...] the types specified by all declarations referring to a given
4480 // object or function shall be identical, except that declarations for an
4481 // array object can specify array types that differ by the presence or
4482 // absence of a major array bound (8.3.4).
4483 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4484 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4485 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4487 // We are merging a variable declaration New into Old. If it has an array
4488 // bound, and that bound differs from Old's bound, we should diagnose the
4489 // mismatch.
4490 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4491 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4492 PrevVD = PrevVD->getPreviousDecl()) {
4493 QualType PrevVDTy = PrevVD->getType();
4494 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4495 continue;
4497 if (!Context.hasSameType(New->getType(), PrevVDTy))
4498 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4502 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4503 if (Context.hasSameType(OldArray->getElementType(),
4504 NewArray->getElementType()))
4505 MergedT = New->getType();
4507 // FIXME: Check visibility. New is hidden but has a complete type. If New
4508 // has no array bound, it should not inherit one from Old, if Old is not
4509 // visible.
4510 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4511 if (Context.hasSameType(OldArray->getElementType(),
4512 NewArray->getElementType()))
4513 MergedT = Old->getType();
4516 else if (New->getType()->isObjCObjectPointerType() &&
4517 Old->getType()->isObjCObjectPointerType()) {
4518 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4519 Old->getType());
4521 } else {
4522 // C 6.2.7p2:
4523 // All declarations that refer to the same object or function shall have
4524 // compatible type.
4525 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4527 if (MergedT.isNull()) {
4528 // It's OK if we couldn't merge types if either type is dependent, for a
4529 // block-scope variable. In other cases (static data members of class
4530 // templates, variable templates, ...), we require the types to be
4531 // equivalent.
4532 // FIXME: The C++ standard doesn't say anything about this.
4533 if ((New->getType()->isDependentType() ||
4534 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4535 // If the old type was dependent, we can't merge with it, so the new type
4536 // becomes dependent for now. We'll reproduce the original type when we
4537 // instantiate the TypeSourceInfo for the variable.
4538 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4539 New->setType(Context.DependentTy);
4540 return;
4542 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4545 // Don't actually update the type on the new declaration if the old
4546 // declaration was an extern declaration in a different scope.
4547 if (MergeTypeWithOld)
4548 New->setType(MergedT);
4551 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4552 LookupResult &Previous) {
4553 // C11 6.2.7p4:
4554 // For an identifier with internal or external linkage declared
4555 // in a scope in which a prior declaration of that identifier is
4556 // visible, if the prior declaration specifies internal or
4557 // external linkage, the type of the identifier at the later
4558 // declaration becomes the composite type.
4560 // If the variable isn't visible, we do not merge with its type.
4561 if (Previous.isShadowed())
4562 return false;
4564 if (S.getLangOpts().CPlusPlus) {
4565 // C++11 [dcl.array]p3:
4566 // If there is a preceding declaration of the entity in the same
4567 // scope in which the bound was specified, an omitted array bound
4568 // is taken to be the same as in that earlier declaration.
4569 return NewVD->isPreviousDeclInSameBlockScope() ||
4570 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4571 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4572 } else {
4573 // If the old declaration was function-local, don't merge with its
4574 // type unless we're in the same function.
4575 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4576 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4580 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4581 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4582 /// situation, merging decls or emitting diagnostics as appropriate.
4584 /// Tentative definition rules (C99 6.9.2p2) are checked by
4585 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4586 /// definitions here, since the initializer hasn't been attached.
4588 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4589 // If the new decl is already invalid, don't do any other checking.
4590 if (New->isInvalidDecl())
4591 return;
4593 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4594 return;
4596 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4598 // Verify the old decl was also a variable or variable template.
4599 VarDecl *Old = nullptr;
4600 VarTemplateDecl *OldTemplate = nullptr;
4601 if (Previous.isSingleResult()) {
4602 if (NewTemplate) {
4603 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4604 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4606 if (auto *Shadow =
4607 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4608 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4609 return New->setInvalidDecl();
4610 } else {
4611 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4613 if (auto *Shadow =
4614 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4615 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4616 return New->setInvalidDecl();
4619 if (!Old) {
4620 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4621 << New->getDeclName();
4622 notePreviousDefinition(Previous.getRepresentativeDecl(),
4623 New->getLocation());
4624 return New->setInvalidDecl();
4627 // If the old declaration was found in an inline namespace and the new
4628 // declaration was qualified, update the DeclContext to match.
4629 adjustDeclContextForDeclaratorDecl(New, Old);
4631 // Ensure the template parameters are compatible.
4632 if (NewTemplate &&
4633 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4634 OldTemplate->getTemplateParameters(),
4635 /*Complain=*/true, TPL_TemplateMatch))
4636 return New->setInvalidDecl();
4638 // C++ [class.mem]p1:
4639 // A member shall not be declared twice in the member-specification [...]
4641 // Here, we need only consider static data members.
4642 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4643 Diag(New->getLocation(), diag::err_duplicate_member)
4644 << New->getIdentifier();
4645 Diag(Old->getLocation(), diag::note_previous_declaration);
4646 New->setInvalidDecl();
4649 mergeDeclAttributes(New, Old);
4650 // Warn if an already-declared variable is made a weak_import in a subsequent
4651 // declaration
4652 if (New->hasAttr<WeakImportAttr>() &&
4653 Old->getStorageClass() == SC_None &&
4654 !Old->hasAttr<WeakImportAttr>()) {
4655 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4656 Diag(Old->getLocation(), diag::note_previous_declaration);
4657 // Remove weak_import attribute on new declaration.
4658 New->dropAttr<WeakImportAttr>();
4661 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4662 if (!Old->hasAttr<InternalLinkageAttr>()) {
4663 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4664 << ILA;
4665 Diag(Old->getLocation(), diag::note_previous_declaration);
4666 New->dropAttr<InternalLinkageAttr>();
4669 // Merge the types.
4670 VarDecl *MostRecent = Old->getMostRecentDecl();
4671 if (MostRecent != Old) {
4672 MergeVarDeclTypes(New, MostRecent,
4673 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4674 if (New->isInvalidDecl())
4675 return;
4678 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4679 if (New->isInvalidDecl())
4680 return;
4682 diag::kind PrevDiag;
4683 SourceLocation OldLocation;
4684 std::tie(PrevDiag, OldLocation) =
4685 getNoteDiagForInvalidRedeclaration(Old, New);
4687 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4688 if (New->getStorageClass() == SC_Static &&
4689 !New->isStaticDataMember() &&
4690 Old->hasExternalFormalLinkage()) {
4691 if (getLangOpts().MicrosoftExt) {
4692 Diag(New->getLocation(), diag::ext_static_non_static)
4693 << New->getDeclName();
4694 Diag(OldLocation, PrevDiag);
4695 } else {
4696 Diag(New->getLocation(), diag::err_static_non_static)
4697 << New->getDeclName();
4698 Diag(OldLocation, PrevDiag);
4699 return New->setInvalidDecl();
4702 // C99 6.2.2p4:
4703 // For an identifier declared with the storage-class specifier
4704 // extern in a scope in which a prior declaration of that
4705 // identifier is visible,23) if the prior declaration specifies
4706 // internal or external linkage, the linkage of the identifier at
4707 // the later declaration is the same as the linkage specified at
4708 // the prior declaration. If no prior declaration is visible, or
4709 // if the prior declaration specifies no linkage, then the
4710 // identifier has external linkage.
4711 if (New->hasExternalStorage() && Old->hasLinkage())
4712 /* Okay */;
4713 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4714 !New->isStaticDataMember() &&
4715 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4716 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4717 Diag(OldLocation, PrevDiag);
4718 return New->setInvalidDecl();
4721 // Check if extern is followed by non-extern and vice-versa.
4722 if (New->hasExternalStorage() &&
4723 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4724 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4725 Diag(OldLocation, PrevDiag);
4726 return New->setInvalidDecl();
4728 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4729 !New->hasExternalStorage()) {
4730 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4731 Diag(OldLocation, PrevDiag);
4732 return New->setInvalidDecl();
4735 if (CheckRedeclarationInModule(New, Old))
4736 return;
4738 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4740 // FIXME: The test for external storage here seems wrong? We still
4741 // need to check for mismatches.
4742 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4743 // Don't complain about out-of-line definitions of static members.
4744 !(Old->getLexicalDeclContext()->isRecord() &&
4745 !New->getLexicalDeclContext()->isRecord())) {
4746 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4747 Diag(OldLocation, PrevDiag);
4748 return New->setInvalidDecl();
4751 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4752 if (VarDecl *Def = Old->getDefinition()) {
4753 // C++1z [dcl.fcn.spec]p4:
4754 // If the definition of a variable appears in a translation unit before
4755 // its first declaration as inline, the program is ill-formed.
4756 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4757 Diag(Def->getLocation(), diag::note_previous_definition);
4761 // If this redeclaration makes the variable inline, we may need to add it to
4762 // UndefinedButUsed.
4763 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4764 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4765 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4766 SourceLocation()));
4768 if (New->getTLSKind() != Old->getTLSKind()) {
4769 if (!Old->getTLSKind()) {
4770 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4771 Diag(OldLocation, PrevDiag);
4772 } else if (!New->getTLSKind()) {
4773 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4774 Diag(OldLocation, PrevDiag);
4775 } else {
4776 // Do not allow redeclaration to change the variable between requiring
4777 // static and dynamic initialization.
4778 // FIXME: GCC allows this, but uses the TLS keyword on the first
4779 // declaration to determine the kind. Do we need to be compatible here?
4780 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4781 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4782 Diag(OldLocation, PrevDiag);
4786 // C++ doesn't have tentative definitions, so go right ahead and check here.
4787 if (getLangOpts().CPlusPlus) {
4788 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4789 Old->getCanonicalDecl()->isConstexpr()) {
4790 // This definition won't be a definition any more once it's been merged.
4791 Diag(New->getLocation(),
4792 diag::warn_deprecated_redundant_constexpr_static_def);
4793 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4794 VarDecl *Def = Old->getDefinition();
4795 if (Def && checkVarDeclRedefinition(Def, New))
4796 return;
4800 if (haveIncompatibleLanguageLinkages(Old, New)) {
4801 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4802 Diag(OldLocation, PrevDiag);
4803 New->setInvalidDecl();
4804 return;
4807 // Merge "used" flag.
4808 if (Old->getMostRecentDecl()->isUsed(false))
4809 New->setIsUsed();
4811 // Keep a chain of previous declarations.
4812 New->setPreviousDecl(Old);
4813 if (NewTemplate)
4814 NewTemplate->setPreviousDecl(OldTemplate);
4816 // Inherit access appropriately.
4817 New->setAccess(Old->getAccess());
4818 if (NewTemplate)
4819 NewTemplate->setAccess(New->getAccess());
4821 if (Old->isInline())
4822 New->setImplicitlyInline();
4825 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4826 SourceManager &SrcMgr = getSourceManager();
4827 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4828 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4829 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4830 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4831 auto &HSI = PP.getHeaderSearchInfo();
4832 StringRef HdrFilename =
4833 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4835 auto noteFromModuleOrInclude = [&](Module *Mod,
4836 SourceLocation IncLoc) -> bool {
4837 // Redefinition errors with modules are common with non modular mapped
4838 // headers, example: a non-modular header H in module A that also gets
4839 // included directly in a TU. Pointing twice to the same header/definition
4840 // is confusing, try to get better diagnostics when modules is on.
4841 if (IncLoc.isValid()) {
4842 if (Mod) {
4843 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4844 << HdrFilename.str() << Mod->getFullModuleName();
4845 if (!Mod->DefinitionLoc.isInvalid())
4846 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4847 << Mod->getFullModuleName();
4848 } else {
4849 Diag(IncLoc, diag::note_redefinition_include_same_file)
4850 << HdrFilename.str();
4852 return true;
4855 return false;
4858 // Is it the same file and same offset? Provide more information on why
4859 // this leads to a redefinition error.
4860 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4861 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4862 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4863 bool EmittedDiag =
4864 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4865 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4867 // If the header has no guards, emit a note suggesting one.
4868 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4869 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4871 if (EmittedDiag)
4872 return;
4875 // Redefinition coming from different files or couldn't do better above.
4876 if (Old->getLocation().isValid())
4877 Diag(Old->getLocation(), diag::note_previous_definition);
4880 /// We've just determined that \p Old and \p New both appear to be definitions
4881 /// of the same variable. Either diagnose or fix the problem.
4882 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4883 if (!hasVisibleDefinition(Old) &&
4884 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4885 isa<VarTemplateSpecializationDecl>(New) ||
4886 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4887 New->getDeclContext()->isDependentContext())) {
4888 // The previous definition is hidden, and multiple definitions are
4889 // permitted (in separate TUs). Demote this to a declaration.
4890 New->demoteThisDefinitionToDeclaration();
4892 // Make the canonical definition visible.
4893 if (auto *OldTD = Old->getDescribedVarTemplate())
4894 makeMergedDefinitionVisible(OldTD);
4895 makeMergedDefinitionVisible(Old);
4896 return false;
4897 } else {
4898 Diag(New->getLocation(), diag::err_redefinition) << New;
4899 notePreviousDefinition(Old, New->getLocation());
4900 New->setInvalidDecl();
4901 return true;
4905 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4906 /// no declarator (e.g. "struct foo;") is parsed.
4907 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
4908 DeclSpec &DS,
4909 const ParsedAttributesView &DeclAttrs,
4910 RecordDecl *&AnonRecord) {
4911 return ParsedFreeStandingDeclSpec(
4912 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4915 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4916 // disambiguate entities defined in different scopes.
4917 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4918 // compatibility.
4919 // We will pick our mangling number depending on which version of MSVC is being
4920 // targeted.
4921 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4922 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4923 ? S->getMSCurManglingNumber()
4924 : S->getMSLastManglingNumber();
4927 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4928 if (!Context.getLangOpts().CPlusPlus)
4929 return;
4931 if (isa<CXXRecordDecl>(Tag->getParent())) {
4932 // If this tag is the direct child of a class, number it if
4933 // it is anonymous.
4934 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4935 return;
4936 MangleNumberingContext &MCtx =
4937 Context.getManglingNumberContext(Tag->getParent());
4938 Context.setManglingNumber(
4939 Tag, MCtx.getManglingNumber(
4940 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4941 return;
4944 // If this tag isn't a direct child of a class, number it if it is local.
4945 MangleNumberingContext *MCtx;
4946 Decl *ManglingContextDecl;
4947 std::tie(MCtx, ManglingContextDecl) =
4948 getCurrentMangleNumberContext(Tag->getDeclContext());
4949 if (MCtx) {
4950 Context.setManglingNumber(
4951 Tag, MCtx->getManglingNumber(
4952 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4956 namespace {
4957 struct NonCLikeKind {
4958 enum {
4959 None,
4960 BaseClass,
4961 DefaultMemberInit,
4962 Lambda,
4963 Friend,
4964 OtherMember,
4965 Invalid,
4966 } Kind = None;
4967 SourceRange Range;
4969 explicit operator bool() { return Kind != None; }
4973 /// Determine whether a class is C-like, according to the rules of C++
4974 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4975 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4976 if (RD->isInvalidDecl())
4977 return {NonCLikeKind::Invalid, {}};
4979 // C++ [dcl.typedef]p9: [P1766R1]
4980 // An unnamed class with a typedef name for linkage purposes shall not
4982 // -- have any base classes
4983 if (RD->getNumBases())
4984 return {NonCLikeKind::BaseClass,
4985 SourceRange(RD->bases_begin()->getBeginLoc(),
4986 RD->bases_end()[-1].getEndLoc())};
4987 bool Invalid = false;
4988 for (Decl *D : RD->decls()) {
4989 // Don't complain about things we already diagnosed.
4990 if (D->isInvalidDecl()) {
4991 Invalid = true;
4992 continue;
4995 // -- have any [...] default member initializers
4996 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4997 if (FD->hasInClassInitializer()) {
4998 auto *Init = FD->getInClassInitializer();
4999 return {NonCLikeKind::DefaultMemberInit,
5000 Init ? Init->getSourceRange() : D->getSourceRange()};
5002 continue;
5005 // FIXME: We don't allow friend declarations. This violates the wording of
5006 // P1766, but not the intent.
5007 if (isa<FriendDecl>(D))
5008 return {NonCLikeKind::Friend, D->getSourceRange()};
5010 // -- declare any members other than non-static data members, member
5011 // enumerations, or member classes,
5012 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
5013 isa<EnumDecl>(D))
5014 continue;
5015 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5016 if (!MemberRD) {
5017 if (D->isImplicit())
5018 continue;
5019 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5022 // -- contain a lambda-expression,
5023 if (MemberRD->isLambda())
5024 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5026 // and all member classes shall also satisfy these requirements
5027 // (recursively).
5028 if (MemberRD->isThisDeclarationADefinition()) {
5029 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5030 return Kind;
5034 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5037 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
5038 TypedefNameDecl *NewTD) {
5039 if (TagFromDeclSpec->isInvalidDecl())
5040 return;
5042 // Do nothing if the tag already has a name for linkage purposes.
5043 if (TagFromDeclSpec->hasNameForLinkage())
5044 return;
5046 // A well-formed anonymous tag must always be a TUK_Definition.
5047 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5049 // The type must match the tag exactly; no qualifiers allowed.
5050 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5051 Context.getTagDeclType(TagFromDeclSpec))) {
5052 if (getLangOpts().CPlusPlus)
5053 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5054 return;
5057 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5058 // An unnamed class with a typedef name for linkage purposes shall [be
5059 // C-like].
5061 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5062 // shouldn't happen, but there are constructs that the language rule doesn't
5063 // disallow for which we can't reasonably avoid computing linkage early.
5064 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5065 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5066 : NonCLikeKind();
5067 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5068 if (NonCLike || ChangesLinkage) {
5069 if (NonCLike.Kind == NonCLikeKind::Invalid)
5070 return;
5072 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5073 if (ChangesLinkage) {
5074 // If the linkage changes, we can't accept this as an extension.
5075 if (NonCLike.Kind == NonCLikeKind::None)
5076 DiagID = diag::err_typedef_changes_linkage;
5077 else
5078 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5081 SourceLocation FixitLoc =
5082 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5083 llvm::SmallString<40> TextToInsert;
5084 TextToInsert += ' ';
5085 TextToInsert += NewTD->getIdentifier()->getName();
5087 Diag(FixitLoc, DiagID)
5088 << isa<TypeAliasDecl>(NewTD)
5089 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5090 if (NonCLike.Kind != NonCLikeKind::None) {
5091 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5092 << NonCLike.Kind - 1 << NonCLike.Range;
5094 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5095 << NewTD << isa<TypeAliasDecl>(NewTD);
5097 if (ChangesLinkage)
5098 return;
5101 // Otherwise, set this as the anon-decl typedef for the tag.
5102 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5105 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5106 DeclSpec::TST T = DS.getTypeSpecType();
5107 switch (T) {
5108 case DeclSpec::TST_class:
5109 return 0;
5110 case DeclSpec::TST_struct:
5111 return 1;
5112 case DeclSpec::TST_interface:
5113 return 2;
5114 case DeclSpec::TST_union:
5115 return 3;
5116 case DeclSpec::TST_enum:
5117 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5118 if (ED->isScopedUsingClassTag())
5119 return 5;
5120 if (ED->isScoped())
5121 return 6;
5123 return 4;
5124 default:
5125 llvm_unreachable("unexpected type specifier");
5128 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
5129 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
5130 /// parameters to cope with template friend declarations.
5131 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
5132 DeclSpec &DS,
5133 const ParsedAttributesView &DeclAttrs,
5134 MultiTemplateParamsArg TemplateParams,
5135 bool IsExplicitInstantiation,
5136 RecordDecl *&AnonRecord) {
5137 Decl *TagD = nullptr;
5138 TagDecl *Tag = nullptr;
5139 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
5140 DS.getTypeSpecType() == DeclSpec::TST_struct ||
5141 DS.getTypeSpecType() == DeclSpec::TST_interface ||
5142 DS.getTypeSpecType() == DeclSpec::TST_union ||
5143 DS.getTypeSpecType() == DeclSpec::TST_enum) {
5144 TagD = DS.getRepAsDecl();
5146 if (!TagD) // We probably had an error
5147 return nullptr;
5149 // Note that the above type specs guarantee that the
5150 // type rep is a Decl, whereas in many of the others
5151 // it's a Type.
5152 if (isa<TagDecl>(TagD))
5153 Tag = cast<TagDecl>(TagD);
5154 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5155 Tag = CTD->getTemplatedDecl();
5158 if (Tag) {
5159 handleTagNumbering(Tag, S);
5160 Tag->setFreeStanding();
5161 if (Tag->isInvalidDecl())
5162 return Tag;
5165 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5166 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5167 // or incomplete types shall not be restrict-qualified."
5168 if (TypeQuals & DeclSpec::TQ_restrict)
5169 Diag(DS.getRestrictSpecLoc(),
5170 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5171 << DS.getSourceRange();
5174 if (DS.isInlineSpecified())
5175 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5176 << getLangOpts().CPlusPlus17;
5178 if (DS.hasConstexprSpecifier()) {
5179 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5180 // and definitions of functions and variables.
5181 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5182 // the declaration of a function or function template
5183 if (Tag)
5184 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5185 << GetDiagnosticTypeSpecifierID(DS)
5186 << static_cast<int>(DS.getConstexprSpecifier());
5187 else
5188 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5189 << static_cast<int>(DS.getConstexprSpecifier());
5190 // Don't emit warnings after this error.
5191 return TagD;
5194 DiagnoseFunctionSpecifiers(DS);
5196 if (DS.isFriendSpecified()) {
5197 // If we're dealing with a decl but not a TagDecl, assume that
5198 // whatever routines created it handled the friendship aspect.
5199 if (TagD && !Tag)
5200 return nullptr;
5201 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5204 const CXXScopeSpec &SS = DS.getTypeSpecScope();
5205 bool IsExplicitSpecialization =
5206 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
5207 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
5208 !IsExplicitInstantiation && !IsExplicitSpecialization &&
5209 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
5210 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
5211 // nested-name-specifier unless it is an explicit instantiation
5212 // or an explicit specialization.
5214 // FIXME: We allow class template partial specializations here too, per the
5215 // obvious intent of DR1819.
5217 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
5218 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
5219 << GetDiagnosticTypeSpecifierID(DS) << SS.getRange();
5220 return nullptr;
5223 // Track whether this decl-specifier declares anything.
5224 bool DeclaresAnything = true;
5226 // Handle anonymous struct definitions.
5227 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5228 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5229 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
5230 if (getLangOpts().CPlusPlus ||
5231 Record->getDeclContext()->isRecord()) {
5232 // If CurContext is a DeclContext that can contain statements,
5233 // RecursiveASTVisitor won't visit the decls that
5234 // BuildAnonymousStructOrUnion() will put into CurContext.
5235 // Also store them here so that they can be part of the
5236 // DeclStmt that gets created in this case.
5237 // FIXME: Also return the IndirectFieldDecls created by
5238 // BuildAnonymousStructOr union, for the same reason?
5239 if (CurContext->isFunctionOrMethod())
5240 AnonRecord = Record;
5241 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5242 Context.getPrintingPolicy());
5245 DeclaresAnything = false;
5249 // C11 6.7.2.1p2:
5250 // A struct-declaration that does not declare an anonymous structure or
5251 // anonymous union shall contain a struct-declarator-list.
5253 // This rule also existed in C89 and C99; the grammar for struct-declaration
5254 // did not permit a struct-declaration without a struct-declarator-list.
5255 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5256 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
5257 // Check for Microsoft C extension: anonymous struct/union member.
5258 // Handle 2 kinds of anonymous struct/union:
5259 // struct STRUCT;
5260 // union UNION;
5261 // and
5262 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5263 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5264 if ((Tag && Tag->getDeclName()) ||
5265 DS.getTypeSpecType() == DeclSpec::TST_typename) {
5266 RecordDecl *Record = nullptr;
5267 if (Tag)
5268 Record = dyn_cast<RecordDecl>(Tag);
5269 else if (const RecordType *RT =
5270 DS.getRepAsType().get()->getAsStructureType())
5271 Record = RT->getDecl();
5272 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5273 Record = UT->getDecl();
5275 if (Record && getLangOpts().MicrosoftExt) {
5276 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5277 << Record->isUnion() << DS.getSourceRange();
5278 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
5281 DeclaresAnything = false;
5285 // Skip all the checks below if we have a type error.
5286 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
5287 (TagD && TagD->isInvalidDecl()))
5288 return TagD;
5290 if (getLangOpts().CPlusPlus &&
5291 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
5292 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5293 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5294 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5295 DeclaresAnything = false;
5297 if (!DS.isMissingDeclaratorOk()) {
5298 // Customize diagnostic for a typedef missing a name.
5299 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
5300 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5301 << DS.getSourceRange();
5302 else
5303 DeclaresAnything = false;
5306 if (DS.isModulePrivateSpecified() &&
5307 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5308 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5309 << llvm::to_underlying(Tag->getTagKind())
5310 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
5312 ActOnDocumentableDecl(TagD);
5314 // C 6.7/2:
5315 // A declaration [...] shall declare at least a declarator [...], a tag,
5316 // or the members of an enumeration.
5317 // C++ [dcl.dcl]p3:
5318 // [If there are no declarators], and except for the declaration of an
5319 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5320 // names into the program, or shall redeclare a name introduced by a
5321 // previous declaration.
5322 if (!DeclaresAnything) {
5323 // In C, we allow this as a (popular) extension / bug. Don't bother
5324 // producing further diagnostics for redundant qualifiers after this.
5325 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5326 ? diag::err_no_declarators
5327 : diag::ext_no_declarators)
5328 << DS.getSourceRange();
5329 return TagD;
5332 // C++ [dcl.stc]p1:
5333 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5334 // init-declarator-list of the declaration shall not be empty.
5335 // C++ [dcl.fct.spec]p1:
5336 // If a cv-qualifier appears in a decl-specifier-seq, the
5337 // init-declarator-list of the declaration shall not be empty.
5339 // Spurious qualifiers here appear to be valid in C.
5340 unsigned DiagID = diag::warn_standalone_specifier;
5341 if (getLangOpts().CPlusPlus)
5342 DiagID = diag::ext_standalone_specifier;
5344 // Note that a linkage-specification sets a storage class, but
5345 // 'extern "C" struct foo;' is actually valid and not theoretically
5346 // useless.
5347 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5348 if (SCS == DeclSpec::SCS_mutable)
5349 // Since mutable is not a viable storage class specifier in C, there is
5350 // no reason to treat it as an extension. Instead, diagnose as an error.
5351 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5352 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5353 Diag(DS.getStorageClassSpecLoc(), DiagID)
5354 << DeclSpec::getSpecifierName(SCS);
5357 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5358 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5359 << DeclSpec::getSpecifierName(TSCS);
5360 if (DS.getTypeQualifiers()) {
5361 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5362 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5363 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5364 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5365 // Restrict is covered above.
5366 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5367 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5368 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5369 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5372 // Warn about ignored type attributes, for example:
5373 // __attribute__((aligned)) struct A;
5374 // Attributes should be placed after tag to apply to type declaration.
5375 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5376 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5377 if (TypeSpecType == DeclSpec::TST_class ||
5378 TypeSpecType == DeclSpec::TST_struct ||
5379 TypeSpecType == DeclSpec::TST_interface ||
5380 TypeSpecType == DeclSpec::TST_union ||
5381 TypeSpecType == DeclSpec::TST_enum) {
5383 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5384 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5385 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5386 DiagnosticId = diag::warn_attribute_ignored;
5387 else if (AL.isRegularKeywordAttribute())
5388 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5389 else
5390 DiagnosticId = diag::warn_declspec_attribute_ignored;
5391 Diag(AL.getLoc(), DiagnosticId)
5392 << AL << GetDiagnosticTypeSpecifierID(DS);
5395 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5396 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5400 return TagD;
5403 /// We are trying to inject an anonymous member into the given scope;
5404 /// check if there's an existing declaration that can't be overloaded.
5406 /// \return true if this is a forbidden redeclaration
5407 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5408 DeclContext *Owner,
5409 DeclarationName Name,
5410 SourceLocation NameLoc, bool IsUnion,
5411 StorageClass SC) {
5412 LookupResult R(SemaRef, Name, NameLoc,
5413 Owner->isRecord() ? Sema::LookupMemberName
5414 : Sema::LookupOrdinaryName,
5415 Sema::ForVisibleRedeclaration);
5416 if (!SemaRef.LookupName(R, S)) return false;
5418 // Pick a representative declaration.
5419 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5420 assert(PrevDecl && "Expected a non-null Decl");
5422 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5423 return false;
5425 if (SC == StorageClass::SC_None &&
5426 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5427 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5428 if (!Owner->isRecord())
5429 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5430 return false;
5433 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5434 << IsUnion << Name;
5435 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5437 return true;
5440 void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) {
5441 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5442 DiagPlaceholderFieldDeclDefinitions(RD);
5445 /// Emit diagnostic warnings for placeholder members.
5446 /// We can only do that after the class is fully constructed,
5447 /// as anonymous union/structs can insert placeholders
5448 /// in their parent scope (which might be a Record).
5449 void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) {
5450 if (!getLangOpts().CPlusPlus)
5451 return;
5453 // This function can be parsed before we have validated the
5454 // structure as an anonymous struct
5455 if (Record->isAnonymousStructOrUnion())
5456 return;
5458 const NamedDecl *First = 0;
5459 for (const Decl *D : Record->decls()) {
5460 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5461 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5462 continue;
5463 if (!First)
5464 First = ND;
5465 else
5466 DiagPlaceholderVariableDefinition(ND->getLocation());
5470 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5471 /// anonymous struct or union AnonRecord into the owning context Owner
5472 /// and scope S. This routine will be invoked just after we realize
5473 /// that an unnamed union or struct is actually an anonymous union or
5474 /// struct, e.g.,
5476 /// @code
5477 /// union {
5478 /// int i;
5479 /// float f;
5480 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5481 /// // f into the surrounding scope.x
5482 /// @endcode
5484 /// This routine is recursive, injecting the names of nested anonymous
5485 /// structs/unions into the owning context and scope as well.
5486 static bool
5487 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
5488 RecordDecl *AnonRecord, AccessSpecifier AS,
5489 StorageClass SC,
5490 SmallVectorImpl<NamedDecl *> &Chaining) {
5491 bool Invalid = false;
5493 // Look every FieldDecl and IndirectFieldDecl with a name.
5494 for (auto *D : AnonRecord->decls()) {
5495 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5496 cast<NamedDecl>(D)->getDeclName()) {
5497 ValueDecl *VD = cast<ValueDecl>(D);
5498 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5499 VD->getLocation(), AnonRecord->isUnion(),
5500 SC)) {
5501 // C++ [class.union]p2:
5502 // The names of the members of an anonymous union shall be
5503 // distinct from the names of any other entity in the
5504 // scope in which the anonymous union is declared.
5505 Invalid = true;
5506 } else {
5507 // C++ [class.union]p2:
5508 // For the purpose of name lookup, after the anonymous union
5509 // definition, the members of the anonymous union are
5510 // considered to have been defined in the scope in which the
5511 // anonymous union is declared.
5512 unsigned OldChainingSize = Chaining.size();
5513 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5514 Chaining.append(IF->chain_begin(), IF->chain_end());
5515 else
5516 Chaining.push_back(VD);
5518 assert(Chaining.size() >= 2);
5519 NamedDecl **NamedChain =
5520 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5521 for (unsigned i = 0; i < Chaining.size(); i++)
5522 NamedChain[i] = Chaining[i];
5524 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
5525 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5526 VD->getType(), {NamedChain, Chaining.size()});
5528 for (const auto *Attr : VD->attrs())
5529 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5531 IndirectField->setAccess(AS);
5532 IndirectField->setImplicit();
5533 SemaRef.PushOnScopeChains(IndirectField, S);
5535 // That includes picking up the appropriate access specifier.
5536 if (AS != AS_none) IndirectField->setAccess(AS);
5538 Chaining.resize(OldChainingSize);
5543 return Invalid;
5546 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5547 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5548 /// illegal input values are mapped to SC_None.
5549 static StorageClass
5550 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5551 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5552 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5553 "Parser allowed 'typedef' as storage class VarDecl.");
5554 switch (StorageClassSpec) {
5555 case DeclSpec::SCS_unspecified: return SC_None;
5556 case DeclSpec::SCS_extern:
5557 if (DS.isExternInLinkageSpec())
5558 return SC_None;
5559 return SC_Extern;
5560 case DeclSpec::SCS_static: return SC_Static;
5561 case DeclSpec::SCS_auto: return SC_Auto;
5562 case DeclSpec::SCS_register: return SC_Register;
5563 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5564 // Illegal SCSs map to None: error reporting is up to the caller.
5565 case DeclSpec::SCS_mutable: // Fall through.
5566 case DeclSpec::SCS_typedef: return SC_None;
5568 llvm_unreachable("unknown storage class specifier");
5571 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5572 assert(Record->hasInClassInitializer());
5574 for (const auto *I : Record->decls()) {
5575 const auto *FD = dyn_cast<FieldDecl>(I);
5576 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5577 FD = IFD->getAnonField();
5578 if (FD && FD->hasInClassInitializer())
5579 return FD->getLocation();
5582 llvm_unreachable("couldn't find in-class initializer");
5585 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5586 SourceLocation DefaultInitLoc) {
5587 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5588 return;
5590 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5591 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5594 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5595 CXXRecordDecl *AnonUnion) {
5596 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5597 return;
5599 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5602 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5603 /// anonymous structure or union. Anonymous unions are a C++ feature
5604 /// (C++ [class.union]) and a C11 feature; anonymous structures
5605 /// are a C11 feature and GNU C++ extension.
5606 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5607 AccessSpecifier AS,
5608 RecordDecl *Record,
5609 const PrintingPolicy &Policy) {
5610 DeclContext *Owner = Record->getDeclContext();
5612 // Diagnose whether this anonymous struct/union is an extension.
5613 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5614 Diag(Record->getLocation(), diag::ext_anonymous_union);
5615 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5616 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5617 else if (!Record->isUnion() && !getLangOpts().C11)
5618 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5620 // C and C++ require different kinds of checks for anonymous
5621 // structs/unions.
5622 bool Invalid = false;
5623 if (getLangOpts().CPlusPlus) {
5624 const char *PrevSpec = nullptr;
5625 if (Record->isUnion()) {
5626 // C++ [class.union]p6:
5627 // C++17 [class.union.anon]p2:
5628 // Anonymous unions declared in a named namespace or in the
5629 // global namespace shall be declared static.
5630 unsigned DiagID;
5631 DeclContext *OwnerScope = Owner->getRedeclContext();
5632 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5633 (OwnerScope->isTranslationUnit() ||
5634 (OwnerScope->isNamespace() &&
5635 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5636 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5637 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5639 // Recover by adding 'static'.
5640 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5641 PrevSpec, DiagID, Policy);
5643 // C++ [class.union]p6:
5644 // A storage class is not allowed in a declaration of an
5645 // anonymous union in a class scope.
5646 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5647 isa<RecordDecl>(Owner)) {
5648 Diag(DS.getStorageClassSpecLoc(),
5649 diag::err_anonymous_union_with_storage_spec)
5650 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5652 // Recover by removing the storage specifier.
5653 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5654 SourceLocation(),
5655 PrevSpec, DiagID, Context.getPrintingPolicy());
5659 // Ignore const/volatile/restrict qualifiers.
5660 if (DS.getTypeQualifiers()) {
5661 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5662 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5663 << Record->isUnion() << "const"
5664 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5665 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5666 Diag(DS.getVolatileSpecLoc(),
5667 diag::ext_anonymous_struct_union_qualified)
5668 << Record->isUnion() << "volatile"
5669 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5670 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5671 Diag(DS.getRestrictSpecLoc(),
5672 diag::ext_anonymous_struct_union_qualified)
5673 << Record->isUnion() << "restrict"
5674 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5675 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5676 Diag(DS.getAtomicSpecLoc(),
5677 diag::ext_anonymous_struct_union_qualified)
5678 << Record->isUnion() << "_Atomic"
5679 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5680 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5681 Diag(DS.getUnalignedSpecLoc(),
5682 diag::ext_anonymous_struct_union_qualified)
5683 << Record->isUnion() << "__unaligned"
5684 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5686 DS.ClearTypeQualifiers();
5689 // C++ [class.union]p2:
5690 // The member-specification of an anonymous union shall only
5691 // define non-static data members. [Note: nested types and
5692 // functions cannot be declared within an anonymous union. ]
5693 for (auto *Mem : Record->decls()) {
5694 // Ignore invalid declarations; we already diagnosed them.
5695 if (Mem->isInvalidDecl())
5696 continue;
5698 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5699 // C++ [class.union]p3:
5700 // An anonymous union shall not have private or protected
5701 // members (clause 11).
5702 assert(FD->getAccess() != AS_none);
5703 if (FD->getAccess() != AS_public) {
5704 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5705 << Record->isUnion() << (FD->getAccess() == AS_protected);
5706 Invalid = true;
5709 // C++ [class.union]p1
5710 // An object of a class with a non-trivial constructor, a non-trivial
5711 // copy constructor, a non-trivial destructor, or a non-trivial copy
5712 // assignment operator cannot be a member of a union, nor can an
5713 // array of such objects.
5714 if (CheckNontrivialField(FD))
5715 Invalid = true;
5716 } else if (Mem->isImplicit()) {
5717 // Any implicit members are fine.
5718 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5719 // This is a type that showed up in an
5720 // elaborated-type-specifier inside the anonymous struct or
5721 // union, but which actually declares a type outside of the
5722 // anonymous struct or union. It's okay.
5723 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5724 if (!MemRecord->isAnonymousStructOrUnion() &&
5725 MemRecord->getDeclName()) {
5726 // Visual C++ allows type definition in anonymous struct or union.
5727 if (getLangOpts().MicrosoftExt)
5728 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5729 << Record->isUnion();
5730 else {
5731 // This is a nested type declaration.
5732 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5733 << Record->isUnion();
5734 Invalid = true;
5736 } else {
5737 // This is an anonymous type definition within another anonymous type.
5738 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5739 // not part of standard C++.
5740 Diag(MemRecord->getLocation(),
5741 diag::ext_anonymous_record_with_anonymous_type)
5742 << Record->isUnion();
5744 } else if (isa<AccessSpecDecl>(Mem)) {
5745 // Any access specifier is fine.
5746 } else if (isa<StaticAssertDecl>(Mem)) {
5747 // In C++1z, static_assert declarations are also fine.
5748 } else {
5749 // We have something that isn't a non-static data
5750 // member. Complain about it.
5751 unsigned DK = diag::err_anonymous_record_bad_member;
5752 if (isa<TypeDecl>(Mem))
5753 DK = diag::err_anonymous_record_with_type;
5754 else if (isa<FunctionDecl>(Mem))
5755 DK = diag::err_anonymous_record_with_function;
5756 else if (isa<VarDecl>(Mem))
5757 DK = diag::err_anonymous_record_with_static;
5759 // Visual C++ allows type definition in anonymous struct or union.
5760 if (getLangOpts().MicrosoftExt &&
5761 DK == diag::err_anonymous_record_with_type)
5762 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5763 << Record->isUnion();
5764 else {
5765 Diag(Mem->getLocation(), DK) << Record->isUnion();
5766 Invalid = true;
5771 // C++11 [class.union]p8 (DR1460):
5772 // At most one variant member of a union may have a
5773 // brace-or-equal-initializer.
5774 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5775 Owner->isRecord())
5776 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5777 cast<CXXRecordDecl>(Record));
5780 if (!Record->isUnion() && !Owner->isRecord()) {
5781 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5782 << getLangOpts().CPlusPlus;
5783 Invalid = true;
5786 // C++ [dcl.dcl]p3:
5787 // [If there are no declarators], and except for the declaration of an
5788 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5789 // names into the program
5790 // C++ [class.mem]p2:
5791 // each such member-declaration shall either declare at least one member
5792 // name of the class or declare at least one unnamed bit-field
5794 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5795 if (getLangOpts().CPlusPlus && Record->field_empty())
5796 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5798 // Mock up a declarator.
5799 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
5800 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5801 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5802 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5804 // Create a declaration for this anonymous struct/union.
5805 NamedDecl *Anon = nullptr;
5806 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5807 Anon = FieldDecl::Create(
5808 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5809 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5810 /*BitWidth=*/nullptr, /*Mutable=*/false,
5811 /*InitStyle=*/ICIS_NoInit);
5812 Anon->setAccess(AS);
5813 ProcessDeclAttributes(S, Anon, Dc);
5815 if (getLangOpts().CPlusPlus)
5816 FieldCollector->Add(cast<FieldDecl>(Anon));
5817 } else {
5818 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5819 if (SCSpec == DeclSpec::SCS_mutable) {
5820 // mutable can only appear on non-static class members, so it's always
5821 // an error here
5822 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5823 Invalid = true;
5824 SC = SC_None;
5827 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5828 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5829 Context.getTypeDeclType(Record), TInfo, SC);
5830 ProcessDeclAttributes(S, Anon, Dc);
5832 // Default-initialize the implicit variable. This initialization will be
5833 // trivial in almost all cases, except if a union member has an in-class
5834 // initializer:
5835 // union { int n = 0; };
5836 ActOnUninitializedDecl(Anon);
5838 Anon->setImplicit();
5840 // Mark this as an anonymous struct/union type.
5841 Record->setAnonymousStructOrUnion(true);
5843 // Add the anonymous struct/union object to the current
5844 // context. We'll be referencing this object when we refer to one of
5845 // its members.
5846 Owner->addDecl(Anon);
5848 // Inject the members of the anonymous struct/union into the owning
5849 // context and into the identifier resolver chain for name lookup
5850 // purposes.
5851 SmallVector<NamedDecl*, 2> Chain;
5852 Chain.push_back(Anon);
5854 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5855 Chain))
5856 Invalid = true;
5858 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5859 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5860 MangleNumberingContext *MCtx;
5861 Decl *ManglingContextDecl;
5862 std::tie(MCtx, ManglingContextDecl) =
5863 getCurrentMangleNumberContext(NewVD->getDeclContext());
5864 if (MCtx) {
5865 Context.setManglingNumber(
5866 NewVD, MCtx->getManglingNumber(
5867 NewVD, getMSManglingNumber(getLangOpts(), S)));
5868 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5873 if (Invalid)
5874 Anon->setInvalidDecl();
5876 return Anon;
5879 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5880 /// Microsoft C anonymous structure.
5881 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5882 /// Example:
5884 /// struct A { int a; };
5885 /// struct B { struct A; int b; };
5887 /// void foo() {
5888 /// B var;
5889 /// var.a = 3;
5890 /// }
5892 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5893 RecordDecl *Record) {
5894 assert(Record && "expected a record!");
5896 // Mock up a declarator.
5897 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
5898 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5899 assert(TInfo && "couldn't build declarator info for anonymous struct");
5901 auto *ParentDecl = cast<RecordDecl>(CurContext);
5902 QualType RecTy = Context.getTypeDeclType(Record);
5904 // Create a declaration for this anonymous struct.
5905 NamedDecl *Anon =
5906 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5907 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5908 /*BitWidth=*/nullptr, /*Mutable=*/false,
5909 /*InitStyle=*/ICIS_NoInit);
5910 Anon->setImplicit();
5912 // Add the anonymous struct object to the current context.
5913 CurContext->addDecl(Anon);
5915 // Inject the members of the anonymous struct into the current
5916 // context and into the identifier resolver chain for name lookup
5917 // purposes.
5918 SmallVector<NamedDecl*, 2> Chain;
5919 Chain.push_back(Anon);
5921 RecordDecl *RecordDef = Record->getDefinition();
5922 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5923 diag::err_field_incomplete_or_sizeless) ||
5924 InjectAnonymousStructOrUnionMembers(
5925 *this, S, CurContext, RecordDef, AS_none,
5926 StorageClassSpecToVarDeclStorageClass(DS), Chain)) {
5927 Anon->setInvalidDecl();
5928 ParentDecl->setInvalidDecl();
5931 return Anon;
5934 /// GetNameForDeclarator - Determine the full declaration name for the
5935 /// given Declarator.
5936 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5937 return GetNameFromUnqualifiedId(D.getName());
5940 /// Retrieves the declaration name from a parsed unqualified-id.
5941 DeclarationNameInfo
5942 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5943 DeclarationNameInfo NameInfo;
5944 NameInfo.setLoc(Name.StartLocation);
5946 switch (Name.getKind()) {
5948 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5949 case UnqualifiedIdKind::IK_Identifier:
5950 NameInfo.setName(Name.Identifier);
5951 return NameInfo;
5953 case UnqualifiedIdKind::IK_DeductionGuideName: {
5954 // C++ [temp.deduct.guide]p3:
5955 // The simple-template-id shall name a class template specialization.
5956 // The template-name shall be the same identifier as the template-name
5957 // of the simple-template-id.
5958 // These together intend to imply that the template-name shall name a
5959 // class template.
5960 // FIXME: template<typename T> struct X {};
5961 // template<typename T> using Y = X<T>;
5962 // Y(int) -> Y<int>;
5963 // satisfies these rules but does not name a class template.
5964 TemplateName TN = Name.TemplateName.get().get();
5965 auto *Template = TN.getAsTemplateDecl();
5966 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5967 Diag(Name.StartLocation,
5968 diag::err_deduction_guide_name_not_class_template)
5969 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5970 if (Template)
5971 NoteTemplateLocation(*Template);
5972 return DeclarationNameInfo();
5975 NameInfo.setName(
5976 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5977 return NameInfo;
5980 case UnqualifiedIdKind::IK_OperatorFunctionId:
5981 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5982 Name.OperatorFunctionId.Operator));
5983 NameInfo.setCXXOperatorNameRange(SourceRange(
5984 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5985 return NameInfo;
5987 case UnqualifiedIdKind::IK_LiteralOperatorId:
5988 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5989 Name.Identifier));
5990 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5991 return NameInfo;
5993 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5994 TypeSourceInfo *TInfo;
5995 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5996 if (Ty.isNull())
5997 return DeclarationNameInfo();
5998 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5999 Context.getCanonicalType(Ty)));
6000 NameInfo.setNamedTypeInfo(TInfo);
6001 return NameInfo;
6004 case UnqualifiedIdKind::IK_ConstructorName: {
6005 TypeSourceInfo *TInfo;
6006 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6007 if (Ty.isNull())
6008 return DeclarationNameInfo();
6009 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6010 Context.getCanonicalType(Ty)));
6011 NameInfo.setNamedTypeInfo(TInfo);
6012 return NameInfo;
6015 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
6016 // In well-formed code, we can only have a constructor
6017 // template-id that refers to the current context, so go there
6018 // to find the actual type being constructed.
6019 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6020 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6021 return DeclarationNameInfo();
6023 // Determine the type of the class being constructed.
6024 QualType CurClassType = Context.getTypeDeclType(CurClass);
6026 // FIXME: Check two things: that the template-id names the same type as
6027 // CurClassType, and that the template-id does not occur when the name
6028 // was qualified.
6030 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6031 Context.getCanonicalType(CurClassType)));
6032 // FIXME: should we retrieve TypeSourceInfo?
6033 NameInfo.setNamedTypeInfo(nullptr);
6034 return NameInfo;
6037 case UnqualifiedIdKind::IK_DestructorName: {
6038 TypeSourceInfo *TInfo;
6039 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6040 if (Ty.isNull())
6041 return DeclarationNameInfo();
6042 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6043 Context.getCanonicalType(Ty)));
6044 NameInfo.setNamedTypeInfo(TInfo);
6045 return NameInfo;
6048 case UnqualifiedIdKind::IK_TemplateId: {
6049 TemplateName TName = Name.TemplateId->Template.get();
6050 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6051 return Context.getNameForTemplate(TName, TNameLoc);
6054 } // switch (Name.getKind())
6056 llvm_unreachable("Unknown name kind");
6059 static QualType getCoreType(QualType Ty) {
6060 do {
6061 if (Ty->isPointerType() || Ty->isReferenceType())
6062 Ty = Ty->getPointeeType();
6063 else if (Ty->isArrayType())
6064 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
6065 else
6066 return Ty.withoutLocalFastQualifiers();
6067 } while (true);
6070 /// hasSimilarParameters - Determine whether the C++ functions Declaration
6071 /// and Definition have "nearly" matching parameters. This heuristic is
6072 /// used to improve diagnostics in the case where an out-of-line function
6073 /// definition doesn't match any declaration within the class or namespace.
6074 /// Also sets Params to the list of indices to the parameters that differ
6075 /// between the declaration and the definition. If hasSimilarParameters
6076 /// returns true and Params is empty, then all of the parameters match.
6077 static bool hasSimilarParameters(ASTContext &Context,
6078 FunctionDecl *Declaration,
6079 FunctionDecl *Definition,
6080 SmallVectorImpl<unsigned> &Params) {
6081 Params.clear();
6082 if (Declaration->param_size() != Definition->param_size())
6083 return false;
6084 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6085 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6086 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6088 // The parameter types are identical
6089 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6090 continue;
6092 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6093 QualType DefParamBaseTy = getCoreType(DefParamTy);
6094 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6095 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6097 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6098 (DeclTyName && DeclTyName == DefTyName))
6099 Params.push_back(Idx);
6100 else // The two parameters aren't even close
6101 return false;
6104 return true;
6107 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6108 /// declarator needs to be rebuilt in the current instantiation.
6109 /// Any bits of declarator which appear before the name are valid for
6110 /// consideration here. That's specifically the type in the decl spec
6111 /// and the base type in any member-pointer chunks.
6112 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
6113 DeclarationName Name) {
6114 // The types we specifically need to rebuild are:
6115 // - typenames, typeofs, and decltypes
6116 // - types which will become injected class names
6117 // Of course, we also need to rebuild any type referencing such a
6118 // type. It's safest to just say "dependent", but we call out a
6119 // few cases here.
6121 DeclSpec &DS = D.getMutableDeclSpec();
6122 switch (DS.getTypeSpecType()) {
6123 case DeclSpec::TST_typename:
6124 case DeclSpec::TST_typeofType:
6125 case DeclSpec::TST_typeof_unqualType:
6126 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6127 #include "clang/Basic/TransformTypeTraits.def"
6128 case DeclSpec::TST_atomic: {
6129 // Grab the type from the parser.
6130 TypeSourceInfo *TSI = nullptr;
6131 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6132 if (T.isNull() || !T->isInstantiationDependentType()) break;
6134 // Make sure there's a type source info. This isn't really much
6135 // of a waste; most dependent types should have type source info
6136 // attached already.
6137 if (!TSI)
6138 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
6140 // Rebuild the type in the current instantiation.
6141 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
6142 if (!TSI) return true;
6144 // Store the new type back in the decl spec.
6145 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6146 DS.UpdateTypeRep(LocType);
6147 break;
6150 case DeclSpec::TST_decltype:
6151 case DeclSpec::TST_typeof_unqualExpr:
6152 case DeclSpec::TST_typeofExpr: {
6153 Expr *E = DS.getRepAsExpr();
6154 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
6155 if (Result.isInvalid()) return true;
6156 DS.UpdateExprRep(Result.get());
6157 break;
6160 default:
6161 // Nothing to do for these decl specs.
6162 break;
6165 // It doesn't matter what order we do this in.
6166 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6167 DeclaratorChunk &Chunk = D.getTypeObject(I);
6169 // The only type information in the declarator which can come
6170 // before the declaration name is the base type of a member
6171 // pointer.
6172 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
6173 continue;
6175 // Rebuild the scope specifier in-place.
6176 CXXScopeSpec &SS = Chunk.Mem.Scope();
6177 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
6178 return true;
6181 return false;
6184 /// Returns true if the declaration is declared in a system header or from a
6185 /// system macro.
6186 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6187 return SM.isInSystemHeader(D->getLocation()) ||
6188 SM.isInSystemMacro(D->getLocation());
6191 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
6192 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6193 // of system decl.
6194 if (D->getPreviousDecl() || D->isImplicit())
6195 return;
6196 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6197 if (Status != ReservedIdentifierStatus::NotReserved &&
6198 !isFromSystemHeader(Context.getSourceManager(), D)) {
6199 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6200 << D << static_cast<int>(Status);
6204 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
6205 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6207 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6208 // declaration only if the `bind_to_declaration` extension is set.
6209 SmallVector<FunctionDecl *, 4> Bases;
6210 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
6211 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
6212 implementation_extension_bind_to_declaration))
6213 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
6214 S, D, MultiTemplateParamsArg(), Bases);
6216 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
6218 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6219 Dcl && Dcl->getDeclContext()->isFileContext())
6220 Dcl->setTopLevelDeclInObjCContainer();
6222 if (!Bases.empty())
6223 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
6225 return Dcl;
6228 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
6229 /// If T is the name of a class, then each of the following shall have a
6230 /// name different from T:
6231 /// - every static data member of class T;
6232 /// - every member function of class T
6233 /// - every member of class T that is itself a type;
6234 /// \returns true if the declaration name violates these rules.
6235 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
6236 DeclarationNameInfo NameInfo) {
6237 DeclarationName Name = NameInfo.getName();
6239 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6240 while (Record && Record->isAnonymousStructOrUnion())
6241 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6242 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6243 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6244 return true;
6247 return false;
6250 /// Diagnose a declaration whose declarator-id has the given
6251 /// nested-name-specifier.
6253 /// \param SS The nested-name-specifier of the declarator-id.
6255 /// \param DC The declaration context to which the nested-name-specifier
6256 /// resolves.
6258 /// \param Name The name of the entity being declared.
6260 /// \param Loc The location of the name of the entity being declared.
6262 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
6263 /// we're declaring an explicit / partial specialization / instantiation.
6265 /// \returns true if we cannot safely recover from this error, false otherwise.
6266 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
6267 DeclarationName Name,
6268 SourceLocation Loc, bool IsTemplateId) {
6269 DeclContext *Cur = CurContext;
6270 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6271 Cur = Cur->getParent();
6273 // If the user provided a superfluous scope specifier that refers back to the
6274 // class in which the entity is already declared, diagnose and ignore it.
6276 // class X {
6277 // void X::f();
6278 // };
6280 // Note, it was once ill-formed to give redundant qualification in all
6281 // contexts, but that rule was removed by DR482.
6282 if (Cur->Equals(DC)) {
6283 if (Cur->isRecord()) {
6284 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6285 : diag::err_member_extra_qualification)
6286 << Name << FixItHint::CreateRemoval(SS.getRange());
6287 SS.clear();
6288 } else {
6289 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6291 return false;
6294 // Check whether the qualifying scope encloses the scope of the original
6295 // declaration. For a template-id, we perform the checks in
6296 // CheckTemplateSpecializationScope.
6297 if (!Cur->Encloses(DC) && !IsTemplateId) {
6298 if (Cur->isRecord())
6299 Diag(Loc, diag::err_member_qualification)
6300 << Name << SS.getRange();
6301 else if (isa<TranslationUnitDecl>(DC))
6302 Diag(Loc, diag::err_invalid_declarator_global_scope)
6303 << Name << SS.getRange();
6304 else if (isa<FunctionDecl>(Cur))
6305 Diag(Loc, diag::err_invalid_declarator_in_function)
6306 << Name << SS.getRange();
6307 else if (isa<BlockDecl>(Cur))
6308 Diag(Loc, diag::err_invalid_declarator_in_block)
6309 << Name << SS.getRange();
6310 else if (isa<ExportDecl>(Cur)) {
6311 if (!isa<NamespaceDecl>(DC))
6312 Diag(Loc, diag::err_export_non_namespace_scope_name)
6313 << Name << SS.getRange();
6314 else
6315 // The cases that DC is not NamespaceDecl should be handled in
6316 // CheckRedeclarationExported.
6317 return false;
6318 } else
6319 Diag(Loc, diag::err_invalid_declarator_scope)
6320 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6322 return true;
6325 if (Cur->isRecord()) {
6326 // Cannot qualify members within a class.
6327 Diag(Loc, diag::err_member_qualification)
6328 << Name << SS.getRange();
6329 SS.clear();
6331 // C++ constructors and destructors with incorrect scopes can break
6332 // our AST invariants by having the wrong underlying types. If
6333 // that's the case, then drop this declaration entirely.
6334 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6335 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6336 !Context.hasSameType(Name.getCXXNameType(),
6337 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6338 return true;
6340 return false;
6343 // C++11 [dcl.meaning]p1:
6344 // [...] "The nested-name-specifier of the qualified declarator-id shall
6345 // not begin with a decltype-specifer"
6346 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
6347 while (SpecLoc.getPrefix())
6348 SpecLoc = SpecLoc.getPrefix();
6349 if (isa_and_nonnull<DecltypeType>(
6350 SpecLoc.getNestedNameSpecifier()->getAsType()))
6351 Diag(Loc, diag::err_decltype_in_declarator)
6352 << SpecLoc.getTypeLoc().getSourceRange();
6354 return false;
6357 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
6358 MultiTemplateParamsArg TemplateParamLists) {
6359 // TODO: consider using NameInfo for diagnostic.
6360 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6361 DeclarationName Name = NameInfo.getName();
6363 // All of these full declarators require an identifier. If it doesn't have
6364 // one, the ParsedFreeStandingDeclSpec action should be used.
6365 if (D.isDecompositionDeclarator()) {
6366 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6367 } else if (!Name) {
6368 if (!D.isInvalidType()) // Reject this if we think it is valid.
6369 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6370 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6371 return nullptr;
6372 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
6373 return nullptr;
6375 // The scope passed in may not be a decl scope. Zip up the scope tree until
6376 // we find one that is.
6377 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6378 (S->getFlags() & Scope::TemplateParamScope) != 0)
6379 S = S->getParent();
6381 DeclContext *DC = CurContext;
6382 if (D.getCXXScopeSpec().isInvalid())
6383 D.setInvalidType();
6384 else if (D.getCXXScopeSpec().isSet()) {
6385 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6386 UPPC_DeclarationQualifier))
6387 return nullptr;
6389 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6390 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6391 if (!DC || isa<EnumDecl>(DC)) {
6392 // If we could not compute the declaration context, it's because the
6393 // declaration context is dependent but does not refer to a class,
6394 // class template, or class template partial specialization. Complain
6395 // and return early, to avoid the coming semantic disaster.
6396 Diag(D.getIdentifierLoc(),
6397 diag::err_template_qualified_declarator_no_match)
6398 << D.getCXXScopeSpec().getScopeRep()
6399 << D.getCXXScopeSpec().getRange();
6400 return nullptr;
6402 bool IsDependentContext = DC->isDependentContext();
6404 if (!IsDependentContext &&
6405 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6406 return nullptr;
6408 // If a class is incomplete, do not parse entities inside it.
6409 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6410 Diag(D.getIdentifierLoc(),
6411 diag::err_member_def_undefined_record)
6412 << Name << DC << D.getCXXScopeSpec().getRange();
6413 return nullptr;
6415 if (!D.getDeclSpec().isFriendSpecified()) {
6416 if (diagnoseQualifiedDeclaration(
6417 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6418 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
6419 if (DC->isRecord())
6420 return nullptr;
6422 D.setInvalidType();
6426 // Check whether we need to rebuild the type of the given
6427 // declaration in the current instantiation.
6428 if (EnteringContext && IsDependentContext &&
6429 TemplateParamLists.size() != 0) {
6430 ContextRAII SavedContext(*this, DC);
6431 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6432 D.setInvalidType();
6436 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6437 QualType R = TInfo->getType();
6439 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6440 UPPC_DeclarationType))
6441 D.setInvalidType();
6443 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6444 forRedeclarationInCurContext());
6446 // See if this is a redefinition of a variable in the same scope.
6447 if (!D.getCXXScopeSpec().isSet()) {
6448 bool IsLinkageLookup = false;
6449 bool CreateBuiltins = false;
6451 // If the declaration we're planning to build will be a function
6452 // or object with linkage, then look for another declaration with
6453 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6455 // If the declaration we're planning to build will be declared with
6456 // external linkage in the translation unit, create any builtin with
6457 // the same name.
6458 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6459 /* Do nothing*/;
6460 else if (CurContext->isFunctionOrMethod() &&
6461 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6462 R->isFunctionType())) {
6463 IsLinkageLookup = true;
6464 CreateBuiltins =
6465 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6466 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6467 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6468 CreateBuiltins = true;
6470 if (IsLinkageLookup) {
6471 Previous.clear(LookupRedeclarationWithLinkage);
6472 Previous.setRedeclarationKind(ForExternalRedeclaration);
6475 LookupName(Previous, S, CreateBuiltins);
6476 } else { // Something like "int foo::x;"
6477 LookupQualifiedName(Previous, DC);
6479 // C++ [dcl.meaning]p1:
6480 // When the declarator-id is qualified, the declaration shall refer to a
6481 // previously declared member of the class or namespace to which the
6482 // qualifier refers (or, in the case of a namespace, of an element of the
6483 // inline namespace set of that namespace (7.3.1)) or to a specialization
6484 // thereof; [...]
6486 // Note that we already checked the context above, and that we do not have
6487 // enough information to make sure that Previous contains the declaration
6488 // we want to match. For example, given:
6490 // class X {
6491 // void f();
6492 // void f(float);
6493 // };
6495 // void X::f(int) { } // ill-formed
6497 // In this case, Previous will point to the overload set
6498 // containing the two f's declared in X, but neither of them
6499 // matches.
6501 RemoveUsingDecls(Previous);
6504 if (Previous.isSingleResult() &&
6505 Previous.getFoundDecl()->isTemplateParameter()) {
6506 // Maybe we will complain about the shadowed template parameter.
6507 if (!D.isInvalidType())
6508 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6509 Previous.getFoundDecl());
6511 // Just pretend that we didn't see the previous declaration.
6512 Previous.clear();
6515 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6516 // Forget that the previous declaration is the injected-class-name.
6517 Previous.clear();
6519 // In C++, the previous declaration we find might be a tag type
6520 // (class or enum). In this case, the new declaration will hide the
6521 // tag type. Note that this applies to functions, function templates, and
6522 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6523 if (Previous.isSingleTagDecl() &&
6524 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6525 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6526 Previous.clear();
6528 // Check that there are no default arguments other than in the parameters
6529 // of a function declaration (C++ only).
6530 if (getLangOpts().CPlusPlus)
6531 CheckExtraCXXDefaultArguments(D);
6533 NamedDecl *New;
6535 bool AddToScope = true;
6536 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6537 if (TemplateParamLists.size()) {
6538 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6539 return nullptr;
6542 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6543 } else if (R->isFunctionType()) {
6544 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6545 TemplateParamLists,
6546 AddToScope);
6547 } else {
6548 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6549 AddToScope);
6552 if (!New)
6553 return nullptr;
6555 // If this has an identifier and is not a function template specialization,
6556 // add it to the scope stack.
6557 if (New->getDeclName() && AddToScope)
6558 PushOnScopeChains(New, S);
6560 if (isInOpenMPDeclareTargetContext())
6561 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6563 return New;
6566 /// Helper method to turn variable array types into constant array
6567 /// types in certain situations which would otherwise be errors (for
6568 /// GCC compatibility).
6569 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6570 ASTContext &Context,
6571 bool &SizeIsNegative,
6572 llvm::APSInt &Oversized) {
6573 // This method tries to turn a variable array into a constant
6574 // array even when the size isn't an ICE. This is necessary
6575 // for compatibility with code that depends on gcc's buggy
6576 // constant expression folding, like struct {char x[(int)(char*)2];}
6577 SizeIsNegative = false;
6578 Oversized = 0;
6580 if (T->isDependentType())
6581 return QualType();
6583 QualifierCollector Qs;
6584 const Type *Ty = Qs.strip(T);
6586 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6587 QualType Pointee = PTy->getPointeeType();
6588 QualType FixedType =
6589 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6590 Oversized);
6591 if (FixedType.isNull()) return FixedType;
6592 FixedType = Context.getPointerType(FixedType);
6593 return Qs.apply(Context, FixedType);
6595 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6596 QualType Inner = PTy->getInnerType();
6597 QualType FixedType =
6598 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6599 Oversized);
6600 if (FixedType.isNull()) return FixedType;
6601 FixedType = Context.getParenType(FixedType);
6602 return Qs.apply(Context, FixedType);
6605 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6606 if (!VLATy)
6607 return QualType();
6609 QualType ElemTy = VLATy->getElementType();
6610 if (ElemTy->isVariablyModifiedType()) {
6611 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6612 SizeIsNegative, Oversized);
6613 if (ElemTy.isNull())
6614 return QualType();
6617 Expr::EvalResult Result;
6618 if (!VLATy->getSizeExpr() ||
6619 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6620 return QualType();
6622 llvm::APSInt Res = Result.Val.getInt();
6624 // Check whether the array size is negative.
6625 if (Res.isSigned() && Res.isNegative()) {
6626 SizeIsNegative = true;
6627 return QualType();
6630 // Check whether the array is too large to be addressed.
6631 unsigned ActiveSizeBits =
6632 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6633 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6634 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6635 : Res.getActiveBits();
6636 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6637 Oversized = Res;
6638 return QualType();
6641 QualType FoldedArrayType = Context.getConstantArrayType(
6642 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6643 return Qs.apply(Context, FoldedArrayType);
6646 static void
6647 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6648 SrcTL = SrcTL.getUnqualifiedLoc();
6649 DstTL = DstTL.getUnqualifiedLoc();
6650 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6651 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6652 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6653 DstPTL.getPointeeLoc());
6654 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6655 return;
6657 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6658 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6659 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6660 DstPTL.getInnerLoc());
6661 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6662 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6663 return;
6665 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6666 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6667 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6668 TypeLoc DstElemTL = DstATL.getElementLoc();
6669 if (VariableArrayTypeLoc SrcElemATL =
6670 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6671 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6672 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6673 } else {
6674 DstElemTL.initializeFullCopy(SrcElemTL);
6676 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6677 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6678 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6681 /// Helper method to turn variable array types into constant array
6682 /// types in certain situations which would otherwise be errors (for
6683 /// GCC compatibility).
6684 static TypeSourceInfo*
6685 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6686 ASTContext &Context,
6687 bool &SizeIsNegative,
6688 llvm::APSInt &Oversized) {
6689 QualType FixedTy
6690 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6691 SizeIsNegative, Oversized);
6692 if (FixedTy.isNull())
6693 return nullptr;
6694 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6695 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6696 FixedTInfo->getTypeLoc());
6697 return FixedTInfo;
6700 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6701 /// true if we were successful.
6702 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6703 QualType &T, SourceLocation Loc,
6704 unsigned FailedFoldDiagID) {
6705 bool SizeIsNegative;
6706 llvm::APSInt Oversized;
6707 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6708 TInfo, Context, SizeIsNegative, Oversized);
6709 if (FixedTInfo) {
6710 Diag(Loc, diag::ext_vla_folded_to_constant);
6711 TInfo = FixedTInfo;
6712 T = FixedTInfo->getType();
6713 return true;
6716 if (SizeIsNegative)
6717 Diag(Loc, diag::err_typecheck_negative_array_size);
6718 else if (Oversized.getBoolValue())
6719 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6720 else if (FailedFoldDiagID)
6721 Diag(Loc, FailedFoldDiagID);
6722 return false;
6725 /// Register the given locally-scoped extern "C" declaration so
6726 /// that it can be found later for redeclarations. We include any extern "C"
6727 /// declaration that is not visible in the translation unit here, not just
6728 /// function-scope declarations.
6729 void
6730 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6731 if (!getLangOpts().CPlusPlus &&
6732 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6733 // Don't need to track declarations in the TU in C.
6734 return;
6736 // Note that we have a locally-scoped external with this name.
6737 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6740 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6741 // FIXME: We can have multiple results via __attribute__((overloadable)).
6742 auto Result = Context.getExternCContextDecl()->lookup(Name);
6743 return Result.empty() ? nullptr : *Result.begin();
6746 /// Diagnose function specifiers on a declaration of an identifier that
6747 /// does not identify a function.
6748 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6749 // FIXME: We should probably indicate the identifier in question to avoid
6750 // confusion for constructs like "virtual int a(), b;"
6751 if (DS.isVirtualSpecified())
6752 Diag(DS.getVirtualSpecLoc(),
6753 diag::err_virtual_non_function);
6755 if (DS.hasExplicitSpecifier())
6756 Diag(DS.getExplicitSpecLoc(),
6757 diag::err_explicit_non_function);
6759 if (DS.isNoreturnSpecified())
6760 Diag(DS.getNoreturnSpecLoc(),
6761 diag::err_noreturn_non_function);
6764 NamedDecl*
6765 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6766 TypeSourceInfo *TInfo, LookupResult &Previous) {
6767 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6768 if (D.getCXXScopeSpec().isSet()) {
6769 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6770 << D.getCXXScopeSpec().getRange();
6771 D.setInvalidType();
6772 // Pretend we didn't see the scope specifier.
6773 DC = CurContext;
6774 Previous.clear();
6777 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6779 if (D.getDeclSpec().isInlineSpecified())
6780 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6781 << getLangOpts().CPlusPlus17;
6782 if (D.getDeclSpec().hasConstexprSpecifier())
6783 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6784 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6786 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6787 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
6788 Diag(D.getName().StartLocation,
6789 diag::err_deduction_guide_invalid_specifier)
6790 << "typedef";
6791 else
6792 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6793 << D.getName().getSourceRange();
6794 return nullptr;
6797 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6798 if (!NewTD) return nullptr;
6800 // Handle attributes prior to checking for duplicates in MergeVarDecl
6801 ProcessDeclAttributes(S, NewTD, D);
6803 CheckTypedefForVariablyModifiedType(S, NewTD);
6805 bool Redeclaration = D.isRedeclaration();
6806 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6807 D.setRedeclaration(Redeclaration);
6808 return ND;
6811 void
6812 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6813 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6814 // then it shall have block scope.
6815 // Note that variably modified types must be fixed before merging the decl so
6816 // that redeclarations will match.
6817 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6818 QualType T = TInfo->getType();
6819 if (T->isVariablyModifiedType()) {
6820 setFunctionHasBranchProtectedScope();
6822 if (S->getFnParent() == nullptr) {
6823 bool SizeIsNegative;
6824 llvm::APSInt Oversized;
6825 TypeSourceInfo *FixedTInfo =
6826 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6827 SizeIsNegative,
6828 Oversized);
6829 if (FixedTInfo) {
6830 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6831 NewTD->setTypeSourceInfo(FixedTInfo);
6832 } else {
6833 if (SizeIsNegative)
6834 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6835 else if (T->isVariableArrayType())
6836 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6837 else if (Oversized.getBoolValue())
6838 Diag(NewTD->getLocation(), diag::err_array_too_large)
6839 << toString(Oversized, 10);
6840 else
6841 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6842 NewTD->setInvalidDecl();
6848 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6849 /// declares a typedef-name, either using the 'typedef' type specifier or via
6850 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6851 NamedDecl*
6852 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6853 LookupResult &Previous, bool &Redeclaration) {
6855 // Find the shadowed declaration before filtering for scope.
6856 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6858 // Merge the decl with the existing one if appropriate. If the decl is
6859 // in an outer scope, it isn't the same thing.
6860 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6861 /*AllowInlineNamespace*/false);
6862 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6863 if (!Previous.empty()) {
6864 Redeclaration = true;
6865 MergeTypedefNameDecl(S, NewTD, Previous);
6866 } else {
6867 inferGslPointerAttribute(NewTD);
6870 if (ShadowedDecl && !Redeclaration)
6871 CheckShadow(NewTD, ShadowedDecl, Previous);
6873 // If this is the C FILE type, notify the AST context.
6874 if (IdentifierInfo *II = NewTD->getIdentifier())
6875 if (!NewTD->isInvalidDecl() &&
6876 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6877 switch (II->getInterestingIdentifierID()) {
6878 case tok::InterestingIdentifierKind::FILE:
6879 Context.setFILEDecl(NewTD);
6880 break;
6881 case tok::InterestingIdentifierKind::jmp_buf:
6882 Context.setjmp_bufDecl(NewTD);
6883 break;
6884 case tok::InterestingIdentifierKind::sigjmp_buf:
6885 Context.setsigjmp_bufDecl(NewTD);
6886 break;
6887 case tok::InterestingIdentifierKind::ucontext_t:
6888 Context.setucontext_tDecl(NewTD);
6889 break;
6890 case tok::InterestingIdentifierKind::float_t:
6891 case tok::InterestingIdentifierKind::double_t:
6892 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6893 break;
6894 default:
6895 break;
6899 return NewTD;
6902 /// Determines whether the given declaration is an out-of-scope
6903 /// previous declaration.
6905 /// This routine should be invoked when name lookup has found a
6906 /// previous declaration (PrevDecl) that is not in the scope where a
6907 /// new declaration by the same name is being introduced. If the new
6908 /// declaration occurs in a local scope, previous declarations with
6909 /// linkage may still be considered previous declarations (C99
6910 /// 6.2.2p4-5, C++ [basic.link]p6).
6912 /// \param PrevDecl the previous declaration found by name
6913 /// lookup
6915 /// \param DC the context in which the new declaration is being
6916 /// declared.
6918 /// \returns true if PrevDecl is an out-of-scope previous declaration
6919 /// for a new delcaration with the same name.
6920 static bool
6921 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6922 ASTContext &Context) {
6923 if (!PrevDecl)
6924 return false;
6926 if (!PrevDecl->hasLinkage())
6927 return false;
6929 if (Context.getLangOpts().CPlusPlus) {
6930 // C++ [basic.link]p6:
6931 // If there is a visible declaration of an entity with linkage
6932 // having the same name and type, ignoring entities declared
6933 // outside the innermost enclosing namespace scope, the block
6934 // scope declaration declares that same entity and receives the
6935 // linkage of the previous declaration.
6936 DeclContext *OuterContext = DC->getRedeclContext();
6937 if (!OuterContext->isFunctionOrMethod())
6938 // This rule only applies to block-scope declarations.
6939 return false;
6941 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6942 if (PrevOuterContext->isRecord())
6943 // We found a member function: ignore it.
6944 return false;
6946 // Find the innermost enclosing namespace for the new and
6947 // previous declarations.
6948 OuterContext = OuterContext->getEnclosingNamespaceContext();
6949 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6951 // The previous declaration is in a different namespace, so it
6952 // isn't the same function.
6953 if (!OuterContext->Equals(PrevOuterContext))
6954 return false;
6957 return true;
6960 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6961 CXXScopeSpec &SS = D.getCXXScopeSpec();
6962 if (!SS.isSet()) return;
6963 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6966 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6967 QualType type = decl->getType();
6968 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6969 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6970 // Various kinds of declaration aren't allowed to be __autoreleasing.
6971 unsigned kind = -1U;
6972 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6973 if (var->hasAttr<BlocksAttr>())
6974 kind = 0; // __block
6975 else if (!var->hasLocalStorage())
6976 kind = 1; // global
6977 } else if (isa<ObjCIvarDecl>(decl)) {
6978 kind = 3; // ivar
6979 } else if (isa<FieldDecl>(decl)) {
6980 kind = 2; // field
6983 if (kind != -1U) {
6984 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6985 << kind;
6987 } else if (lifetime == Qualifiers::OCL_None) {
6988 // Try to infer lifetime.
6989 if (!type->isObjCLifetimeType())
6990 return false;
6992 lifetime = type->getObjCARCImplicitLifetime();
6993 type = Context.getLifetimeQualifiedType(type, lifetime);
6994 decl->setType(type);
6997 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6998 // Thread-local variables cannot have lifetime.
6999 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
7000 var->getTLSKind()) {
7001 Diag(var->getLocation(), diag::err_arc_thread_ownership)
7002 << var->getType();
7003 return true;
7007 return false;
7010 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
7011 if (Decl->getType().hasAddressSpace())
7012 return;
7013 if (Decl->getType()->isDependentType())
7014 return;
7015 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
7016 QualType Type = Var->getType();
7017 if (Type->isSamplerT() || Type->isVoidType())
7018 return;
7019 LangAS ImplAS = LangAS::opencl_private;
7020 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7021 // __opencl_c_program_scope_global_variables feature, the address space
7022 // for a variable at program scope or a static or extern variable inside
7023 // a function are inferred to be __global.
7024 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7025 Var->hasGlobalStorage())
7026 ImplAS = LangAS::opencl_global;
7027 // If the original type from a decayed type is an array type and that array
7028 // type has no address space yet, deduce it now.
7029 if (auto DT = dyn_cast<DecayedType>(Type)) {
7030 auto OrigTy = DT->getOriginalType();
7031 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7032 // Add the address space to the original array type and then propagate
7033 // that to the element type through `getAsArrayType`.
7034 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7035 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7036 // Re-generate the decayed type.
7037 Type = Context.getDecayedType(OrigTy);
7040 Type = Context.getAddrSpaceQualType(Type, ImplAS);
7041 // Apply any qualifiers (including address space) from the array type to
7042 // the element type. This implements C99 6.7.3p8: "If the specification of
7043 // an array type includes any type qualifiers, the element type is so
7044 // qualified, not the array type."
7045 if (Type->isArrayType())
7046 Type = QualType(Context.getAsArrayType(Type), 0);
7047 Decl->setType(Type);
7051 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
7052 // Ensure that an auto decl is deduced otherwise the checks below might cache
7053 // the wrong linkage.
7054 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7056 // 'weak' only applies to declarations with external linkage.
7057 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7058 if (!ND.isExternallyVisible()) {
7059 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7060 ND.dropAttr<WeakAttr>();
7063 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7064 if (ND.isExternallyVisible()) {
7065 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7066 ND.dropAttr<WeakRefAttr>();
7067 ND.dropAttr<AliasAttr>();
7071 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7072 if (VD->hasInit()) {
7073 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7074 assert(VD->isThisDeclarationADefinition() &&
7075 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7076 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7077 VD->dropAttr<AliasAttr>();
7082 // 'selectany' only applies to externally visible variable declarations.
7083 // It does not apply to functions.
7084 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7085 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7086 S.Diag(Attr->getLocation(),
7087 diag::err_attribute_selectany_non_extern_data);
7088 ND.dropAttr<SelectAnyAttr>();
7092 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7093 auto *VD = dyn_cast<VarDecl>(&ND);
7094 bool IsAnonymousNS = false;
7095 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7096 if (VD) {
7097 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7098 while (NS && !IsAnonymousNS) {
7099 IsAnonymousNS = NS->isAnonymousNamespace();
7100 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7103 // dll attributes require external linkage. Static locals may have external
7104 // linkage but still cannot be explicitly imported or exported.
7105 // In Microsoft mode, a variable defined in anonymous namespace must have
7106 // external linkage in order to be exported.
7107 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7108 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7109 (!AnonNSInMicrosoftMode &&
7110 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7111 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7112 << &ND << Attr;
7113 ND.setInvalidDecl();
7117 // Check the attributes on the function type, if any.
7118 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7119 // Don't declare this variable in the second operand of the for-statement;
7120 // GCC miscompiles that by ending its lifetime before evaluating the
7121 // third operand. See gcc.gnu.org/PR86769.
7122 AttributedTypeLoc ATL;
7123 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7124 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7125 TL = ATL.getModifiedLoc()) {
7126 // The [[lifetimebound]] attribute can be applied to the implicit object
7127 // parameter of a non-static member function (other than a ctor or dtor)
7128 // by applying it to the function type.
7129 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7130 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7131 if (!MD || MD->isStatic()) {
7132 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7133 << !MD << A->getRange();
7134 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7135 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7136 << isa<CXXDestructorDecl>(MD) << A->getRange();
7143 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
7144 NamedDecl *NewDecl,
7145 bool IsSpecialization,
7146 bool IsDefinition) {
7147 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7148 return;
7150 bool IsTemplate = false;
7151 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7152 OldDecl = OldTD->getTemplatedDecl();
7153 IsTemplate = true;
7154 if (!IsSpecialization)
7155 IsDefinition = false;
7157 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7158 NewDecl = NewTD->getTemplatedDecl();
7159 IsTemplate = true;
7162 if (!OldDecl || !NewDecl)
7163 return;
7165 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7166 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7167 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7168 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7170 // dllimport and dllexport are inheritable attributes so we have to exclude
7171 // inherited attribute instances.
7172 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7173 (NewExportAttr && !NewExportAttr->isInherited());
7175 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7176 // the only exception being explicit specializations.
7177 // Implicitly generated declarations are also excluded for now because there
7178 // is no other way to switch these to use dllimport or dllexport.
7179 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7181 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7182 // Allow with a warning for free functions and global variables.
7183 bool JustWarn = false;
7184 if (!OldDecl->isCXXClassMember()) {
7185 auto *VD = dyn_cast<VarDecl>(OldDecl);
7186 if (VD && !VD->getDescribedVarTemplate())
7187 JustWarn = true;
7188 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7189 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7190 JustWarn = true;
7193 // We cannot change a declaration that's been used because IR has already
7194 // been emitted. Dllimported functions will still work though (modulo
7195 // address equality) as they can use the thunk.
7196 if (OldDecl->isUsed())
7197 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7198 JustWarn = false;
7200 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7201 : diag::err_attribute_dll_redeclaration;
7202 S.Diag(NewDecl->getLocation(), DiagID)
7203 << NewDecl
7204 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7205 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7206 if (!JustWarn) {
7207 NewDecl->setInvalidDecl();
7208 return;
7212 // A redeclaration is not allowed to drop a dllimport attribute, the only
7213 // exceptions being inline function definitions (except for function
7214 // templates), local extern declarations, qualified friend declarations or
7215 // special MSVC extension: in the last case, the declaration is treated as if
7216 // it were marked dllexport.
7217 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7218 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7219 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7220 // Ignore static data because out-of-line definitions are diagnosed
7221 // separately.
7222 IsStaticDataMember = VD->isStaticDataMember();
7223 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7224 VarDecl::DeclarationOnly;
7225 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7226 IsInline = FD->isInlined();
7227 IsQualifiedFriend = FD->getQualifier() &&
7228 FD->getFriendObjectKind() == Decl::FOK_Declared;
7231 if (OldImportAttr && !HasNewAttr &&
7232 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7233 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7234 if (IsMicrosoftABI && IsDefinition) {
7235 if (IsSpecialization) {
7236 S.Diag(
7237 NewDecl->getLocation(),
7238 diag::err_attribute_dllimport_function_specialization_definition);
7239 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7240 NewDecl->dropAttr<DLLImportAttr>();
7241 } else {
7242 S.Diag(NewDecl->getLocation(),
7243 diag::warn_redeclaration_without_import_attribute)
7244 << NewDecl;
7245 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7246 NewDecl->dropAttr<DLLImportAttr>();
7247 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7248 S.Context, NewImportAttr->getRange()));
7250 } else if (IsMicrosoftABI && IsSpecialization) {
7251 assert(!IsDefinition);
7252 // MSVC allows this. Keep the inherited attribute.
7253 } else {
7254 S.Diag(NewDecl->getLocation(),
7255 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7256 << NewDecl << OldImportAttr;
7257 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7258 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7259 OldDecl->dropAttr<DLLImportAttr>();
7260 NewDecl->dropAttr<DLLImportAttr>();
7262 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7263 // In MinGW, seeing a function declared inline drops the dllimport
7264 // attribute.
7265 OldDecl->dropAttr<DLLImportAttr>();
7266 NewDecl->dropAttr<DLLImportAttr>();
7267 S.Diag(NewDecl->getLocation(),
7268 diag::warn_dllimport_dropped_from_inline_function)
7269 << NewDecl << OldImportAttr;
7272 // A specialization of a class template member function is processed here
7273 // since it's a redeclaration. If the parent class is dllexport, the
7274 // specialization inherits that attribute. This doesn't happen automatically
7275 // since the parent class isn't instantiated until later.
7276 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7277 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7278 !NewImportAttr && !NewExportAttr) {
7279 if (const DLLExportAttr *ParentExportAttr =
7280 MD->getParent()->getAttr<DLLExportAttr>()) {
7281 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7282 NewAttr->setInherited(true);
7283 NewDecl->addAttr(NewAttr);
7289 /// Given that we are within the definition of the given function,
7290 /// will that definition behave like C99's 'inline', where the
7291 /// definition is discarded except for optimization purposes?
7292 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
7293 // Try to avoid calling GetGVALinkageForFunction.
7295 // All cases of this require the 'inline' keyword.
7296 if (!FD->isInlined()) return false;
7298 // This is only possible in C++ with the gnu_inline attribute.
7299 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7300 return false;
7302 // Okay, go ahead and call the relatively-more-expensive function.
7303 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
7306 /// Determine whether a variable is extern "C" prior to attaching
7307 /// an initializer. We can't just call isExternC() here, because that
7308 /// will also compute and cache whether the declaration is externally
7309 /// visible, which might change when we attach the initializer.
7311 /// This can only be used if the declaration is known to not be a
7312 /// redeclaration of an internal linkage declaration.
7314 /// For instance:
7316 /// auto x = []{};
7318 /// Attaching the initializer here makes this declaration not externally
7319 /// visible, because its type has internal linkage.
7321 /// FIXME: This is a hack.
7322 template<typename T>
7323 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7324 if (S.getLangOpts().CPlusPlus) {
7325 // In C++, the overloadable attribute negates the effects of extern "C".
7326 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7327 return false;
7329 // So do CUDA's host/device attributes.
7330 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7331 D->template hasAttr<CUDAHostAttr>()))
7332 return false;
7334 return D->isExternC();
7337 static bool shouldConsiderLinkage(const VarDecl *VD) {
7338 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7339 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7340 isa<OMPDeclareMapperDecl>(DC))
7341 return VD->hasExternalStorage();
7342 if (DC->isFileContext())
7343 return true;
7344 if (DC->isRecord())
7345 return false;
7346 if (DC->getDeclKind() == Decl::HLSLBuffer)
7347 return false;
7349 if (isa<RequiresExprBodyDecl>(DC))
7350 return false;
7351 llvm_unreachable("Unexpected context");
7354 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7355 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7356 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7357 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7358 return true;
7359 if (DC->isRecord())
7360 return false;
7361 llvm_unreachable("Unexpected context");
7364 static bool hasParsedAttr(Scope *S, const Declarator &PD,
7365 ParsedAttr::Kind Kind) {
7366 // Check decl attributes on the DeclSpec.
7367 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7368 return true;
7370 // Walk the declarator structure, checking decl attributes that were in a type
7371 // position to the decl itself.
7372 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7373 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7374 return true;
7377 // Finally, check attributes on the decl itself.
7378 return PD.getAttributes().hasAttribute(Kind) ||
7379 PD.getDeclarationAttributes().hasAttribute(Kind);
7382 /// Adjust the \c DeclContext for a function or variable that might be a
7383 /// function-local external declaration.
7384 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
7385 if (!DC->isFunctionOrMethod())
7386 return false;
7388 // If this is a local extern function or variable declared within a function
7389 // template, don't add it into the enclosing namespace scope until it is
7390 // instantiated; it might have a dependent type right now.
7391 if (DC->isDependentContext())
7392 return true;
7394 // C++11 [basic.link]p7:
7395 // When a block scope declaration of an entity with linkage is not found to
7396 // refer to some other declaration, then that entity is a member of the
7397 // innermost enclosing namespace.
7399 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7400 // semantically-enclosing namespace, not a lexically-enclosing one.
7401 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7402 DC = DC->getParent();
7403 return true;
7406 /// Returns true if given declaration has external C language linkage.
7407 static bool isDeclExternC(const Decl *D) {
7408 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7409 return FD->isExternC();
7410 if (const auto *VD = dyn_cast<VarDecl>(D))
7411 return VD->isExternC();
7413 llvm_unreachable("Unknown type of decl!");
7416 /// Returns true if there hasn't been any invalid type diagnosed.
7417 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7418 DeclContext *DC = NewVD->getDeclContext();
7419 QualType R = NewVD->getType();
7421 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7422 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7423 // argument.
7424 if (R->isImageType() || R->isPipeType()) {
7425 Se.Diag(NewVD->getLocation(),
7426 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7427 << R;
7428 NewVD->setInvalidDecl();
7429 return false;
7432 // OpenCL v1.2 s6.9.r:
7433 // The event type cannot be used to declare a program scope variable.
7434 // OpenCL v2.0 s6.9.q:
7435 // The clk_event_t and reserve_id_t types cannot be declared in program
7436 // scope.
7437 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7438 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7439 Se.Diag(NewVD->getLocation(),
7440 diag::err_invalid_type_for_program_scope_var)
7441 << R;
7442 NewVD->setInvalidDecl();
7443 return false;
7447 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7448 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7449 Se.getLangOpts())) {
7450 QualType NR = R.getCanonicalType();
7451 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7452 NR->isReferenceType()) {
7453 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
7454 NR->isFunctionReferenceType()) {
7455 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7456 << NR->isReferenceType();
7457 NewVD->setInvalidDecl();
7458 return false;
7460 NR = NR->getPointeeType();
7464 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7465 Se.getLangOpts())) {
7466 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7467 // half array type (unless the cl_khr_fp16 extension is enabled).
7468 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7469 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7470 NewVD->setInvalidDecl();
7471 return false;
7475 // OpenCL v1.2 s6.9.r:
7476 // The event type cannot be used with the __local, __constant and __global
7477 // address space qualifiers.
7478 if (R->isEventT()) {
7479 if (R.getAddressSpace() != LangAS::opencl_private) {
7480 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7481 NewVD->setInvalidDecl();
7482 return false;
7486 if (R->isSamplerT()) {
7487 // OpenCL v1.2 s6.9.b p4:
7488 // The sampler type cannot be used with the __local and __global address
7489 // space qualifiers.
7490 if (R.getAddressSpace() == LangAS::opencl_local ||
7491 R.getAddressSpace() == LangAS::opencl_global) {
7492 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7493 NewVD->setInvalidDecl();
7496 // OpenCL v1.2 s6.12.14.1:
7497 // A global sampler must be declared with either the constant address
7498 // space qualifier or with the const qualifier.
7499 if (DC->isTranslationUnit() &&
7500 !(R.getAddressSpace() == LangAS::opencl_constant ||
7501 R.isConstQualified())) {
7502 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7503 NewVD->setInvalidDecl();
7505 if (NewVD->isInvalidDecl())
7506 return false;
7509 return true;
7512 template <typename AttrTy>
7513 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7514 const TypedefNameDecl *TND = TT->getDecl();
7515 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7516 AttrTy *Clone = Attribute->clone(S.Context);
7517 Clone->setInherited(true);
7518 D->addAttr(Clone);
7522 // This function emits warning and a corresponding note based on the
7523 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7524 // declarations of an annotated type must be const qualified.
7525 void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
7526 QualType VarType = VD->getType().getCanonicalType();
7528 // Ignore local declarations (for now) and those with const qualification.
7529 // TODO: Local variables should not be allowed if their type declaration has
7530 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7531 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7532 return;
7534 if (VarType->isArrayType()) {
7535 // Retrieve element type for array declarations.
7536 VarType = S.getASTContext().getBaseElementType(VarType);
7539 const RecordDecl *RD = VarType->getAsRecordDecl();
7541 // Check if the record declaration is present and if it has any attributes.
7542 if (RD == nullptr)
7543 return;
7545 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7546 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7547 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7548 return;
7552 NamedDecl *Sema::ActOnVariableDeclarator(
7553 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7554 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7555 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7556 QualType R = TInfo->getType();
7557 DeclarationName Name = GetNameForDeclarator(D).getName();
7559 IdentifierInfo *II = Name.getAsIdentifierInfo();
7560 bool IsPlaceholderVariable = false;
7562 if (D.isDecompositionDeclarator()) {
7563 // Take the name of the first declarator as our name for diagnostic
7564 // purposes.
7565 auto &Decomp = D.getDecompositionDeclarator();
7566 if (!Decomp.bindings().empty()) {
7567 II = Decomp.bindings()[0].Name;
7568 Name = II;
7570 } else if (!II) {
7571 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7572 return nullptr;
7576 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7577 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
7579 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7580 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7581 IsPlaceholderVariable = true;
7582 if (!Previous.empty()) {
7583 NamedDecl *PrevDecl = *Previous.begin();
7584 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7585 DC->getRedeclContext());
7586 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7587 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7591 // dllimport globals without explicit storage class are treated as extern. We
7592 // have to change the storage class this early to get the right DeclContext.
7593 if (SC == SC_None && !DC->isRecord() &&
7594 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7595 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7596 SC = SC_Extern;
7598 DeclContext *OriginalDC = DC;
7599 bool IsLocalExternDecl = SC == SC_Extern &&
7600 adjustContextForLocalExternDecl(DC);
7602 if (SCSpec == DeclSpec::SCS_mutable) {
7603 // mutable can only appear on non-static class members, so it's always
7604 // an error here
7605 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7606 D.setInvalidType();
7607 SC = SC_None;
7610 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7611 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7612 D.getDeclSpec().getStorageClassSpecLoc())) {
7613 // In C++11, the 'register' storage class specifier is deprecated.
7614 // Suppress the warning in system macros, it's used in macros in some
7615 // popular C system headers, such as in glibc's htonl() macro.
7616 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7617 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7618 : diag::warn_deprecated_register)
7619 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7622 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7624 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7625 // C99 6.9p2: The storage-class specifiers auto and register shall not
7626 // appear in the declaration specifiers in an external declaration.
7627 // Global Register+Asm is a GNU extension we support.
7628 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7629 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7630 D.setInvalidType();
7634 // If this variable has a VLA type and an initializer, try to
7635 // fold to a constant-sized type. This is otherwise invalid.
7636 if (D.hasInitializer() && R->isVariableArrayType())
7637 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7638 /*DiagID=*/0);
7640 bool IsMemberSpecialization = false;
7641 bool IsVariableTemplateSpecialization = false;
7642 bool IsPartialSpecialization = false;
7643 bool IsVariableTemplate = false;
7644 VarDecl *NewVD = nullptr;
7645 VarTemplateDecl *NewTemplate = nullptr;
7646 TemplateParameterList *TemplateParams = nullptr;
7647 if (!getLangOpts().CPlusPlus) {
7648 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7649 II, R, TInfo, SC);
7651 if (R->getContainedDeducedType())
7652 ParsingInitForAutoVars.insert(NewVD);
7654 if (D.isInvalidType())
7655 NewVD->setInvalidDecl();
7657 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7658 NewVD->hasLocalStorage())
7659 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7660 NTCUC_AutoVar, NTCUK_Destruct);
7661 } else {
7662 bool Invalid = false;
7664 if (DC->isRecord() && !CurContext->isRecord()) {
7665 // This is an out-of-line definition of a static data member.
7666 switch (SC) {
7667 case SC_None:
7668 break;
7669 case SC_Static:
7670 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7671 diag::err_static_out_of_line)
7672 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7673 break;
7674 case SC_Auto:
7675 case SC_Register:
7676 case SC_Extern:
7677 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7678 // to names of variables declared in a block or to function parameters.
7679 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7680 // of class members
7682 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7683 diag::err_storage_class_for_static_member)
7684 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7685 break;
7686 case SC_PrivateExtern:
7687 llvm_unreachable("C storage class in c++!");
7691 if (SC == SC_Static && CurContext->isRecord()) {
7692 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7693 // Walk up the enclosing DeclContexts to check for any that are
7694 // incompatible with static data members.
7695 const DeclContext *FunctionOrMethod = nullptr;
7696 const CXXRecordDecl *AnonStruct = nullptr;
7697 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7698 if (Ctxt->isFunctionOrMethod()) {
7699 FunctionOrMethod = Ctxt;
7700 break;
7702 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7703 if (ParentDecl && !ParentDecl->getDeclName()) {
7704 AnonStruct = ParentDecl;
7705 break;
7708 if (FunctionOrMethod) {
7709 // C++ [class.static.data]p5: A local class shall not have static data
7710 // members.
7711 Diag(D.getIdentifierLoc(),
7712 diag::err_static_data_member_not_allowed_in_local_class)
7713 << Name << RD->getDeclName()
7714 << llvm::to_underlying(RD->getTagKind());
7715 } else if (AnonStruct) {
7716 // C++ [class.static.data]p4: Unnamed classes and classes contained
7717 // directly or indirectly within unnamed classes shall not contain
7718 // static data members.
7719 Diag(D.getIdentifierLoc(),
7720 diag::err_static_data_member_not_allowed_in_anon_struct)
7721 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7722 Invalid = true;
7723 } else if (RD->isUnion()) {
7724 // C++98 [class.union]p1: If a union contains a static data member,
7725 // the program is ill-formed. C++11 drops this restriction.
7726 Diag(D.getIdentifierLoc(),
7727 getLangOpts().CPlusPlus11
7728 ? diag::warn_cxx98_compat_static_data_member_in_union
7729 : diag::ext_static_data_member_in_union) << Name;
7734 // Match up the template parameter lists with the scope specifier, then
7735 // determine whether we have a template or a template specialization.
7736 bool InvalidScope = false;
7737 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7738 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7739 D.getCXXScopeSpec(),
7740 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7741 ? D.getName().TemplateId
7742 : nullptr,
7743 TemplateParamLists,
7744 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7745 Invalid |= InvalidScope;
7747 if (TemplateParams) {
7748 if (!TemplateParams->size() &&
7749 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7750 // There is an extraneous 'template<>' for this variable. Complain
7751 // about it, but allow the declaration of the variable.
7752 Diag(TemplateParams->getTemplateLoc(),
7753 diag::err_template_variable_noparams)
7754 << II
7755 << SourceRange(TemplateParams->getTemplateLoc(),
7756 TemplateParams->getRAngleLoc());
7757 TemplateParams = nullptr;
7758 } else {
7759 // Check that we can declare a template here.
7760 if (CheckTemplateDeclScope(S, TemplateParams))
7761 return nullptr;
7763 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7764 // This is an explicit specialization or a partial specialization.
7765 IsVariableTemplateSpecialization = true;
7766 IsPartialSpecialization = TemplateParams->size() > 0;
7767 } else { // if (TemplateParams->size() > 0)
7768 // This is a template declaration.
7769 IsVariableTemplate = true;
7771 // Only C++1y supports variable templates (N3651).
7772 Diag(D.getIdentifierLoc(),
7773 getLangOpts().CPlusPlus14
7774 ? diag::warn_cxx11_compat_variable_template
7775 : diag::ext_variable_template);
7778 } else {
7779 // Check that we can declare a member specialization here.
7780 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7781 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7782 return nullptr;
7783 assert((Invalid ||
7784 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7785 "should have a 'template<>' for this decl");
7788 if (IsVariableTemplateSpecialization) {
7789 SourceLocation TemplateKWLoc =
7790 TemplateParamLists.size() > 0
7791 ? TemplateParamLists[0]->getTemplateLoc()
7792 : SourceLocation();
7793 DeclResult Res = ActOnVarTemplateSpecialization(
7794 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7795 IsPartialSpecialization);
7796 if (Res.isInvalid())
7797 return nullptr;
7798 NewVD = cast<VarDecl>(Res.get());
7799 AddToScope = false;
7800 } else if (D.isDecompositionDeclarator()) {
7801 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7802 D.getIdentifierLoc(), R, TInfo, SC,
7803 Bindings);
7804 } else
7805 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7806 D.getIdentifierLoc(), II, R, TInfo, SC);
7808 // If this is supposed to be a variable template, create it as such.
7809 if (IsVariableTemplate) {
7810 NewTemplate =
7811 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7812 TemplateParams, NewVD);
7813 NewVD->setDescribedVarTemplate(NewTemplate);
7816 // If this decl has an auto type in need of deduction, make a note of the
7817 // Decl so we can diagnose uses of it in its own initializer.
7818 if (R->getContainedDeducedType())
7819 ParsingInitForAutoVars.insert(NewVD);
7821 if (D.isInvalidType() || Invalid) {
7822 NewVD->setInvalidDecl();
7823 if (NewTemplate)
7824 NewTemplate->setInvalidDecl();
7827 SetNestedNameSpecifier(*this, NewVD, D);
7829 // If we have any template parameter lists that don't directly belong to
7830 // the variable (matching the scope specifier), store them.
7831 // An explicit variable template specialization does not own any template
7832 // parameter lists.
7833 bool IsExplicitSpecialization =
7834 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7835 unsigned VDTemplateParamLists =
7836 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7837 if (TemplateParamLists.size() > VDTemplateParamLists)
7838 NewVD->setTemplateParameterListsInfo(
7839 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7842 if (D.getDeclSpec().isInlineSpecified()) {
7843 if (!getLangOpts().CPlusPlus) {
7844 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7845 << 0;
7846 } else if (CurContext->isFunctionOrMethod()) {
7847 // 'inline' is not allowed on block scope variable declaration.
7848 Diag(D.getDeclSpec().getInlineSpecLoc(),
7849 diag::err_inline_declaration_block_scope) << Name
7850 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7851 } else {
7852 Diag(D.getDeclSpec().getInlineSpecLoc(),
7853 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7854 : diag::ext_inline_variable);
7855 NewVD->setInlineSpecified();
7859 // Set the lexical context. If the declarator has a C++ scope specifier, the
7860 // lexical context will be different from the semantic context.
7861 NewVD->setLexicalDeclContext(CurContext);
7862 if (NewTemplate)
7863 NewTemplate->setLexicalDeclContext(CurContext);
7865 if (IsLocalExternDecl) {
7866 if (D.isDecompositionDeclarator())
7867 for (auto *B : Bindings)
7868 B->setLocalExternDecl();
7869 else
7870 NewVD->setLocalExternDecl();
7873 bool EmitTLSUnsupportedError = false;
7874 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7875 // C++11 [dcl.stc]p4:
7876 // When thread_local is applied to a variable of block scope the
7877 // storage-class-specifier static is implied if it does not appear
7878 // explicitly.
7879 // Core issue: 'static' is not implied if the variable is declared
7880 // 'extern'.
7881 if (NewVD->hasLocalStorage() &&
7882 (SCSpec != DeclSpec::SCS_unspecified ||
7883 TSCS != DeclSpec::TSCS_thread_local ||
7884 !DC->isFunctionOrMethod()))
7885 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7886 diag::err_thread_non_global)
7887 << DeclSpec::getSpecifierName(TSCS);
7888 else if (!Context.getTargetInfo().isTLSSupported()) {
7889 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7890 getLangOpts().SYCLIsDevice) {
7891 // Postpone error emission until we've collected attributes required to
7892 // figure out whether it's a host or device variable and whether the
7893 // error should be ignored.
7894 EmitTLSUnsupportedError = true;
7895 // We still need to mark the variable as TLS so it shows up in AST with
7896 // proper storage class for other tools to use even if we're not going
7897 // to emit any code for it.
7898 NewVD->setTSCSpec(TSCS);
7899 } else
7900 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7901 diag::err_thread_unsupported);
7902 } else
7903 NewVD->setTSCSpec(TSCS);
7906 switch (D.getDeclSpec().getConstexprSpecifier()) {
7907 case ConstexprSpecKind::Unspecified:
7908 break;
7910 case ConstexprSpecKind::Consteval:
7911 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7912 diag::err_constexpr_wrong_decl_kind)
7913 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7914 [[fallthrough]];
7916 case ConstexprSpecKind::Constexpr:
7917 NewVD->setConstexpr(true);
7918 // C++1z [dcl.spec.constexpr]p1:
7919 // A static data member declared with the constexpr specifier is
7920 // implicitly an inline variable.
7921 if (NewVD->isStaticDataMember() &&
7922 (getLangOpts().CPlusPlus17 ||
7923 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7924 NewVD->setImplicitlyInline();
7925 break;
7927 case ConstexprSpecKind::Constinit:
7928 if (!NewVD->hasGlobalStorage())
7929 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7930 diag::err_constinit_local_variable);
7931 else
7932 NewVD->addAttr(
7933 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7934 ConstInitAttr::Keyword_constinit));
7935 break;
7938 // C99 6.7.4p3
7939 // An inline definition of a function with external linkage shall
7940 // not contain a definition of a modifiable object with static or
7941 // thread storage duration...
7942 // We only apply this when the function is required to be defined
7943 // elsewhere, i.e. when the function is not 'extern inline'. Note
7944 // that a local variable with thread storage duration still has to
7945 // be marked 'static'. Also note that it's possible to get these
7946 // semantics in C++ using __attribute__((gnu_inline)).
7947 if (SC == SC_Static && S->getFnParent() != nullptr &&
7948 !NewVD->getType().isConstQualified()) {
7949 FunctionDecl *CurFD = getCurFunctionDecl();
7950 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7951 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7952 diag::warn_static_local_in_extern_inline);
7953 MaybeSuggestAddingStaticToDecl(CurFD);
7957 if (D.getDeclSpec().isModulePrivateSpecified()) {
7958 if (IsVariableTemplateSpecialization)
7959 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7960 << (IsPartialSpecialization ? 1 : 0)
7961 << FixItHint::CreateRemoval(
7962 D.getDeclSpec().getModulePrivateSpecLoc());
7963 else if (IsMemberSpecialization)
7964 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7965 << 2
7966 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7967 else if (NewVD->hasLocalStorage())
7968 Diag(NewVD->getLocation(), diag::err_module_private_local)
7969 << 0 << NewVD
7970 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7971 << FixItHint::CreateRemoval(
7972 D.getDeclSpec().getModulePrivateSpecLoc());
7973 else {
7974 NewVD->setModulePrivate();
7975 if (NewTemplate)
7976 NewTemplate->setModulePrivate();
7977 for (auto *B : Bindings)
7978 B->setModulePrivate();
7982 if (getLangOpts().OpenCL) {
7983 deduceOpenCLAddressSpace(NewVD);
7985 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7986 if (TSC != TSCS_unspecified) {
7987 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7988 diag::err_opencl_unknown_type_specifier)
7989 << getLangOpts().getOpenCLVersionString()
7990 << DeclSpec::getSpecifierName(TSC) << 1;
7991 NewVD->setInvalidDecl();
7995 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7996 // address space if the table has local storage (semantic checks elsewhere
7997 // will produce an error anyway).
7998 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7999 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8000 !NewVD->hasLocalStorage()) {
8001 QualType Type = Context.getAddrSpaceQualType(
8002 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8003 NewVD->setType(Type);
8007 // Handle attributes prior to checking for duplicates in MergeVarDecl
8008 ProcessDeclAttributes(S, NewVD, D);
8010 // FIXME: This is probably the wrong location to be doing this and we should
8011 // probably be doing this for more attributes (especially for function
8012 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8013 // the code to copy attributes would be generated by TableGen.
8014 if (R->isFunctionPointerType())
8015 if (const auto *TT = R->getAs<TypedefType>())
8016 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
8018 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
8019 getLangOpts().SYCLIsDevice) {
8020 if (EmitTLSUnsupportedError &&
8021 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
8022 (getLangOpts().OpenMPIsTargetDevice &&
8023 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8024 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8025 diag::err_thread_unsupported);
8027 if (EmitTLSUnsupportedError &&
8028 (LangOpts.SYCLIsDevice ||
8029 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8030 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8031 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8032 // storage [duration]."
8033 if (SC == SC_None && S->getFnParent() != nullptr &&
8034 (NewVD->hasAttr<CUDASharedAttr>() ||
8035 NewVD->hasAttr<CUDAConstantAttr>())) {
8036 NewVD->setStorageClass(SC_Static);
8040 // Ensure that dllimport globals without explicit storage class are treated as
8041 // extern. The storage class is set above using parsed attributes. Now we can
8042 // check the VarDecl itself.
8043 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8044 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8045 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8047 // In auto-retain/release, infer strong retension for variables of
8048 // retainable type.
8049 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
8050 NewVD->setInvalidDecl();
8052 // Handle GNU asm-label extension (encoded as an attribute).
8053 if (Expr *E = (Expr*)D.getAsmLabel()) {
8054 // The parser guarantees this is a string.
8055 StringLiteral *SE = cast<StringLiteral>(E);
8056 StringRef Label = SE->getString();
8057 if (S->getFnParent() != nullptr) {
8058 switch (SC) {
8059 case SC_None:
8060 case SC_Auto:
8061 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
8062 break;
8063 case SC_Register:
8064 // Local Named register
8065 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
8066 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
8067 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8068 break;
8069 case SC_Static:
8070 case SC_Extern:
8071 case SC_PrivateExtern:
8072 break;
8074 } else if (SC == SC_Register) {
8075 // Global Named register
8076 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
8077 const auto &TI = Context.getTargetInfo();
8078 bool HasSizeMismatch;
8080 if (!TI.isValidGCCRegisterName(Label))
8081 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
8082 else if (!TI.validateGlobalRegisterVariable(Label,
8083 Context.getTypeSize(R),
8084 HasSizeMismatch))
8085 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
8086 else if (HasSizeMismatch)
8087 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8090 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8091 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
8092 NewVD->setInvalidDecl(true);
8096 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8097 /*IsLiteralLabel=*/true,
8098 SE->getStrTokenLoc(0)));
8099 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8100 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8101 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
8102 if (I != ExtnameUndeclaredIdentifiers.end()) {
8103 if (isDeclExternC(NewVD)) {
8104 NewVD->addAttr(I->second);
8105 ExtnameUndeclaredIdentifiers.erase(I);
8106 } else
8107 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8108 << /*Variable*/1 << NewVD;
8112 // Find the shadowed declaration before filtering for scope.
8113 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8114 ? getShadowedDeclaration(NewVD, Previous)
8115 : nullptr;
8117 // Don't consider existing declarations that are in a different
8118 // scope and are out-of-semantic-context declarations (if the new
8119 // declaration has linkage).
8120 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
8121 D.getCXXScopeSpec().isNotEmpty() ||
8122 IsMemberSpecialization ||
8123 IsVariableTemplateSpecialization);
8125 // Check whether the previous declaration is in the same block scope. This
8126 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8127 if (getLangOpts().CPlusPlus &&
8128 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8129 NewVD->setPreviousDeclInSameBlockScope(
8130 Previous.isSingleResult() && !Previous.isShadowed() &&
8131 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8133 if (!getLangOpts().CPlusPlus) {
8134 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8135 } else {
8136 // If this is an explicit specialization of a static data member, check it.
8137 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
8138 CheckMemberSpecialization(NewVD, Previous))
8139 NewVD->setInvalidDecl();
8141 // Merge the decl with the existing one if appropriate.
8142 if (!Previous.empty()) {
8143 if (Previous.isSingleResult() &&
8144 isa<FieldDecl>(Previous.getFoundDecl()) &&
8145 D.getCXXScopeSpec().isSet()) {
8146 // The user tried to define a non-static data member
8147 // out-of-line (C++ [dcl.meaning]p1).
8148 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8149 << D.getCXXScopeSpec().getRange();
8150 Previous.clear();
8151 NewVD->setInvalidDecl();
8153 } else if (D.getCXXScopeSpec().isSet()) {
8154 // No previous declaration in the qualifying scope.
8155 Diag(D.getIdentifierLoc(), diag::err_no_member)
8156 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8157 << D.getCXXScopeSpec().getRange();
8158 NewVD->setInvalidDecl();
8161 if (!IsVariableTemplateSpecialization && !IsPlaceholderVariable)
8162 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8164 // CheckVariableDeclaration will set NewVD as invalid if something is in
8165 // error like WebAssembly tables being declared as arrays with a non-zero
8166 // size, but then parsing continues and emits further errors on that line.
8167 // To avoid that we check here if it happened and return nullptr.
8168 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8169 return nullptr;
8171 if (NewTemplate) {
8172 VarTemplateDecl *PrevVarTemplate =
8173 NewVD->getPreviousDecl()
8174 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
8175 : nullptr;
8177 // Check the template parameter list of this declaration, possibly
8178 // merging in the template parameter list from the previous variable
8179 // template declaration.
8180 if (CheckTemplateParameterList(
8181 TemplateParams,
8182 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8183 : nullptr,
8184 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8185 DC->isDependentContext())
8186 ? TPC_ClassTemplateMember
8187 : TPC_VarTemplate))
8188 NewVD->setInvalidDecl();
8190 // If we are providing an explicit specialization of a static variable
8191 // template, make a note of that.
8192 if (PrevVarTemplate &&
8193 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8194 PrevVarTemplate->setMemberSpecialization();
8198 // Diagnose shadowed variables iff this isn't a redeclaration.
8199 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8200 CheckShadow(NewVD, ShadowedDecl, Previous);
8202 ProcessPragmaWeak(S, NewVD);
8204 // If this is the first declaration of an extern C variable, update
8205 // the map of such variables.
8206 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8207 isIncompleteDeclExternC(*this, NewVD))
8208 RegisterLocallyScopedExternCDecl(NewVD, S);
8210 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8211 MangleNumberingContext *MCtx;
8212 Decl *ManglingContextDecl;
8213 std::tie(MCtx, ManglingContextDecl) =
8214 getCurrentMangleNumberContext(NewVD->getDeclContext());
8215 if (MCtx) {
8216 Context.setManglingNumber(
8217 NewVD, MCtx->getManglingNumber(
8218 NewVD, getMSManglingNumber(getLangOpts(), S)));
8219 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8223 // Special handling of variable named 'main'.
8224 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8225 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8226 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8228 // C++ [basic.start.main]p3
8229 // A program that declares a variable main at global scope is ill-formed.
8230 if (getLangOpts().CPlusPlus)
8231 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8233 // In C, and external-linkage variable named main results in undefined
8234 // behavior.
8235 else if (NewVD->hasExternalFormalLinkage())
8236 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8239 if (D.isRedeclaration() && !Previous.empty()) {
8240 NamedDecl *Prev = Previous.getRepresentativeDecl();
8241 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8242 D.isFunctionDefinition());
8245 if (NewTemplate) {
8246 if (NewVD->isInvalidDecl())
8247 NewTemplate->setInvalidDecl();
8248 ActOnDocumentableDecl(NewTemplate);
8249 return NewTemplate;
8252 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8253 CompleteMemberSpecialization(NewVD, Previous);
8255 emitReadOnlyPlacementAttrWarning(*this, NewVD);
8257 return NewVD;
8260 /// Enum describing the %select options in diag::warn_decl_shadow.
8261 enum ShadowedDeclKind {
8262 SDK_Local,
8263 SDK_Global,
8264 SDK_StaticMember,
8265 SDK_Field,
8266 SDK_Typedef,
8267 SDK_Using,
8268 SDK_StructuredBinding
8271 /// Determine what kind of declaration we're shadowing.
8272 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
8273 const DeclContext *OldDC) {
8274 if (isa<TypeAliasDecl>(ShadowedDecl))
8275 return SDK_Using;
8276 else if (isa<TypedefDecl>(ShadowedDecl))
8277 return SDK_Typedef;
8278 else if (isa<BindingDecl>(ShadowedDecl))
8279 return SDK_StructuredBinding;
8280 else if (isa<RecordDecl>(OldDC))
8281 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8283 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8286 /// Return the location of the capture if the given lambda captures the given
8287 /// variable \p VD, or an invalid source location otherwise.
8288 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
8289 const VarDecl *VD) {
8290 for (const Capture &Capture : LSI->Captures) {
8291 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
8292 return Capture.getLocation();
8294 return SourceLocation();
8297 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
8298 const LookupResult &R) {
8299 // Only diagnose if we're shadowing an unambiguous field or variable.
8300 if (R.getResultKind() != LookupResult::Found)
8301 return false;
8303 // Return false if warning is ignored.
8304 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8307 /// Return the declaration shadowed by the given variable \p D, or null
8308 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8309 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
8310 const LookupResult &R) {
8311 if (!shouldWarnIfShadowedDecl(Diags, R))
8312 return nullptr;
8314 // Don't diagnose declarations at file scope.
8315 if (D->hasGlobalStorage() && !D->isStaticLocal())
8316 return nullptr;
8318 NamedDecl *ShadowedDecl = R.getFoundDecl();
8319 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8320 : nullptr;
8323 /// Return the declaration shadowed by the given typedef \p D, or null
8324 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8325 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
8326 const LookupResult &R) {
8327 // Don't warn if typedef declaration is part of a class
8328 if (D->getDeclContext()->isRecord())
8329 return nullptr;
8331 if (!shouldWarnIfShadowedDecl(Diags, R))
8332 return nullptr;
8334 NamedDecl *ShadowedDecl = R.getFoundDecl();
8335 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8338 /// Return the declaration shadowed by the given variable \p D, or null
8339 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
8340 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
8341 const LookupResult &R) {
8342 if (!shouldWarnIfShadowedDecl(Diags, R))
8343 return nullptr;
8345 NamedDecl *ShadowedDecl = R.getFoundDecl();
8346 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8347 : nullptr;
8350 /// Diagnose variable or built-in function shadowing. Implements
8351 /// -Wshadow.
8353 /// This method is called whenever a VarDecl is added to a "useful"
8354 /// scope.
8356 /// \param ShadowedDecl the declaration that is shadowed by the given variable
8357 /// \param R the lookup of the name
8359 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
8360 const LookupResult &R) {
8361 DeclContext *NewDC = D->getDeclContext();
8363 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8364 // Fields are not shadowed by variables in C++ static methods.
8365 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8366 if (MD->isStatic())
8367 return;
8369 // Fields shadowed by constructor parameters are a special case. Usually
8370 // the constructor initializes the field with the parameter.
8371 if (isa<CXXConstructorDecl>(NewDC))
8372 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8373 // Remember that this was shadowed so we can either warn about its
8374 // modification or its existence depending on warning settings.
8375 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8376 return;
8380 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8381 if (shadowedVar->isExternC()) {
8382 // For shadowing external vars, make sure that we point to the global
8383 // declaration, not a locally scoped extern declaration.
8384 for (auto *I : shadowedVar->redecls())
8385 if (I->isFileVarDecl()) {
8386 ShadowedDecl = I;
8387 break;
8391 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8393 unsigned WarningDiag = diag::warn_decl_shadow;
8394 SourceLocation CaptureLoc;
8395 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
8396 isa<CXXMethodDecl>(NewDC)) {
8397 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8398 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8399 if (RD->getLambdaCaptureDefault() == LCD_None) {
8400 // Try to avoid warnings for lambdas with an explicit capture list.
8401 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8402 // Warn only when the lambda captures the shadowed decl explicitly.
8403 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
8404 if (CaptureLoc.isInvalid())
8405 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8406 } else {
8407 // Remember that this was shadowed so we can avoid the warning if the
8408 // shadowed decl isn't captured and the warning settings allow it.
8409 cast<LambdaScopeInfo>(getCurFunction())
8410 ->ShadowingDecls.push_back(
8411 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
8412 return;
8416 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
8417 // A variable can't shadow a local variable in an enclosing scope, if
8418 // they are separated by a non-capturing declaration context.
8419 for (DeclContext *ParentDC = NewDC;
8420 ParentDC && !ParentDC->Equals(OldDC);
8421 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8422 // Only block literals, captured statements, and lambda expressions
8423 // can capture; other scopes don't.
8424 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8425 !isLambdaCallOperator(ParentDC)) {
8426 return;
8433 // Never warn about shadowing a placeholder variable.
8434 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8435 return;
8437 // Only warn about certain kinds of shadowing for class members.
8438 if (NewDC && NewDC->isRecord()) {
8439 // In particular, don't warn about shadowing non-class members.
8440 if (!OldDC->isRecord())
8441 return;
8443 // TODO: should we warn about static data members shadowing
8444 // static data members from base classes?
8446 // TODO: don't diagnose for inaccessible shadowed members.
8447 // This is hard to do perfectly because we might friend the
8448 // shadowing context, but that's just a false negative.
8452 DeclarationName Name = R.getLookupName();
8454 // Emit warning and note.
8455 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8456 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8457 if (!CaptureLoc.isInvalid())
8458 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8459 << Name << /*explicitly*/ 1;
8460 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8463 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
8464 /// when these variables are captured by the lambda.
8465 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
8466 for (const auto &Shadow : LSI->ShadowingDecls) {
8467 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
8468 // Try to avoid the warning when the shadowed decl isn't captured.
8469 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
8470 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8471 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
8472 ? diag::warn_decl_shadow_uncaptured_local
8473 : diag::warn_decl_shadow)
8474 << Shadow.VD->getDeclName()
8475 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8476 if (!CaptureLoc.isInvalid())
8477 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8478 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8479 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8483 /// Check -Wshadow without the advantage of a previous lookup.
8484 void Sema::CheckShadow(Scope *S, VarDecl *D) {
8485 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8486 return;
8488 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8489 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
8490 LookupName(R, S);
8491 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8492 CheckShadow(D, ShadowedDecl, R);
8495 /// Check if 'E', which is an expression that is about to be modified, refers
8496 /// to a constructor parameter that shadows a field.
8497 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
8498 // Quickly ignore expressions that can't be shadowing ctor parameters.
8499 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8500 return;
8501 E = E->IgnoreParenImpCasts();
8502 auto *DRE = dyn_cast<DeclRefExpr>(E);
8503 if (!DRE)
8504 return;
8505 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8506 auto I = ShadowingDecls.find(D);
8507 if (I == ShadowingDecls.end())
8508 return;
8509 const NamedDecl *ShadowedDecl = I->second;
8510 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8511 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8512 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8513 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8515 // Avoid issuing multiple warnings about the same decl.
8516 ShadowingDecls.erase(I);
8519 /// Check for conflict between this global or extern "C" declaration and
8520 /// previous global or extern "C" declarations. This is only used in C++.
8521 template<typename T>
8522 static bool checkGlobalOrExternCConflict(
8523 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8524 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8525 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8527 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8528 // The common case: this global doesn't conflict with any extern "C"
8529 // declaration.
8530 return false;
8533 if (Prev) {
8534 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8535 // Both the old and new declarations have C language linkage. This is a
8536 // redeclaration.
8537 Previous.clear();
8538 Previous.addDecl(Prev);
8539 return true;
8542 // This is a global, non-extern "C" declaration, and there is a previous
8543 // non-global extern "C" declaration. Diagnose if this is a variable
8544 // declaration.
8545 if (!isa<VarDecl>(ND))
8546 return false;
8547 } else {
8548 // The declaration is extern "C". Check for any declaration in the
8549 // translation unit which might conflict.
8550 if (IsGlobal) {
8551 // We have already performed the lookup into the translation unit.
8552 IsGlobal = false;
8553 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8554 I != E; ++I) {
8555 if (isa<VarDecl>(*I)) {
8556 Prev = *I;
8557 break;
8560 } else {
8561 DeclContext::lookup_result R =
8562 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8563 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8564 I != E; ++I) {
8565 if (isa<VarDecl>(*I)) {
8566 Prev = *I;
8567 break;
8569 // FIXME: If we have any other entity with this name in global scope,
8570 // the declaration is ill-formed, but that is a defect: it breaks the
8571 // 'stat' hack, for instance. Only variables can have mangled name
8572 // clashes with extern "C" declarations, so only they deserve a
8573 // diagnostic.
8577 if (!Prev)
8578 return false;
8581 // Use the first declaration's location to ensure we point at something which
8582 // is lexically inside an extern "C" linkage-spec.
8583 assert(Prev && "should have found a previous declaration to diagnose");
8584 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8585 Prev = FD->getFirstDecl();
8586 else
8587 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8589 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8590 << IsGlobal << ND;
8591 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8592 << IsGlobal;
8593 return false;
8596 /// Apply special rules for handling extern "C" declarations. Returns \c true
8597 /// if we have found that this is a redeclaration of some prior entity.
8599 /// Per C++ [dcl.link]p6:
8600 /// Two declarations [for a function or variable] with C language linkage
8601 /// with the same name that appear in different scopes refer to the same
8602 /// [entity]. An entity with C language linkage shall not be declared with
8603 /// the same name as an entity in global scope.
8604 template<typename T>
8605 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8606 LookupResult &Previous) {
8607 if (!S.getLangOpts().CPlusPlus) {
8608 // In C, when declaring a global variable, look for a corresponding 'extern'
8609 // variable declared in function scope. We don't need this in C++, because
8610 // we find local extern decls in the surrounding file-scope DeclContext.
8611 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8612 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8613 Previous.clear();
8614 Previous.addDecl(Prev);
8615 return true;
8618 return false;
8621 // A declaration in the translation unit can conflict with an extern "C"
8622 // declaration.
8623 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8624 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8626 // An extern "C" declaration can conflict with a declaration in the
8627 // translation unit or can be a redeclaration of an extern "C" declaration
8628 // in another scope.
8629 if (isIncompleteDeclExternC(S,ND))
8630 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8632 // Neither global nor extern "C": nothing to do.
8633 return false;
8636 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
8637 // If the decl is already known invalid, don't check it.
8638 if (NewVD->isInvalidDecl())
8639 return;
8641 QualType T = NewVD->getType();
8643 // Defer checking an 'auto' type until its initializer is attached.
8644 if (T->isUndeducedType())
8645 return;
8647 if (NewVD->hasAttrs())
8648 CheckAlignasUnderalignment(NewVD);
8650 if (T->isObjCObjectType()) {
8651 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8652 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8653 T = Context.getObjCObjectPointerType(T);
8654 NewVD->setType(T);
8657 // Emit an error if an address space was applied to decl with local storage.
8658 // This includes arrays of objects with address space qualifiers, but not
8659 // automatic variables that point to other address spaces.
8660 // ISO/IEC TR 18037 S5.1.2
8661 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8662 T.getAddressSpace() != LangAS::Default) {
8663 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8664 NewVD->setInvalidDecl();
8665 return;
8668 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8669 // scope.
8670 if (getLangOpts().OpenCLVersion == 120 &&
8671 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8672 getLangOpts()) &&
8673 NewVD->isStaticLocal()) {
8674 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8675 NewVD->setInvalidDecl();
8676 return;
8679 if (getLangOpts().OpenCL) {
8680 if (!diagnoseOpenCLTypes(*this, NewVD))
8681 return;
8683 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8684 if (NewVD->hasAttr<BlocksAttr>()) {
8685 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8686 return;
8689 if (T->isBlockPointerType()) {
8690 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8691 // can't use 'extern' storage class.
8692 if (!T.isConstQualified()) {
8693 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8694 << 0 /*const*/;
8695 NewVD->setInvalidDecl();
8696 return;
8698 if (NewVD->hasExternalStorage()) {
8699 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8700 NewVD->setInvalidDecl();
8701 return;
8705 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8706 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8707 NewVD->hasExternalStorage()) {
8708 if (!T->isSamplerT() && !T->isDependentType() &&
8709 !(T.getAddressSpace() == LangAS::opencl_constant ||
8710 (T.getAddressSpace() == LangAS::opencl_global &&
8711 getOpenCLOptions().areProgramScopeVariablesSupported(
8712 getLangOpts())))) {
8713 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8714 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8715 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8716 << Scope << "global or constant";
8717 else
8718 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8719 << Scope << "constant";
8720 NewVD->setInvalidDecl();
8721 return;
8723 } else {
8724 if (T.getAddressSpace() == LangAS::opencl_global) {
8725 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8726 << 1 /*is any function*/ << "global";
8727 NewVD->setInvalidDecl();
8728 return;
8730 if (T.getAddressSpace() == LangAS::opencl_constant ||
8731 T.getAddressSpace() == LangAS::opencl_local) {
8732 FunctionDecl *FD = getCurFunctionDecl();
8733 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8734 // in functions.
8735 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8736 if (T.getAddressSpace() == LangAS::opencl_constant)
8737 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8738 << 0 /*non-kernel only*/ << "constant";
8739 else
8740 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8741 << 0 /*non-kernel only*/ << "local";
8742 NewVD->setInvalidDecl();
8743 return;
8745 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8746 // in the outermost scope of a kernel function.
8747 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8748 if (!getCurScope()->isFunctionScope()) {
8749 if (T.getAddressSpace() == LangAS::opencl_constant)
8750 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8751 << "constant";
8752 else
8753 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8754 << "local";
8755 NewVD->setInvalidDecl();
8756 return;
8759 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8760 // If we are parsing a template we didn't deduce an addr
8761 // space yet.
8762 T.getAddressSpace() != LangAS::Default) {
8763 // Do not allow other address spaces on automatic variable.
8764 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8765 NewVD->setInvalidDecl();
8766 return;
8771 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8772 && !NewVD->hasAttr<BlocksAttr>()) {
8773 if (getLangOpts().getGC() != LangOptions::NonGC)
8774 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8775 else {
8776 assert(!getLangOpts().ObjCAutoRefCount);
8777 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8781 // WebAssembly tables must be static with a zero length and can't be
8782 // declared within functions.
8783 if (T->isWebAssemblyTableType()) {
8784 if (getCurScope()->getParent()) { // Parent is null at top-level
8785 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8786 NewVD->setInvalidDecl();
8787 return;
8789 if (NewVD->getStorageClass() != SC_Static) {
8790 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8791 NewVD->setInvalidDecl();
8792 return;
8794 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8795 if (!ATy || ATy->getSize().getSExtValue() != 0) {
8796 Diag(NewVD->getLocation(),
8797 diag::err_typecheck_wasm_table_must_have_zero_length);
8798 NewVD->setInvalidDecl();
8799 return;
8803 bool isVM = T->isVariablyModifiedType();
8804 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8805 NewVD->hasAttr<BlocksAttr>())
8806 setFunctionHasBranchProtectedScope();
8808 if ((isVM && NewVD->hasLinkage()) ||
8809 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8810 bool SizeIsNegative;
8811 llvm::APSInt Oversized;
8812 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8813 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8814 QualType FixedT;
8815 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8816 FixedT = FixedTInfo->getType();
8817 else if (FixedTInfo) {
8818 // Type and type-as-written are canonically different. We need to fix up
8819 // both types separately.
8820 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8821 Oversized);
8823 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8824 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8825 // FIXME: This won't give the correct result for
8826 // int a[10][n];
8827 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8829 if (NewVD->isFileVarDecl())
8830 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8831 << SizeRange;
8832 else if (NewVD->isStaticLocal())
8833 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8834 << SizeRange;
8835 else
8836 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8837 << SizeRange;
8838 NewVD->setInvalidDecl();
8839 return;
8842 if (!FixedTInfo) {
8843 if (NewVD->isFileVarDecl())
8844 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8845 else
8846 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8847 NewVD->setInvalidDecl();
8848 return;
8851 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8852 NewVD->setType(FixedT);
8853 NewVD->setTypeSourceInfo(FixedTInfo);
8856 if (T->isVoidType()) {
8857 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8858 // of objects and functions.
8859 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8860 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8861 << T;
8862 NewVD->setInvalidDecl();
8863 return;
8867 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8868 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8869 NewVD->setInvalidDecl();
8870 return;
8873 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8874 !T.isWebAssemblyReferenceType()) {
8875 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8876 NewVD->setInvalidDecl();
8877 return;
8880 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8881 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8882 NewVD->setInvalidDecl();
8883 return;
8886 if (NewVD->isConstexpr() && !T->isDependentType() &&
8887 RequireLiteralType(NewVD->getLocation(), T,
8888 diag::err_constexpr_var_non_literal)) {
8889 NewVD->setInvalidDecl();
8890 return;
8893 // PPC MMA non-pointer types are not allowed as non-local variable types.
8894 if (Context.getTargetInfo().getTriple().isPPC64() &&
8895 !NewVD->isLocalVarDecl() &&
8896 CheckPPCMMAType(T, NewVD->getLocation())) {
8897 NewVD->setInvalidDecl();
8898 return;
8901 // Check that SVE types are only used in functions with SVE available.
8902 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8903 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8904 llvm::StringMap<bool> CallerFeatureMap;
8905 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8906 if (!Builtin::evaluateRequiredTargetFeatures(
8907 "sve", CallerFeatureMap)) {
8908 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8909 NewVD->setInvalidDecl();
8910 return;
8914 if (T->isRVVSizelessBuiltinType())
8915 checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext));
8918 /// Perform semantic checking on a newly-created variable
8919 /// declaration.
8921 /// This routine performs all of the type-checking required for a
8922 /// variable declaration once it has been built. It is used both to
8923 /// check variables after they have been parsed and their declarators
8924 /// have been translated into a declaration, and to check variables
8925 /// that have been instantiated from a template.
8927 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8929 /// Returns true if the variable declaration is a redeclaration.
8930 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8931 CheckVariableDeclarationType(NewVD);
8933 // If the decl is already known invalid, don't check it.
8934 if (NewVD->isInvalidDecl())
8935 return false;
8937 // If we did not find anything by this name, look for a non-visible
8938 // extern "C" declaration with the same name.
8939 if (Previous.empty() &&
8940 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8941 Previous.setShadowed();
8943 if (!Previous.empty()) {
8944 MergeVarDecl(NewVD, Previous);
8945 return true;
8947 return false;
8950 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8951 /// and if so, check that it's a valid override and remember it.
8952 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8953 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8955 // Look for methods in base classes that this method might override.
8956 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8957 /*DetectVirtual=*/false);
8958 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8959 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8960 DeclarationName Name = MD->getDeclName();
8962 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8963 // We really want to find the base class destructor here.
8964 QualType T = Context.getTypeDeclType(BaseRecord);
8965 CanQualType CT = Context.getCanonicalType(T);
8966 Name = Context.DeclarationNames.getCXXDestructorName(CT);
8969 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8970 CXXMethodDecl *BaseMD =
8971 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8972 if (!BaseMD || !BaseMD->isVirtual() ||
8973 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8974 /*ConsiderCudaAttrs=*/true))
8975 continue;
8976 if (!CheckExplicitObjectOverride(MD, BaseMD))
8977 continue;
8978 if (Overridden.insert(BaseMD).second) {
8979 MD->addOverriddenMethod(BaseMD);
8980 CheckOverridingFunctionReturnType(MD, BaseMD);
8981 CheckOverridingFunctionAttributes(MD, BaseMD);
8982 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8983 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8986 // A method can only override one function from each base class. We
8987 // don't track indirectly overridden methods from bases of bases.
8988 return true;
8991 return false;
8994 DC->lookupInBases(VisitBase, Paths);
8995 return !Overridden.empty();
8998 namespace {
8999 // Struct for holding all of the extra arguments needed by
9000 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9001 struct ActOnFDArgs {
9002 Scope *S;
9003 Declarator &D;
9004 MultiTemplateParamsArg TemplateParamLists;
9005 bool AddToScope;
9007 } // end anonymous namespace
9009 namespace {
9011 // Callback to only accept typo corrections that have a non-zero edit distance.
9012 // Also only accept corrections that have the same parent decl.
9013 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9014 public:
9015 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9016 CXXRecordDecl *Parent)
9017 : Context(Context), OriginalFD(TypoFD),
9018 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9020 bool ValidateCandidate(const TypoCorrection &candidate) override {
9021 if (candidate.getEditDistance() == 0)
9022 return false;
9024 SmallVector<unsigned, 1> MismatchedParams;
9025 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9026 CDeclEnd = candidate.end();
9027 CDecl != CDeclEnd; ++CDecl) {
9028 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9030 if (FD && !FD->hasBody() &&
9031 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9032 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9033 CXXRecordDecl *Parent = MD->getParent();
9034 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9035 return true;
9036 } else if (!ExpectedParent) {
9037 return true;
9042 return false;
9045 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9046 return std::make_unique<DifferentNameValidatorCCC>(*this);
9049 private:
9050 ASTContext &Context;
9051 FunctionDecl *OriginalFD;
9052 CXXRecordDecl *ExpectedParent;
9055 } // end anonymous namespace
9057 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
9058 TypoCorrectedFunctionDefinitions.insert(F);
9061 /// Generate diagnostics for an invalid function redeclaration.
9063 /// This routine handles generating the diagnostic messages for an invalid
9064 /// function redeclaration, including finding possible similar declarations
9065 /// or performing typo correction if there are no previous declarations with
9066 /// the same name.
9068 /// Returns a NamedDecl iff typo correction was performed and substituting in
9069 /// the new declaration name does not cause new errors.
9070 static NamedDecl *DiagnoseInvalidRedeclaration(
9071 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9072 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9073 DeclarationName Name = NewFD->getDeclName();
9074 DeclContext *NewDC = NewFD->getDeclContext();
9075 SmallVector<unsigned, 1> MismatchedParams;
9076 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
9077 TypoCorrection Correction;
9078 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9079 unsigned DiagMsg =
9080 IsLocalFriend ? diag::err_no_matching_local_friend :
9081 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9082 diag::err_member_decl_does_not_match;
9083 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9084 IsLocalFriend ? Sema::LookupLocalFriendName
9085 : Sema::LookupOrdinaryName,
9086 Sema::ForVisibleRedeclaration);
9088 NewFD->setInvalidDecl();
9089 if (IsLocalFriend)
9090 SemaRef.LookupName(Prev, S);
9091 else
9092 SemaRef.LookupQualifiedName(Prev, NewDC);
9093 assert(!Prev.isAmbiguous() &&
9094 "Cannot have an ambiguity in previous-declaration lookup");
9095 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9096 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9097 MD ? MD->getParent() : nullptr);
9098 if (!Prev.empty()) {
9099 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9100 Func != FuncEnd; ++Func) {
9101 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9102 if (FD &&
9103 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9104 // Add 1 to the index so that 0 can mean the mismatch didn't
9105 // involve a parameter
9106 unsigned ParamNum =
9107 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9108 NearMatches.push_back(std::make_pair(FD, ParamNum));
9111 // If the qualified name lookup yielded nothing, try typo correction
9112 } else if ((Correction = SemaRef.CorrectTypo(
9113 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9114 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9115 IsLocalFriend ? nullptr : NewDC))) {
9116 // Set up everything for the call to ActOnFunctionDeclarator
9117 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9118 ExtraArgs.D.getIdentifierLoc());
9119 Previous.clear();
9120 Previous.setLookupName(Correction.getCorrection());
9121 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9122 CDeclEnd = Correction.end();
9123 CDecl != CDeclEnd; ++CDecl) {
9124 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9125 if (FD && !FD->hasBody() &&
9126 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9127 Previous.addDecl(FD);
9130 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9132 NamedDecl *Result;
9133 // Retry building the function declaration with the new previous
9134 // declarations, and with errors suppressed.
9136 // Trap errors.
9137 Sema::SFINAETrap Trap(SemaRef);
9139 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9140 // pieces need to verify the typo-corrected C++ declaration and hopefully
9141 // eliminate the need for the parameter pack ExtraArgs.
9142 Result = SemaRef.ActOnFunctionDeclarator(
9143 ExtraArgs.S, ExtraArgs.D,
9144 Correction.getCorrectionDecl()->getDeclContext(),
9145 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9146 ExtraArgs.AddToScope);
9148 if (Trap.hasErrorOccurred())
9149 Result = nullptr;
9152 if (Result) {
9153 // Determine which correction we picked.
9154 Decl *Canonical = Result->getCanonicalDecl();
9155 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9156 I != E; ++I)
9157 if ((*I)->getCanonicalDecl() == Canonical)
9158 Correction.setCorrectionDecl(*I);
9160 // Let Sema know about the correction.
9161 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
9162 SemaRef.diagnoseTypo(
9163 Correction,
9164 SemaRef.PDiag(IsLocalFriend
9165 ? diag::err_no_matching_local_friend_suggest
9166 : diag::err_member_decl_does_not_match_suggest)
9167 << Name << NewDC << IsDefinition);
9168 return Result;
9171 // Pretend the typo correction never occurred
9172 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9173 ExtraArgs.D.getIdentifierLoc());
9174 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9175 Previous.clear();
9176 Previous.setLookupName(Name);
9179 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9180 << Name << NewDC << IsDefinition << NewFD->getLocation();
9182 bool NewFDisConst = false;
9183 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9184 NewFDisConst = NewMD->isConst();
9186 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9187 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9188 NearMatch != NearMatchEnd; ++NearMatch) {
9189 FunctionDecl *FD = NearMatch->first;
9190 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9191 bool FDisConst = MD && MD->isConst();
9192 bool IsMember = MD || !IsLocalFriend;
9194 // FIXME: These notes are poorly worded for the local friend case.
9195 if (unsigned Idx = NearMatch->second) {
9196 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9197 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9198 if (Loc.isInvalid()) Loc = FD->getLocation();
9199 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9200 : diag::note_local_decl_close_param_match)
9201 << Idx << FDParam->getType()
9202 << NewFD->getParamDecl(Idx - 1)->getType();
9203 } else if (FDisConst != NewFDisConst) {
9204 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
9205 << NewFDisConst << FD->getSourceRange().getEnd()
9206 << (NewFDisConst
9207 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
9208 .getConstQualifierLoc())
9209 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
9210 .getRParenLoc()
9211 .getLocWithOffset(1),
9212 " const"));
9213 } else
9214 SemaRef.Diag(FD->getLocation(),
9215 IsMember ? diag::note_member_def_close_match
9216 : diag::note_local_decl_close_match);
9218 return nullptr;
9221 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
9222 switch (D.getDeclSpec().getStorageClassSpec()) {
9223 default: llvm_unreachable("Unknown storage class!");
9224 case DeclSpec::SCS_auto:
9225 case DeclSpec::SCS_register:
9226 case DeclSpec::SCS_mutable:
9227 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9228 diag::err_typecheck_sclass_func);
9229 D.getMutableDeclSpec().ClearStorageClassSpecs();
9230 D.setInvalidType();
9231 break;
9232 case DeclSpec::SCS_unspecified: break;
9233 case DeclSpec::SCS_extern:
9234 if (D.getDeclSpec().isExternInLinkageSpec())
9235 return SC_None;
9236 return SC_Extern;
9237 case DeclSpec::SCS_static: {
9238 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9239 // C99 6.7.1p5:
9240 // The declaration of an identifier for a function that has
9241 // block scope shall have no explicit storage-class specifier
9242 // other than extern
9243 // See also (C++ [dcl.stc]p4).
9244 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9245 diag::err_static_block_func);
9246 break;
9247 } else
9248 return SC_Static;
9250 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
9253 // No explicit storage class has already been returned
9254 return SC_None;
9257 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
9258 DeclContext *DC, QualType &R,
9259 TypeSourceInfo *TInfo,
9260 StorageClass SC,
9261 bool &IsVirtualOkay) {
9262 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9263 DeclarationName Name = NameInfo.getName();
9265 FunctionDecl *NewFD = nullptr;
9266 bool isInline = D.getDeclSpec().isInlineSpecified();
9268 if (!SemaRef.getLangOpts().CPlusPlus) {
9269 // Determine whether the function was written with a prototype. This is
9270 // true when:
9271 // - there is a prototype in the declarator, or
9272 // - the type R of the function is some kind of typedef or other non-
9273 // attributed reference to a type name (which eventually refers to a
9274 // function type). Note, we can't always look at the adjusted type to
9275 // check this case because attributes may cause a non-function
9276 // declarator to still have a function type. e.g.,
9277 // typedef void func(int a);
9278 // __attribute__((noreturn)) func other_func; // This has a prototype
9279 bool HasPrototype =
9280 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9281 (D.getDeclSpec().isTypeRep() &&
9282 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9283 ->isFunctionProtoType()) ||
9284 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9285 assert(
9286 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9287 "Strict prototypes are required");
9289 NewFD = FunctionDecl::Create(
9290 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9291 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9292 ConstexprSpecKind::Unspecified,
9293 /*TrailingRequiresClause=*/nullptr);
9294 if (D.isInvalidType())
9295 NewFD->setInvalidDecl();
9297 return NewFD;
9300 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9302 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9303 if (ConstexprKind == ConstexprSpecKind::Constinit) {
9304 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9305 diag::err_constexpr_wrong_decl_kind)
9306 << static_cast<int>(ConstexprKind);
9307 ConstexprKind = ConstexprSpecKind::Unspecified;
9308 D.getMutableDeclSpec().ClearConstexprSpec();
9310 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9312 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9314 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9315 // This is a C++ constructor declaration.
9316 assert(DC->isRecord() &&
9317 "Constructors can only be declared in a member context");
9319 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9320 return CXXConstructorDecl::Create(
9321 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9322 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
9323 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9324 InheritedConstructor(), TrailingRequiresClause);
9326 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9327 // This is a C++ destructor declaration.
9328 if (DC->isRecord()) {
9329 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9330 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9331 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
9332 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9333 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9334 /*isImplicitlyDeclared=*/false, ConstexprKind,
9335 TrailingRequiresClause);
9336 // User defined destructors start as not selected if the class definition is still
9337 // not done.
9338 if (Record->isBeingDefined())
9339 NewDD->setIneligibleOrNotSelected(true);
9341 // If the destructor needs an implicit exception specification, set it
9342 // now. FIXME: It'd be nice to be able to create the right type to start
9343 // with, but the type needs to reference the destructor declaration.
9344 if (SemaRef.getLangOpts().CPlusPlus11)
9345 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9347 IsVirtualOkay = true;
9348 return NewDD;
9350 } else {
9351 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9352 D.setInvalidType();
9354 // Create a FunctionDecl to satisfy the function definition parsing
9355 // code path.
9356 return FunctionDecl::Create(
9357 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9358 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9359 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9362 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9363 if (!DC->isRecord()) {
9364 SemaRef.Diag(D.getIdentifierLoc(),
9365 diag::err_conv_function_not_member);
9366 return nullptr;
9369 SemaRef.CheckConversionDeclarator(D, R, SC);
9370 if (D.isInvalidType())
9371 return nullptr;
9373 IsVirtualOkay = true;
9374 return CXXConversionDecl::Create(
9375 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9376 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9377 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9378 TrailingRequiresClause);
9380 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9381 if (TrailingRequiresClause)
9382 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9383 diag::err_trailing_requires_clause_on_deduction_guide)
9384 << TrailingRequiresClause->getSourceRange();
9385 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9386 return nullptr;
9387 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9388 ExplicitSpecifier, NameInfo, R, TInfo,
9389 D.getEndLoc());
9390 } else if (DC->isRecord()) {
9391 // If the name of the function is the same as the name of the record,
9392 // then this must be an invalid constructor that has a return type.
9393 // (The parser checks for a return type and makes the declarator a
9394 // constructor if it has no return type).
9395 if (Name.getAsIdentifierInfo() &&
9396 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9397 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9398 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9399 << SourceRange(D.getIdentifierLoc());
9400 return nullptr;
9403 // This is a C++ method declaration.
9404 CXXMethodDecl *Ret = CXXMethodDecl::Create(
9405 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9406 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9407 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9408 IsVirtualOkay = !Ret->isStatic();
9409 return Ret;
9410 } else {
9411 bool isFriend =
9412 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9413 if (!isFriend && SemaRef.CurContext->isRecord())
9414 return nullptr;
9416 // Determine whether the function was written with a
9417 // prototype. This true when:
9418 // - we're in C++ (where every function has a prototype),
9419 return FunctionDecl::Create(
9420 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9421 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9422 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9426 enum OpenCLParamType {
9427 ValidKernelParam,
9428 PtrPtrKernelParam,
9429 PtrKernelParam,
9430 InvalidAddrSpacePtrKernelParam,
9431 InvalidKernelParam,
9432 RecordKernelParam
9435 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
9436 // Size dependent types are just typedefs to normal integer types
9437 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9438 // integers other than by their names.
9439 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9441 // Remove typedefs one by one until we reach a typedef
9442 // for a size dependent type.
9443 QualType DesugaredTy = Ty;
9444 do {
9445 ArrayRef<StringRef> Names(SizeTypeNames);
9446 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9447 if (Names.end() != Match)
9448 return true;
9450 Ty = DesugaredTy;
9451 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9452 } while (DesugaredTy != Ty);
9454 return false;
9457 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
9458 if (PT->isDependentType())
9459 return InvalidKernelParam;
9461 if (PT->isPointerType() || PT->isReferenceType()) {
9462 QualType PointeeType = PT->getPointeeType();
9463 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9464 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9465 PointeeType.getAddressSpace() == LangAS::Default)
9466 return InvalidAddrSpacePtrKernelParam;
9468 if (PointeeType->isPointerType()) {
9469 // This is a pointer to pointer parameter.
9470 // Recursively check inner type.
9471 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9472 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9473 ParamKind == InvalidKernelParam)
9474 return ParamKind;
9476 // OpenCL v3.0 s6.11.a:
9477 // A restriction to pass pointers to pointers only applies to OpenCL C
9478 // v1.2 or below.
9479 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9480 return ValidKernelParam;
9482 return PtrPtrKernelParam;
9485 // C++ for OpenCL v1.0 s2.4:
9486 // Moreover the types used in parameters of the kernel functions must be:
9487 // Standard layout types for pointer parameters. The same applies to
9488 // reference if an implementation supports them in kernel parameters.
9489 if (S.getLangOpts().OpenCLCPlusPlus &&
9490 !S.getOpenCLOptions().isAvailableOption(
9491 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9492 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9493 bool IsStandardLayoutType = true;
9494 if (CXXRec) {
9495 // If template type is not ODR-used its definition is only available
9496 // in the template definition not its instantiation.
9497 // FIXME: This logic doesn't work for types that depend on template
9498 // parameter (PR58590).
9499 if (!CXXRec->hasDefinition())
9500 CXXRec = CXXRec->getTemplateInstantiationPattern();
9501 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9502 IsStandardLayoutType = false;
9504 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9505 !IsStandardLayoutType)
9506 return InvalidKernelParam;
9509 // OpenCL v1.2 s6.9.p:
9510 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9511 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
9512 return ValidKernelParam;
9514 return PtrKernelParam;
9517 // OpenCL v1.2 s6.9.k:
9518 // Arguments to kernel functions in a program cannot be declared with the
9519 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9520 // uintptr_t or a struct and/or union that contain fields declared to be one
9521 // of these built-in scalar types.
9522 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
9523 return InvalidKernelParam;
9525 if (PT->isImageType())
9526 return PtrKernelParam;
9528 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9529 return InvalidKernelParam;
9531 // OpenCL extension spec v1.2 s9.5:
9532 // This extension adds support for half scalar and vector types as built-in
9533 // types that can be used for arithmetic operations, conversions etc.
9534 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9535 PT->isHalfType())
9536 return InvalidKernelParam;
9538 // Look into an array argument to check if it has a forbidden type.
9539 if (PT->isArrayType()) {
9540 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9541 // Call ourself to check an underlying type of an array. Since the
9542 // getPointeeOrArrayElementType returns an innermost type which is not an
9543 // array, this recursive call only happens once.
9544 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9547 // C++ for OpenCL v1.0 s2.4:
9548 // Moreover the types used in parameters of the kernel functions must be:
9549 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9550 // types) for parameters passed by value;
9551 if (S.getLangOpts().OpenCLCPlusPlus &&
9552 !S.getOpenCLOptions().isAvailableOption(
9553 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9554 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9555 return InvalidKernelParam;
9557 if (PT->isRecordType())
9558 return RecordKernelParam;
9560 return ValidKernelParam;
9563 static void checkIsValidOpenCLKernelParameter(
9564 Sema &S,
9565 Declarator &D,
9566 ParmVarDecl *Param,
9567 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9568 QualType PT = Param->getType();
9570 // Cache the valid types we encounter to avoid rechecking structs that are
9571 // used again
9572 if (ValidTypes.count(PT.getTypePtr()))
9573 return;
9575 switch (getOpenCLKernelParameterType(S, PT)) {
9576 case PtrPtrKernelParam:
9577 // OpenCL v3.0 s6.11.a:
9578 // A kernel function argument cannot be declared as a pointer to a pointer
9579 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9580 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9581 D.setInvalidType();
9582 return;
9584 case InvalidAddrSpacePtrKernelParam:
9585 // OpenCL v1.0 s6.5:
9586 // __kernel function arguments declared to be a pointer of a type can point
9587 // to one of the following address spaces only : __global, __local or
9588 // __constant.
9589 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9590 D.setInvalidType();
9591 return;
9593 // OpenCL v1.2 s6.9.k:
9594 // Arguments to kernel functions in a program cannot be declared with the
9595 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9596 // uintptr_t or a struct and/or union that contain fields declared to be
9597 // one of these built-in scalar types.
9599 case InvalidKernelParam:
9600 // OpenCL v1.2 s6.8 n:
9601 // A kernel function argument cannot be declared
9602 // of event_t type.
9603 // Do not diagnose half type since it is diagnosed as invalid argument
9604 // type for any function elsewhere.
9605 if (!PT->isHalfType()) {
9606 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9608 // Explain what typedefs are involved.
9609 const TypedefType *Typedef = nullptr;
9610 while ((Typedef = PT->getAs<TypedefType>())) {
9611 SourceLocation Loc = Typedef->getDecl()->getLocation();
9612 // SourceLocation may be invalid for a built-in type.
9613 if (Loc.isValid())
9614 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9615 PT = Typedef->desugar();
9619 D.setInvalidType();
9620 return;
9622 case PtrKernelParam:
9623 case ValidKernelParam:
9624 ValidTypes.insert(PT.getTypePtr());
9625 return;
9627 case RecordKernelParam:
9628 break;
9631 // Track nested structs we will inspect
9632 SmallVector<const Decl *, 4> VisitStack;
9634 // Track where we are in the nested structs. Items will migrate from
9635 // VisitStack to HistoryStack as we do the DFS for bad field.
9636 SmallVector<const FieldDecl *, 4> HistoryStack;
9637 HistoryStack.push_back(nullptr);
9639 // At this point we already handled everything except of a RecordType or
9640 // an ArrayType of a RecordType.
9641 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9642 const RecordType *RecTy =
9643 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
9644 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9646 VisitStack.push_back(RecTy->getDecl());
9647 assert(VisitStack.back() && "First decl null?");
9649 do {
9650 const Decl *Next = VisitStack.pop_back_val();
9651 if (!Next) {
9652 assert(!HistoryStack.empty());
9653 // Found a marker, we have gone up a level
9654 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9655 ValidTypes.insert(Hist->getType().getTypePtr());
9657 continue;
9660 // Adds everything except the original parameter declaration (which is not a
9661 // field itself) to the history stack.
9662 const RecordDecl *RD;
9663 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9664 HistoryStack.push_back(Field);
9666 QualType FieldTy = Field->getType();
9667 // Other field types (known to be valid or invalid) are handled while we
9668 // walk around RecordDecl::fields().
9669 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9670 "Unexpected type.");
9671 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9673 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9674 } else {
9675 RD = cast<RecordDecl>(Next);
9678 // Add a null marker so we know when we've gone back up a level
9679 VisitStack.push_back(nullptr);
9681 for (const auto *FD : RD->fields()) {
9682 QualType QT = FD->getType();
9684 if (ValidTypes.count(QT.getTypePtr()))
9685 continue;
9687 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9688 if (ParamType == ValidKernelParam)
9689 continue;
9691 if (ParamType == RecordKernelParam) {
9692 VisitStack.push_back(FD);
9693 continue;
9696 // OpenCL v1.2 s6.9.p:
9697 // Arguments to kernel functions that are declared to be a struct or union
9698 // do not allow OpenCL objects to be passed as elements of the struct or
9699 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9700 // of SVM.
9701 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9702 ParamType == InvalidAddrSpacePtrKernelParam) {
9703 S.Diag(Param->getLocation(),
9704 diag::err_record_with_pointers_kernel_param)
9705 << PT->isUnionType()
9706 << PT;
9707 } else {
9708 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9711 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9712 << OrigRecDecl->getDeclName();
9714 // We have an error, now let's go back up through history and show where
9715 // the offending field came from
9716 for (ArrayRef<const FieldDecl *>::const_iterator
9717 I = HistoryStack.begin() + 1,
9718 E = HistoryStack.end();
9719 I != E; ++I) {
9720 const FieldDecl *OuterField = *I;
9721 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9722 << OuterField->getType();
9725 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9726 << QT->isPointerType()
9727 << QT;
9728 D.setInvalidType();
9729 return;
9731 } while (!VisitStack.empty());
9734 /// Find the DeclContext in which a tag is implicitly declared if we see an
9735 /// elaborated type specifier in the specified context, and lookup finds
9736 /// nothing.
9737 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9738 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9739 DC = DC->getParent();
9740 return DC;
9743 /// Find the Scope in which a tag is implicitly declared if we see an
9744 /// elaborated type specifier in the specified context, and lookup finds
9745 /// nothing.
9746 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9747 while (S->isClassScope() ||
9748 (LangOpts.CPlusPlus &&
9749 S->isFunctionPrototypeScope()) ||
9750 ((S->getFlags() & Scope::DeclScope) == 0) ||
9751 (S->getEntity() && S->getEntity()->isTransparentContext()))
9752 S = S->getParent();
9753 return S;
9756 /// Determine whether a declaration matches a known function in namespace std.
9757 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
9758 unsigned BuiltinID) {
9759 switch (BuiltinID) {
9760 case Builtin::BI__GetExceptionInfo:
9761 // No type checking whatsoever.
9762 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9764 case Builtin::BIaddressof:
9765 case Builtin::BI__addressof:
9766 case Builtin::BIforward:
9767 case Builtin::BIforward_like:
9768 case Builtin::BImove:
9769 case Builtin::BImove_if_noexcept:
9770 case Builtin::BIas_const: {
9771 // Ensure that we don't treat the algorithm
9772 // OutputIt std::move(InputIt, InputIt, OutputIt)
9773 // as the builtin std::move.
9774 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9775 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9778 default:
9779 return false;
9783 NamedDecl*
9784 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9785 TypeSourceInfo *TInfo, LookupResult &Previous,
9786 MultiTemplateParamsArg TemplateParamListsRef,
9787 bool &AddToScope) {
9788 QualType R = TInfo->getType();
9790 assert(R->isFunctionType());
9791 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9792 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9794 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9795 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9796 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9797 if (!TemplateParamLists.empty() &&
9798 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9799 TemplateParamLists.back() = Invented;
9800 else
9801 TemplateParamLists.push_back(Invented);
9804 // TODO: consider using NameInfo for diagnostic.
9805 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9806 DeclarationName Name = NameInfo.getName();
9807 StorageClass SC = getFunctionStorageClass(*this, D);
9809 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9810 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9811 diag::err_invalid_thread)
9812 << DeclSpec::getSpecifierName(TSCS);
9814 if (D.isFirstDeclarationOfMember())
9815 adjustMemberFunctionCC(
9816 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9817 D.isCtorOrDtor(), D.getIdentifierLoc());
9819 bool isFriend = false;
9820 FunctionTemplateDecl *FunctionTemplate = nullptr;
9821 bool isMemberSpecialization = false;
9822 bool isFunctionTemplateSpecialization = false;
9824 bool HasExplicitTemplateArgs = false;
9825 TemplateArgumentListInfo TemplateArgs;
9827 bool isVirtualOkay = false;
9829 DeclContext *OriginalDC = DC;
9830 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9832 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9833 isVirtualOkay);
9834 if (!NewFD) return nullptr;
9836 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9837 NewFD->setTopLevelDeclInObjCContainer();
9839 // Set the lexical context. If this is a function-scope declaration, or has a
9840 // C++ scope specifier, or is the object of a friend declaration, the lexical
9841 // context will be different from the semantic context.
9842 NewFD->setLexicalDeclContext(CurContext);
9844 if (IsLocalExternDecl)
9845 NewFD->setLocalExternDecl();
9847 if (getLangOpts().CPlusPlus) {
9848 // The rules for implicit inlines changed in C++20 for methods and friends
9849 // with an in-class definition (when such a definition is not attached to
9850 // the global module). User-specified 'inline' overrides this (set when
9851 // the function decl is created above).
9852 // FIXME: We need a better way to separate C++ standard and clang modules.
9853 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9854 !NewFD->getOwningModule() ||
9855 NewFD->getOwningModule()->isGlobalModule() ||
9856 NewFD->getOwningModule()->isHeaderLikeModule();
9857 bool isInline = D.getDeclSpec().isInlineSpecified();
9858 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9859 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9860 isFriend = D.getDeclSpec().isFriendSpecified();
9861 if (isFriend && !isInline && D.isFunctionDefinition()) {
9862 // Pre-C++20 [class.friend]p5
9863 // A function can be defined in a friend declaration of a
9864 // class . . . . Such a function is implicitly inline.
9865 // Post C++20 [class.friend]p7
9866 // Such a function is implicitly an inline function if it is attached
9867 // to the global module.
9868 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9871 // If this is a method defined in an __interface, and is not a constructor
9872 // or an overloaded operator, then set the pure flag (isVirtual will already
9873 // return true).
9874 if (const CXXRecordDecl *Parent =
9875 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9876 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9877 NewFD->setPure(true);
9879 // C++ [class.union]p2
9880 // A union can have member functions, but not virtual functions.
9881 if (isVirtual && Parent->isUnion()) {
9882 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9883 NewFD->setInvalidDecl();
9885 if ((Parent->isClass() || Parent->isStruct()) &&
9886 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9887 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9888 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9889 if (auto *Def = Parent->getDefinition())
9890 Def->setInitMethod(true);
9894 SetNestedNameSpecifier(*this, NewFD, D);
9895 isMemberSpecialization = false;
9896 isFunctionTemplateSpecialization = false;
9897 if (D.isInvalidType())
9898 NewFD->setInvalidDecl();
9900 // Match up the template parameter lists with the scope specifier, then
9901 // determine whether we have a template or a template specialization.
9902 bool Invalid = false;
9903 TemplateParameterList *TemplateParams =
9904 MatchTemplateParametersToScopeSpecifier(
9905 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9906 D.getCXXScopeSpec(),
9907 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9908 ? D.getName().TemplateId
9909 : nullptr,
9910 TemplateParamLists, isFriend, isMemberSpecialization,
9911 Invalid);
9912 if (TemplateParams) {
9913 // Check that we can declare a template here.
9914 if (CheckTemplateDeclScope(S, TemplateParams))
9915 NewFD->setInvalidDecl();
9917 if (TemplateParams->size() > 0) {
9918 // This is a function template
9920 // A destructor cannot be a template.
9921 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9922 Diag(NewFD->getLocation(), diag::err_destructor_template);
9923 NewFD->setInvalidDecl();
9926 // If we're adding a template to a dependent context, we may need to
9927 // rebuilding some of the types used within the template parameter list,
9928 // now that we know what the current instantiation is.
9929 if (DC->isDependentContext()) {
9930 ContextRAII SavedContext(*this, DC);
9931 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9932 Invalid = true;
9935 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9936 NewFD->getLocation(),
9937 Name, TemplateParams,
9938 NewFD);
9939 FunctionTemplate->setLexicalDeclContext(CurContext);
9940 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9942 // For source fidelity, store the other template param lists.
9943 if (TemplateParamLists.size() > 1) {
9944 NewFD->setTemplateParameterListsInfo(Context,
9945 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9946 .drop_back(1));
9948 } else {
9949 // This is a function template specialization.
9950 isFunctionTemplateSpecialization = true;
9951 // For source fidelity, store all the template param lists.
9952 if (TemplateParamLists.size() > 0)
9953 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9955 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9956 if (isFriend) {
9957 // We want to remove the "template<>", found here.
9958 SourceRange RemoveRange = TemplateParams->getSourceRange();
9960 // If we remove the template<> and the name is not a
9961 // template-id, we're actually silently creating a problem:
9962 // the friend declaration will refer to an untemplated decl,
9963 // and clearly the user wants a template specialization. So
9964 // we need to insert '<>' after the name.
9965 SourceLocation InsertLoc;
9966 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9967 InsertLoc = D.getName().getSourceRange().getEnd();
9968 InsertLoc = getLocForEndOfToken(InsertLoc);
9971 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9972 << Name << RemoveRange
9973 << FixItHint::CreateRemoval(RemoveRange)
9974 << FixItHint::CreateInsertion(InsertLoc, "<>");
9975 Invalid = true;
9978 } else {
9979 // Check that we can declare a template here.
9980 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9981 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9982 NewFD->setInvalidDecl();
9984 // All template param lists were matched against the scope specifier:
9985 // this is NOT (an explicit specialization of) a template.
9986 if (TemplateParamLists.size() > 0)
9987 // For source fidelity, store all the template param lists.
9988 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9991 if (Invalid) {
9992 NewFD->setInvalidDecl();
9993 if (FunctionTemplate)
9994 FunctionTemplate->setInvalidDecl();
9997 // C++ [dcl.fct.spec]p5:
9998 // The virtual specifier shall only be used in declarations of
9999 // nonstatic class member functions that appear within a
10000 // member-specification of a class declaration; see 10.3.
10002 if (isVirtual && !NewFD->isInvalidDecl()) {
10003 if (!isVirtualOkay) {
10004 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10005 diag::err_virtual_non_function);
10006 } else if (!CurContext->isRecord()) {
10007 // 'virtual' was specified outside of the class.
10008 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10009 diag::err_virtual_out_of_class)
10010 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10011 } else if (NewFD->getDescribedFunctionTemplate()) {
10012 // C++ [temp.mem]p3:
10013 // A member function template shall not be virtual.
10014 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10015 diag::err_virtual_member_function_template)
10016 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10017 } else {
10018 // Okay: Add virtual to the method.
10019 NewFD->setVirtualAsWritten(true);
10022 if (getLangOpts().CPlusPlus14 &&
10023 NewFD->getReturnType()->isUndeducedType())
10024 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10027 if (getLangOpts().CPlusPlus14 &&
10028 (NewFD->isDependentContext() ||
10029 (isFriend && CurContext->isDependentContext())) &&
10030 NewFD->getReturnType()->isUndeducedType()) {
10031 // If the function template is referenced directly (for instance, as a
10032 // member of the current instantiation), pretend it has a dependent type.
10033 // This is not really justified by the standard, but is the only sane
10034 // thing to do.
10035 // FIXME: For a friend function, we have not marked the function as being
10036 // a friend yet, so 'isDependentContext' on the FD doesn't work.
10037 const FunctionProtoType *FPT =
10038 NewFD->getType()->castAs<FunctionProtoType>();
10039 QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
10040 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
10041 FPT->getExtProtoInfo()));
10044 // C++ [dcl.fct.spec]p3:
10045 // The inline specifier shall not appear on a block scope function
10046 // declaration.
10047 if (isInline && !NewFD->isInvalidDecl()) {
10048 if (CurContext->isFunctionOrMethod()) {
10049 // 'inline' is not allowed on block scope function declaration.
10050 Diag(D.getDeclSpec().getInlineSpecLoc(),
10051 diag::err_inline_declaration_block_scope) << Name
10052 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10056 // C++ [dcl.fct.spec]p6:
10057 // The explicit specifier shall be used only in the declaration of a
10058 // constructor or conversion function within its class definition;
10059 // see 12.3.1 and 12.3.2.
10060 if (hasExplicit && !NewFD->isInvalidDecl() &&
10061 !isa<CXXDeductionGuideDecl>(NewFD)) {
10062 if (!CurContext->isRecord()) {
10063 // 'explicit' was specified outside of the class.
10064 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10065 diag::err_explicit_out_of_class)
10066 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10067 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10068 !isa<CXXConversionDecl>(NewFD)) {
10069 // 'explicit' was specified on a function that wasn't a constructor
10070 // or conversion function.
10071 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10072 diag::err_explicit_non_ctor_or_conv_function)
10073 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10077 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10078 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10079 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10080 // are implicitly inline.
10081 NewFD->setImplicitlyInline();
10083 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10084 // be either constructors or to return a literal type. Therefore,
10085 // destructors cannot be declared constexpr.
10086 if (isa<CXXDestructorDecl>(NewFD) &&
10087 (!getLangOpts().CPlusPlus20 ||
10088 ConstexprKind == ConstexprSpecKind::Consteval)) {
10089 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10090 << static_cast<int>(ConstexprKind);
10091 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10092 ? ConstexprSpecKind::Unspecified
10093 : ConstexprSpecKind::Constexpr);
10095 // C++20 [dcl.constexpr]p2: An allocation function, or a
10096 // deallocation function shall not be declared with the consteval
10097 // specifier.
10098 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10099 (NewFD->getOverloadedOperator() == OO_New ||
10100 NewFD->getOverloadedOperator() == OO_Array_New ||
10101 NewFD->getOverloadedOperator() == OO_Delete ||
10102 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10103 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10104 diag::err_invalid_consteval_decl_kind)
10105 << NewFD;
10106 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
10110 // If __module_private__ was specified, mark the function accordingly.
10111 if (D.getDeclSpec().isModulePrivateSpecified()) {
10112 if (isFunctionTemplateSpecialization) {
10113 SourceLocation ModulePrivateLoc
10114 = D.getDeclSpec().getModulePrivateSpecLoc();
10115 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10116 << 0
10117 << FixItHint::CreateRemoval(ModulePrivateLoc);
10118 } else {
10119 NewFD->setModulePrivate();
10120 if (FunctionTemplate)
10121 FunctionTemplate->setModulePrivate();
10125 if (isFriend) {
10126 if (FunctionTemplate) {
10127 FunctionTemplate->setObjectOfFriendDecl();
10128 FunctionTemplate->setAccess(AS_public);
10130 NewFD->setObjectOfFriendDecl();
10131 NewFD->setAccess(AS_public);
10134 // If a function is defined as defaulted or deleted, mark it as such now.
10135 // We'll do the relevant checks on defaulted / deleted functions later.
10136 switch (D.getFunctionDefinitionKind()) {
10137 case FunctionDefinitionKind::Declaration:
10138 case FunctionDefinitionKind::Definition:
10139 break;
10141 case FunctionDefinitionKind::Defaulted:
10142 NewFD->setDefaulted();
10143 break;
10145 case FunctionDefinitionKind::Deleted:
10146 NewFD->setDeletedAsWritten();
10147 break;
10150 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10151 D.isFunctionDefinition() && !isInline) {
10152 // Pre C++20 [class.mfct]p2:
10153 // A member function may be defined (8.4) in its class definition, in
10154 // which case it is an inline member function (7.1.2)
10155 // Post C++20 [class.mfct]p1:
10156 // If a member function is attached to the global module and is defined
10157 // in its class definition, it is inline.
10158 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10161 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
10162 !CurContext->isRecord()) {
10163 // C++ [class.static]p1:
10164 // A data or function member of a class may be declared static
10165 // in a class definition, in which case it is a static member of
10166 // the class.
10168 // Complain about the 'static' specifier if it's on an out-of-line
10169 // member function definition.
10171 // MSVC permits the use of a 'static' storage specifier on an out-of-line
10172 // member function template declaration and class member template
10173 // declaration (MSVC versions before 2015), warn about this.
10174 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10175 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10176 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10177 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
10178 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
10179 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10182 // C++11 [except.spec]p15:
10183 // A deallocation function with no exception-specification is treated
10184 // as if it were specified with noexcept(true).
10185 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10186 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10187 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10188 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10189 NewFD->setType(Context.getFunctionType(
10190 FPT->getReturnType(), FPT->getParamTypes(),
10191 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
10193 // C++20 [dcl.inline]/7
10194 // If an inline function or variable that is attached to a named module
10195 // is declared in a definition domain, it shall be defined in that
10196 // domain.
10197 // So, if the current declaration does not have a definition, we must
10198 // check at the end of the TU (or when the PMF starts) to see that we
10199 // have a definition at that point.
10200 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10201 NewFD->hasOwningModule() && NewFD->getOwningModule()->isNamedModule()) {
10202 PendingInlineFuncDecls.insert(NewFD);
10206 // Filter out previous declarations that don't match the scope.
10207 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
10208 D.getCXXScopeSpec().isNotEmpty() ||
10209 isMemberSpecialization ||
10210 isFunctionTemplateSpecialization);
10212 // Handle GNU asm-label extension (encoded as an attribute).
10213 if (Expr *E = (Expr*) D.getAsmLabel()) {
10214 // The parser guarantees this is a string.
10215 StringLiteral *SE = cast<StringLiteral>(E);
10216 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10217 /*IsLiteralLabel=*/true,
10218 SE->getStrTokenLoc(0)));
10219 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10220 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10221 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
10222 if (I != ExtnameUndeclaredIdentifiers.end()) {
10223 if (isDeclExternC(NewFD)) {
10224 NewFD->addAttr(I->second);
10225 ExtnameUndeclaredIdentifiers.erase(I);
10226 } else
10227 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10228 << /*Variable*/0 << NewFD;
10232 // Copy the parameter declarations from the declarator D to the function
10233 // declaration NewFD, if they are available. First scavenge them into Params.
10234 SmallVector<ParmVarDecl*, 16> Params;
10235 unsigned FTIIdx;
10236 if (D.isFunctionDeclarator(FTIIdx)) {
10237 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10239 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10240 // function that takes no arguments, not a function that takes a
10241 // single void argument.
10242 // We let through "const void" here because Sema::GetTypeForDeclarator
10243 // already checks for that case.
10244 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10245 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10246 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10247 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10248 Param->setDeclContext(NewFD);
10249 Params.push_back(Param);
10251 if (Param->isInvalidDecl())
10252 NewFD->setInvalidDecl();
10256 if (!getLangOpts().CPlusPlus) {
10257 // In C, find all the tag declarations from the prototype and move them
10258 // into the function DeclContext. Remove them from the surrounding tag
10259 // injection context of the function, which is typically but not always
10260 // the TU.
10261 DeclContext *PrototypeTagContext =
10262 getTagInjectionContext(NewFD->getLexicalDeclContext());
10263 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10264 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10266 // We don't want to reparent enumerators. Look at their parent enum
10267 // instead.
10268 if (!TD) {
10269 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10270 TD = cast<EnumDecl>(ECD->getDeclContext());
10272 if (!TD)
10273 continue;
10274 DeclContext *TagDC = TD->getLexicalDeclContext();
10275 if (!TagDC->containsDecl(TD))
10276 continue;
10277 TagDC->removeDecl(TD);
10278 TD->setDeclContext(NewFD);
10279 NewFD->addDecl(TD);
10281 // Preserve the lexical DeclContext if it is not the surrounding tag
10282 // injection context of the FD. In this example, the semantic context of
10283 // E will be f and the lexical context will be S, while both the
10284 // semantic and lexical contexts of S will be f:
10285 // void f(struct S { enum E { a } f; } s);
10286 if (TagDC != PrototypeTagContext)
10287 TD->setLexicalDeclContext(TagDC);
10290 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10291 // When we're declaring a function with a typedef, typeof, etc as in the
10292 // following example, we'll need to synthesize (unnamed)
10293 // parameters for use in the declaration.
10295 // @code
10296 // typedef void fn(int);
10297 // fn f;
10298 // @endcode
10300 // Synthesize a parameter for each argument type.
10301 for (const auto &AI : FT->param_types()) {
10302 ParmVarDecl *Param =
10303 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10304 Param->setScopeInfo(0, Params.size());
10305 Params.push_back(Param);
10307 } else {
10308 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10309 "Should not need args for typedef of non-prototype fn");
10312 // Finally, we know we have the right number of parameters, install them.
10313 NewFD->setParams(Params);
10315 if (D.getDeclSpec().isNoreturnSpecified())
10316 NewFD->addAttr(
10317 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10319 // Functions returning a variably modified type violate C99 6.7.5.2p2
10320 // because all functions have linkage.
10321 if (!NewFD->isInvalidDecl() &&
10322 NewFD->getReturnType()->isVariablyModifiedType()) {
10323 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10324 NewFD->setInvalidDecl();
10327 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10328 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10329 !NewFD->hasAttr<SectionAttr>())
10330 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10331 Context, PragmaClangTextSection.SectionName,
10332 PragmaClangTextSection.PragmaLocation));
10334 // Apply an implicit SectionAttr if #pragma code_seg is active.
10335 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10336 !NewFD->hasAttr<SectionAttr>()) {
10337 NewFD->addAttr(SectionAttr::CreateImplicit(
10338 Context, CodeSegStack.CurrentValue->getString(),
10339 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10340 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10341 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
10342 ASTContext::PSF_Read,
10343 NewFD))
10344 NewFD->dropAttr<SectionAttr>();
10347 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10348 // active.
10349 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10350 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10351 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10352 Context, PragmaClangTextSection.PragmaLocation));
10354 // Apply an implicit CodeSegAttr from class declspec or
10355 // apply an implicit SectionAttr from #pragma code_seg if active.
10356 if (!NewFD->hasAttr<CodeSegAttr>()) {
10357 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
10358 D.isFunctionDefinition())) {
10359 NewFD->addAttr(SAttr);
10363 // Handle attributes.
10364 ProcessDeclAttributes(S, NewFD, D);
10365 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10366 if (NewTVA && !NewTVA->isDefaultVersion() &&
10367 !Context.getTargetInfo().hasFeature("fmv")) {
10368 // Don't add to scope fmv functions declarations if fmv disabled
10369 AddToScope = false;
10370 return NewFD;
10373 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10374 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10375 // type.
10377 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10378 // type declaration will generate a compilation error.
10379 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10380 if (AddressSpace != LangAS::Default) {
10381 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10382 NewFD->setInvalidDecl();
10386 if (!getLangOpts().CPlusPlus) {
10387 // Perform semantic checking on the function declaration.
10388 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10389 CheckMain(NewFD, D.getDeclSpec());
10391 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10392 CheckMSVCRTEntryPoint(NewFD);
10394 if (!NewFD->isInvalidDecl())
10395 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10396 isMemberSpecialization,
10397 D.isFunctionDefinition()));
10398 else if (!Previous.empty())
10399 // Recover gracefully from an invalid redeclaration.
10400 D.setRedeclaration(true);
10401 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10402 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10403 "previous declaration set still overloaded");
10405 // Diagnose no-prototype function declarations with calling conventions that
10406 // don't support variadic calls. Only do this in C and do it after merging
10407 // possibly prototyped redeclarations.
10408 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10409 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10410 CallingConv CC = FT->getExtInfo().getCC();
10411 if (!supportsVariadicCall(CC)) {
10412 // Windows system headers sometimes accidentally use stdcall without
10413 // (void) parameters, so we relax this to a warning.
10414 int DiagID =
10415 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10416 Diag(NewFD->getLocation(), DiagID)
10417 << FunctionType::getNameForCallConv(CC);
10421 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
10422 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
10423 checkNonTrivialCUnion(NewFD->getReturnType(),
10424 NewFD->getReturnTypeSourceRange().getBegin(),
10425 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
10426 } else {
10427 // C++11 [replacement.functions]p3:
10428 // The program's definitions shall not be specified as inline.
10430 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10432 // Suppress the diagnostic if the function is __attribute__((used)), since
10433 // that forces an external definition to be emitted.
10434 if (D.getDeclSpec().isInlineSpecified() &&
10435 NewFD->isReplaceableGlobalAllocationFunction() &&
10436 !NewFD->hasAttr<UsedAttr>())
10437 Diag(D.getDeclSpec().getInlineSpecLoc(),
10438 diag::ext_operator_new_delete_declared_inline)
10439 << NewFD->getDeclName();
10441 // If the declarator is a template-id, translate the parser's template
10442 // argument list into our AST format.
10443 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10444 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
10445 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10446 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10447 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10448 TemplateId->NumArgs);
10449 translateTemplateArguments(TemplateArgsPtr,
10450 TemplateArgs);
10452 HasExplicitTemplateArgs = true;
10454 if (NewFD->isInvalidDecl()) {
10455 HasExplicitTemplateArgs = false;
10456 } else if (FunctionTemplate) {
10457 // Function template with explicit template arguments.
10458 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10459 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10461 HasExplicitTemplateArgs = false;
10462 } else if (isFriend) {
10463 // "friend void foo<>(int);" is an implicit specialization decl.
10464 isFunctionTemplateSpecialization = true;
10465 } else {
10466 assert(isFunctionTemplateSpecialization &&
10467 "should have a 'template<>' for this decl");
10469 } else if (isFriend && isFunctionTemplateSpecialization) {
10470 // This combination is only possible in a recovery case; the user
10471 // wrote something like:
10472 // template <> friend void foo(int);
10473 // which we're recovering from as if the user had written:
10474 // friend void foo<>(int);
10475 // Go ahead and fake up a template id.
10476 HasExplicitTemplateArgs = true;
10477 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
10478 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
10481 // We do not add HD attributes to specializations here because
10482 // they may have different constexpr-ness compared to their
10483 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
10484 // may end up with different effective targets. Instead, a
10485 // specialization inherits its target attributes from its template
10486 // in the CheckFunctionTemplateSpecialization() call below.
10487 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10488 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
10490 // Handle explict specializations of function templates
10491 // and friend function declarations with an explicit
10492 // template argument list.
10493 if (isFunctionTemplateSpecialization) {
10494 bool isDependentSpecialization = false;
10495 if (isFriend) {
10496 // For friend function specializations, this is a dependent
10497 // specialization if its semantic context is dependent, its
10498 // type is dependent, or if its template-id is dependent.
10499 isDependentSpecialization =
10500 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10501 (HasExplicitTemplateArgs &&
10502 TemplateSpecializationType::
10503 anyInstantiationDependentTemplateArguments(
10504 TemplateArgs.arguments()));
10505 assert((!isDependentSpecialization ||
10506 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10507 "dependent friend function specialization without template "
10508 "args");
10509 } else {
10510 // For class-scope explicit specializations of function templates,
10511 // if the lexical context is dependent, then the specialization
10512 // is dependent.
10513 isDependentSpecialization =
10514 CurContext->isRecord() && CurContext->isDependentContext();
10517 TemplateArgumentListInfo *ExplicitTemplateArgs =
10518 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10519 if (isDependentSpecialization) {
10520 // If it's a dependent specialization, it may not be possible
10521 // to determine the primary template (for explicit specializations)
10522 // or befriended declaration (for friends) until the enclosing
10523 // template is instantiated. In such cases, we store the declarations
10524 // found by name lookup and defer resolution until instantiation.
10525 if (CheckDependentFunctionTemplateSpecialization(
10526 NewFD, ExplicitTemplateArgs, Previous))
10527 NewFD->setInvalidDecl();
10528 } else if (!NewFD->isInvalidDecl()) {
10529 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10530 Previous))
10531 NewFD->setInvalidDecl();
10534 // C++ [dcl.stc]p1:
10535 // A storage-class-specifier shall not be specified in an explicit
10536 // specialization (14.7.3)
10537 // FIXME: We should be checking this for dependent specializations.
10538 FunctionTemplateSpecializationInfo *Info =
10539 NewFD->getTemplateSpecializationInfo();
10540 if (Info && SC != SC_None) {
10541 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
10542 Diag(NewFD->getLocation(),
10543 diag::err_explicit_specialization_inconsistent_storage_class)
10544 << SC
10545 << FixItHint::CreateRemoval(
10546 D.getDeclSpec().getStorageClassSpecLoc());
10548 else
10549 Diag(NewFD->getLocation(),
10550 diag::ext_explicit_specialization_storage_class)
10551 << FixItHint::CreateRemoval(
10552 D.getDeclSpec().getStorageClassSpecLoc());
10554 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10555 if (CheckMemberSpecialization(NewFD, Previous))
10556 NewFD->setInvalidDecl();
10559 // Perform semantic checking on the function declaration.
10560 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10561 CheckMain(NewFD, D.getDeclSpec());
10563 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10564 CheckMSVCRTEntryPoint(NewFD);
10566 if (!NewFD->isInvalidDecl())
10567 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10568 isMemberSpecialization,
10569 D.isFunctionDefinition()));
10570 else if (!Previous.empty())
10571 // Recover gracefully from an invalid redeclaration.
10572 D.setRedeclaration(true);
10574 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10575 !D.isRedeclaration() ||
10576 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10577 "previous declaration set still overloaded");
10579 NamedDecl *PrincipalDecl = (FunctionTemplate
10580 ? cast<NamedDecl>(FunctionTemplate)
10581 : NewFD);
10583 if (isFriend && NewFD->getPreviousDecl()) {
10584 AccessSpecifier Access = AS_public;
10585 if (!NewFD->isInvalidDecl())
10586 Access = NewFD->getPreviousDecl()->getAccess();
10588 NewFD->setAccess(Access);
10589 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10592 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10593 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
10594 PrincipalDecl->setNonMemberOperator();
10596 // If we have a function template, check the template parameter
10597 // list. This will check and merge default template arguments.
10598 if (FunctionTemplate) {
10599 FunctionTemplateDecl *PrevTemplate =
10600 FunctionTemplate->getPreviousDecl();
10601 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10602 PrevTemplate ? PrevTemplate->getTemplateParameters()
10603 : nullptr,
10604 D.getDeclSpec().isFriendSpecified()
10605 ? (D.isFunctionDefinition()
10606 ? TPC_FriendFunctionTemplateDefinition
10607 : TPC_FriendFunctionTemplate)
10608 : (D.getCXXScopeSpec().isSet() &&
10609 DC && DC->isRecord() &&
10610 DC->isDependentContext())
10611 ? TPC_ClassTemplateMember
10612 : TPC_FunctionTemplate);
10615 if (NewFD->isInvalidDecl()) {
10616 // Ignore all the rest of this.
10617 } else if (!D.isRedeclaration()) {
10618 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10619 AddToScope };
10620 // Fake up an access specifier if it's supposed to be a class member.
10621 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10622 NewFD->setAccess(AS_public);
10624 // Qualified decls generally require a previous declaration.
10625 if (D.getCXXScopeSpec().isSet()) {
10626 // ...with the major exception of templated-scope or
10627 // dependent-scope friend declarations.
10629 // TODO: we currently also suppress this check in dependent
10630 // contexts because (1) the parameter depth will be off when
10631 // matching friend templates and (2) we might actually be
10632 // selecting a friend based on a dependent factor. But there
10633 // are situations where these conditions don't apply and we
10634 // can actually do this check immediately.
10636 // Unless the scope is dependent, it's always an error if qualified
10637 // redeclaration lookup found nothing at all. Diagnose that now;
10638 // nothing will diagnose that error later.
10639 if (isFriend &&
10640 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10641 (!Previous.empty() && CurContext->isDependentContext()))) {
10642 // ignore these
10643 } else if (NewFD->isCPUDispatchMultiVersion() ||
10644 NewFD->isCPUSpecificMultiVersion()) {
10645 // ignore this, we allow the redeclaration behavior here to create new
10646 // versions of the function.
10647 } else {
10648 // The user tried to provide an out-of-line definition for a
10649 // function that is a member of a class or namespace, but there
10650 // was no such member function declared (C++ [class.mfct]p2,
10651 // C++ [namespace.memdef]p2). For example:
10653 // class X {
10654 // void f() const;
10655 // };
10657 // void X::f() { } // ill-formed
10659 // Complain about this problem, and attempt to suggest close
10660 // matches (e.g., those that differ only in cv-qualifiers and
10661 // whether the parameter types are references).
10663 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10664 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10665 AddToScope = ExtraArgs.AddToScope;
10666 return Result;
10670 // Unqualified local friend declarations are required to resolve
10671 // to something.
10672 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10673 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
10674 *this, Previous, NewFD, ExtraArgs, true, S)) {
10675 AddToScope = ExtraArgs.AddToScope;
10676 return Result;
10679 } else if (!D.isFunctionDefinition() &&
10680 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10681 !isFriend && !isFunctionTemplateSpecialization &&
10682 !isMemberSpecialization) {
10683 // An out-of-line member function declaration must also be a
10684 // definition (C++ [class.mfct]p2).
10685 // Note that this is not the case for explicit specializations of
10686 // function templates or member functions of class templates, per
10687 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10688 // extension for compatibility with old SWIG code which likes to
10689 // generate them.
10690 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10691 << D.getCXXScopeSpec().getRange();
10695 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10696 // Any top level function could potentially be specified as an entry.
10697 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10698 ActOnHLSLTopLevelFunction(NewFD);
10700 if (NewFD->hasAttr<HLSLShaderAttr>())
10701 CheckHLSLEntryPoint(NewFD);
10704 // If this is the first declaration of a library builtin function, add
10705 // attributes as appropriate.
10706 if (!D.isRedeclaration()) {
10707 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10708 if (unsigned BuiltinID = II->getBuiltinID()) {
10709 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10710 if (!InStdNamespace &&
10711 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
10712 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10713 // Validate the type matches unless this builtin is specified as
10714 // matching regardless of its declared type.
10715 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10716 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10717 } else {
10718 ASTContext::GetBuiltinTypeError Error;
10719 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10720 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10722 if (!Error && !BuiltinType.isNull() &&
10723 Context.hasSameFunctionTypeIgnoringExceptionSpec(
10724 NewFD->getType(), BuiltinType))
10725 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10728 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10729 isStdBuiltin(Context, NewFD, BuiltinID)) {
10730 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10736 ProcessPragmaWeak(S, NewFD);
10737 checkAttributesAfterMerging(*this, *NewFD);
10739 AddKnownFunctionAttributes(NewFD);
10741 if (NewFD->hasAttr<OverloadableAttr>() &&
10742 !NewFD->getType()->getAs<FunctionProtoType>()) {
10743 Diag(NewFD->getLocation(),
10744 diag::err_attribute_overloadable_no_prototype)
10745 << NewFD;
10746 NewFD->dropAttr<OverloadableAttr>();
10749 // If there's a #pragma GCC visibility in scope, and this isn't a class
10750 // member, set the visibility of this function.
10751 if (!DC->isRecord() && NewFD->isExternallyVisible())
10752 AddPushedVisibilityAttribute(NewFD);
10754 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10755 // marking the function.
10756 AddCFAuditedAttribute(NewFD);
10758 // If this is a function definition, check if we have to apply any
10759 // attributes (i.e. optnone and no_builtin) due to a pragma.
10760 if (D.isFunctionDefinition()) {
10761 AddRangeBasedOptnone(NewFD);
10762 AddImplicitMSFunctionNoBuiltinAttr(NewFD);
10763 AddSectionMSAllocText(NewFD);
10764 ModifyFnAttributesMSPragmaOptimize(NewFD);
10767 // If this is the first declaration of an extern C variable, update
10768 // the map of such variables.
10769 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10770 isIncompleteDeclExternC(*this, NewFD))
10771 RegisterLocallyScopedExternCDecl(NewFD, S);
10773 // Set this FunctionDecl's range up to the right paren.
10774 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10776 if (D.isRedeclaration() && !Previous.empty()) {
10777 NamedDecl *Prev = Previous.getRepresentativeDecl();
10778 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10779 isMemberSpecialization ||
10780 isFunctionTemplateSpecialization,
10781 D.isFunctionDefinition());
10784 if (getLangOpts().CUDA) {
10785 IdentifierInfo *II = NewFD->getIdentifier();
10786 if (II && II->isStr(getCudaConfigureFuncName()) &&
10787 !NewFD->isInvalidDecl() &&
10788 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
10789 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10790 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10791 << getCudaConfigureFuncName();
10792 Context.setcudaConfigureCallDecl(NewFD);
10795 // Variadic functions, other than a *declaration* of printf, are not allowed
10796 // in device-side CUDA code, unless someone passed
10797 // -fcuda-allow-variadic-functions.
10798 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10799 (NewFD->hasAttr<CUDADeviceAttr>() ||
10800 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10801 !(II && II->isStr("printf") && NewFD->isExternC() &&
10802 !D.isFunctionDefinition())) {
10803 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10807 MarkUnusedFileScopedDecl(NewFD);
10811 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10812 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10813 if (SC == SC_Static) {
10814 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10815 D.setInvalidType();
10818 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10819 if (!NewFD->getReturnType()->isVoidType()) {
10820 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10821 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10822 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10823 : FixItHint());
10824 D.setInvalidType();
10827 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10828 for (auto *Param : NewFD->parameters())
10829 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10831 if (getLangOpts().OpenCLCPlusPlus) {
10832 if (DC->isRecord()) {
10833 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10834 D.setInvalidType();
10836 if (FunctionTemplate) {
10837 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10838 D.setInvalidType();
10843 if (getLangOpts().CPlusPlus) {
10844 // Precalculate whether this is a friend function template with a constraint
10845 // that depends on an enclosing template, per [temp.friend]p9.
10846 if (isFriend && FunctionTemplate &&
10847 FriendConstraintsDependOnEnclosingTemplate(NewFD))
10848 NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
10850 if (FunctionTemplate) {
10851 if (NewFD->isInvalidDecl())
10852 FunctionTemplate->setInvalidDecl();
10853 return FunctionTemplate;
10856 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10857 CompleteMemberSpecialization(NewFD, Previous);
10860 for (const ParmVarDecl *Param : NewFD->parameters()) {
10861 QualType PT = Param->getType();
10863 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10864 // types.
10865 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10866 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10867 QualType ElemTy = PipeTy->getElementType();
10868 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10869 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10870 D.setInvalidType();
10874 // WebAssembly tables can't be used as function parameters.
10875 if (Context.getTargetInfo().getTriple().isWasm()) {
10876 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
10877 Diag(Param->getTypeSpecStartLoc(),
10878 diag::err_wasm_table_as_function_parameter);
10879 D.setInvalidType();
10884 // Diagnose availability attributes. Availability cannot be used on functions
10885 // that are run during load/unload.
10886 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10887 if (NewFD->hasAttr<ConstructorAttr>()) {
10888 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10889 << 1;
10890 NewFD->dropAttr<AvailabilityAttr>();
10892 if (NewFD->hasAttr<DestructorAttr>()) {
10893 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10894 << 2;
10895 NewFD->dropAttr<AvailabilityAttr>();
10899 // Diagnose no_builtin attribute on function declaration that are not a
10900 // definition.
10901 // FIXME: We should really be doing this in
10902 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10903 // the FunctionDecl and at this point of the code
10904 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10905 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10906 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10907 switch (D.getFunctionDefinitionKind()) {
10908 case FunctionDefinitionKind::Defaulted:
10909 case FunctionDefinitionKind::Deleted:
10910 Diag(NBA->getLocation(),
10911 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10912 << NBA->getSpelling();
10913 break;
10914 case FunctionDefinitionKind::Declaration:
10915 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10916 << NBA->getSpelling();
10917 break;
10918 case FunctionDefinitionKind::Definition:
10919 break;
10922 return NewFD;
10925 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
10926 /// when __declspec(code_seg) "is applied to a class, all member functions of
10927 /// the class and nested classes -- this includes compiler-generated special
10928 /// member functions -- are put in the specified segment."
10929 /// The actual behavior is a little more complicated. The Microsoft compiler
10930 /// won't check outer classes if there is an active value from #pragma code_seg.
10931 /// The CodeSeg is always applied from the direct parent but only from outer
10932 /// classes when the #pragma code_seg stack is empty. See:
10933 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10934 /// available since MS has removed the page.
10935 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10936 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10937 if (!Method)
10938 return nullptr;
10939 const CXXRecordDecl *Parent = Method->getParent();
10940 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10941 Attr *NewAttr = SAttr->clone(S.getASTContext());
10942 NewAttr->setImplicit(true);
10943 return NewAttr;
10946 // The Microsoft compiler won't check outer classes for the CodeSeg
10947 // when the #pragma code_seg stack is active.
10948 if (S.CodeSegStack.CurrentValue)
10949 return nullptr;
10951 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10952 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10953 Attr *NewAttr = SAttr->clone(S.getASTContext());
10954 NewAttr->setImplicit(true);
10955 return NewAttr;
10958 return nullptr;
10961 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10962 /// containing class. Otherwise it will return implicit SectionAttr if the
10963 /// function is a definition and there is an active value on CodeSegStack
10964 /// (from the current #pragma code-seg value).
10966 /// \param FD Function being declared.
10967 /// \param IsDefinition Whether it is a definition or just a declaration.
10968 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10969 /// nullptr if no attribute should be added.
10970 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10971 bool IsDefinition) {
10972 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10973 return A;
10974 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10975 CodeSegStack.CurrentValue)
10976 return SectionAttr::CreateImplicit(
10977 getASTContext(), CodeSegStack.CurrentValue->getString(),
10978 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10979 return nullptr;
10982 /// Determines if we can perform a correct type check for \p D as a
10983 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10984 /// best-effort check.
10986 /// \param NewD The new declaration.
10987 /// \param OldD The old declaration.
10988 /// \param NewT The portion of the type of the new declaration to check.
10989 /// \param OldT The portion of the type of the old declaration to check.
10990 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10991 QualType NewT, QualType OldT) {
10992 if (!NewD->getLexicalDeclContext()->isDependentContext())
10993 return true;
10995 // For dependently-typed local extern declarations and friends, we can't
10996 // perform a correct type check in general until instantiation:
10998 // int f();
10999 // template<typename T> void g() { T f(); }
11001 // (valid if g() is only instantiated with T = int).
11002 if (NewT->isDependentType() &&
11003 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11004 return false;
11006 // Similarly, if the previous declaration was a dependent local extern
11007 // declaration, we don't really know its type yet.
11008 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11009 return false;
11011 return true;
11014 /// Checks if the new declaration declared in dependent context must be
11015 /// put in the same redeclaration chain as the specified declaration.
11017 /// \param D Declaration that is checked.
11018 /// \param PrevDecl Previous declaration found with proper lookup method for the
11019 /// same declaration name.
11020 /// \returns True if D must be added to the redeclaration chain which PrevDecl
11021 /// belongs to.
11023 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
11024 if (!D->getLexicalDeclContext()->isDependentContext())
11025 return true;
11027 // Don't chain dependent friend function definitions until instantiation, to
11028 // permit cases like
11030 // void func();
11031 // template<typename T> class C1 { friend void func() {} };
11032 // template<typename T> class C2 { friend void func() {} };
11034 // ... which is valid if only one of C1 and C2 is ever instantiated.
11036 // FIXME: This need only apply to function definitions. For now, we proxy
11037 // this by checking for a file-scope function. We do not want this to apply
11038 // to friend declarations nominating member functions, because that gets in
11039 // the way of access checks.
11040 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
11041 return false;
11043 auto *VD = dyn_cast<ValueDecl>(D);
11044 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11045 return !VD || !PrevVD ||
11046 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11047 PrevVD->getType());
11050 /// Check the target or target_version attribute of the function for
11051 /// MultiVersion validity.
11053 /// Returns true if there was an error, false otherwise.
11054 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11055 const auto *TA = FD->getAttr<TargetAttr>();
11056 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11057 assert(
11058 (TA || TVA) &&
11059 "MultiVersion candidate requires a target or target_version attribute");
11060 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
11061 enum ErrType { Feature = 0, Architecture = 1 };
11063 if (TA) {
11064 ParsedTargetAttr ParseInfo =
11065 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11066 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11067 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11068 << Architecture << ParseInfo.CPU;
11069 return true;
11071 for (const auto &Feat : ParseInfo.Features) {
11072 auto BareFeat = StringRef{Feat}.substr(1);
11073 if (Feat[0] == '-') {
11074 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11075 << Feature << ("no-" + BareFeat).str();
11076 return true;
11079 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11080 !TargetInfo.isValidFeatureName(BareFeat)) {
11081 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11082 << Feature << BareFeat;
11083 return true;
11088 if (TVA) {
11089 llvm::SmallVector<StringRef, 8> Feats;
11090 TVA->getFeatures(Feats);
11091 for (const auto &Feat : Feats) {
11092 if (!TargetInfo.validateCpuSupports(Feat)) {
11093 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11094 << Feature << Feat;
11095 return true;
11099 return false;
11102 // Provide a white-list of attributes that are allowed to be combined with
11103 // multiversion functions.
11104 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
11105 MultiVersionKind MVKind) {
11106 // Note: this list/diagnosis must match the list in
11107 // checkMultiversionAttributesAllSame.
11108 switch (Kind) {
11109 default:
11110 return false;
11111 case attr::Used:
11112 return MVKind == MultiVersionKind::Target;
11113 case attr::NonNull:
11114 case attr::NoThrow:
11115 return true;
11119 static bool checkNonMultiVersionCompatAttributes(Sema &S,
11120 const FunctionDecl *FD,
11121 const FunctionDecl *CausedFD,
11122 MultiVersionKind MVKind) {
11123 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11124 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11125 << static_cast<unsigned>(MVKind) << A;
11126 if (CausedFD)
11127 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11128 return true;
11131 for (const Attr *A : FD->attrs()) {
11132 switch (A->getKind()) {
11133 case attr::CPUDispatch:
11134 case attr::CPUSpecific:
11135 if (MVKind != MultiVersionKind::CPUDispatch &&
11136 MVKind != MultiVersionKind::CPUSpecific)
11137 return Diagnose(S, A);
11138 break;
11139 case attr::Target:
11140 if (MVKind != MultiVersionKind::Target)
11141 return Diagnose(S, A);
11142 break;
11143 case attr::TargetVersion:
11144 if (MVKind != MultiVersionKind::TargetVersion)
11145 return Diagnose(S, A);
11146 break;
11147 case attr::TargetClones:
11148 if (MVKind != MultiVersionKind::TargetClones)
11149 return Diagnose(S, A);
11150 break;
11151 default:
11152 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11153 return Diagnose(S, A);
11154 break;
11157 return false;
11160 bool Sema::areMultiversionVariantFunctionsCompatible(
11161 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11162 const PartialDiagnostic &NoProtoDiagID,
11163 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11164 const PartialDiagnosticAt &NoSupportDiagIDAt,
11165 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11166 bool ConstexprSupported, bool CLinkageMayDiffer) {
11167 enum DoesntSupport {
11168 FuncTemplates = 0,
11169 VirtFuncs = 1,
11170 DeducedReturn = 2,
11171 Constructors = 3,
11172 Destructors = 4,
11173 DeletedFuncs = 5,
11174 DefaultedFuncs = 6,
11175 ConstexprFuncs = 7,
11176 ConstevalFuncs = 8,
11177 Lambda = 9,
11179 enum Different {
11180 CallingConv = 0,
11181 ReturnType = 1,
11182 ConstexprSpec = 2,
11183 InlineSpec = 3,
11184 Linkage = 4,
11185 LanguageLinkage = 5,
11188 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11189 !OldFD->getType()->getAs<FunctionProtoType>()) {
11190 Diag(OldFD->getLocation(), NoProtoDiagID);
11191 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11192 return true;
11195 if (NoProtoDiagID.getDiagID() != 0 &&
11196 !NewFD->getType()->getAs<FunctionProtoType>())
11197 return Diag(NewFD->getLocation(), NoProtoDiagID);
11199 if (!TemplatesSupported &&
11200 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11201 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11202 << FuncTemplates;
11204 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11205 if (NewCXXFD->isVirtual())
11206 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11207 << VirtFuncs;
11209 if (isa<CXXConstructorDecl>(NewCXXFD))
11210 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11211 << Constructors;
11213 if (isa<CXXDestructorDecl>(NewCXXFD))
11214 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11215 << Destructors;
11218 if (NewFD->isDeleted())
11219 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11220 << DeletedFuncs;
11222 if (NewFD->isDefaulted())
11223 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11224 << DefaultedFuncs;
11226 if (!ConstexprSupported && NewFD->isConstexpr())
11227 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11228 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11230 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11231 const auto *NewType = cast<FunctionType>(NewQType);
11232 QualType NewReturnType = NewType->getReturnType();
11234 if (NewReturnType->isUndeducedType())
11235 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11236 << DeducedReturn;
11238 // Ensure the return type is identical.
11239 if (OldFD) {
11240 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11241 const auto *OldType = cast<FunctionType>(OldQType);
11242 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11243 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11245 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11246 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11248 QualType OldReturnType = OldType->getReturnType();
11250 if (OldReturnType != NewReturnType)
11251 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11253 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11254 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11256 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11257 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11259 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11260 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11262 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11263 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11265 if (CheckEquivalentExceptionSpec(
11266 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11267 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11268 return true;
11270 return false;
11273 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
11274 const FunctionDecl *NewFD,
11275 bool CausesMV,
11276 MultiVersionKind MVKind) {
11277 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
11278 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11279 if (OldFD)
11280 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11281 return true;
11284 bool IsCPUSpecificCPUDispatchMVKind =
11285 MVKind == MultiVersionKind::CPUDispatch ||
11286 MVKind == MultiVersionKind::CPUSpecific;
11288 if (CausesMV && OldFD &&
11289 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11290 return true;
11292 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11293 return true;
11295 // Only allow transition to MultiVersion if it hasn't been used.
11296 if (OldFD && CausesMV && OldFD->isUsed(false))
11297 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11299 return S.areMultiversionVariantFunctionsCompatible(
11300 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11301 PartialDiagnosticAt(NewFD->getLocation(),
11302 S.PDiag(diag::note_multiversioning_caused_here)),
11303 PartialDiagnosticAt(NewFD->getLocation(),
11304 S.PDiag(diag::err_multiversion_doesnt_support)
11305 << static_cast<unsigned>(MVKind)),
11306 PartialDiagnosticAt(NewFD->getLocation(),
11307 S.PDiag(diag::err_multiversion_diff)),
11308 /*TemplatesSupported=*/false,
11309 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11310 /*CLinkageMayDiffer=*/false);
11313 /// Check the validity of a multiversion function declaration that is the
11314 /// first of its kind. Also sets the multiversion'ness' of the function itself.
11316 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11318 /// Returns true if there was an error, false otherwise.
11319 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
11320 MultiVersionKind MVKind = FD->getMultiVersionKind();
11321 assert(MVKind != MultiVersionKind::None &&
11322 "Function lacks multiversion attribute");
11323 const auto *TA = FD->getAttr<TargetAttr>();
11324 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11325 // Target and target_version only causes MV if it is default, otherwise this
11326 // is a normal function.
11327 if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
11328 return false;
11330 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11331 FD->setInvalidDecl();
11332 return true;
11335 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11336 FD->setInvalidDecl();
11337 return true;
11340 FD->setIsMultiVersion();
11341 return false;
11344 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
11345 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11346 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
11347 return true;
11350 return false;
11353 static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
11354 FunctionDecl *NewFD,
11355 bool &Redeclaration,
11356 NamedDecl *&OldDecl,
11357 LookupResult &Previous) {
11358 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11359 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11360 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11361 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11362 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11363 // to change, this is a simple redeclaration.
11364 if ((NewTA && !NewTA->isDefaultVersion() &&
11365 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
11366 (NewTVA && !NewTVA->isDefaultVersion() &&
11367 (!OldTVA || OldTVA->getName() == NewTVA->getName())))
11368 return false;
11370 // Otherwise, this decl causes MultiVersioning.
11371 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11372 NewTVA ? MultiVersionKind::TargetVersion
11373 : MultiVersionKind::Target)) {
11374 NewFD->setInvalidDecl();
11375 return true;
11378 if (CheckMultiVersionValue(S, NewFD)) {
11379 NewFD->setInvalidDecl();
11380 return true;
11383 // If this is 'default', permit the forward declaration.
11384 if (!OldFD->isMultiVersion() &&
11385 ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11386 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
11387 Redeclaration = true;
11388 OldDecl = OldFD;
11389 OldFD->setIsMultiVersion();
11390 NewFD->setIsMultiVersion();
11391 return false;
11394 if (CheckMultiVersionValue(S, OldFD)) {
11395 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11396 NewFD->setInvalidDecl();
11397 return true;
11400 if (NewTA) {
11401 ParsedTargetAttr OldParsed =
11402 S.getASTContext().getTargetInfo().parseTargetAttr(
11403 OldTA->getFeaturesStr());
11404 llvm::sort(OldParsed.Features);
11405 ParsedTargetAttr NewParsed =
11406 S.getASTContext().getTargetInfo().parseTargetAttr(
11407 NewTA->getFeaturesStr());
11408 // Sort order doesn't matter, it just needs to be consistent.
11409 llvm::sort(NewParsed.Features);
11410 if (OldParsed == NewParsed) {
11411 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11412 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11413 NewFD->setInvalidDecl();
11414 return true;
11418 if (NewTVA) {
11419 llvm::SmallVector<StringRef, 8> Feats;
11420 OldTVA->getFeatures(Feats);
11421 llvm::sort(Feats);
11422 llvm::SmallVector<StringRef, 8> NewFeats;
11423 NewTVA->getFeatures(NewFeats);
11424 llvm::sort(NewFeats);
11426 if (Feats == NewFeats) {
11427 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11428 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11429 NewFD->setInvalidDecl();
11430 return true;
11434 for (const auto *FD : OldFD->redecls()) {
11435 const auto *CurTA = FD->getAttr<TargetAttr>();
11436 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11437 // We allow forward declarations before ANY multiversioning attributes, but
11438 // nothing after the fact.
11439 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
11440 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11441 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11442 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11443 << (NewTA ? 0 : 2);
11444 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11445 NewFD->setInvalidDecl();
11446 return true;
11450 OldFD->setIsMultiVersion();
11451 NewFD->setIsMultiVersion();
11452 Redeclaration = false;
11453 OldDecl = nullptr;
11454 Previous.clear();
11455 return false;
11458 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
11459 MultiVersionKind New) {
11460 if (Old == New || Old == MultiVersionKind::None ||
11461 New == MultiVersionKind::None)
11462 return true;
11464 return (Old == MultiVersionKind::CPUDispatch &&
11465 New == MultiVersionKind::CPUSpecific) ||
11466 (Old == MultiVersionKind::CPUSpecific &&
11467 New == MultiVersionKind::CPUDispatch);
11470 /// Check the validity of a new function declaration being added to an existing
11471 /// multiversioned declaration collection.
11472 static bool CheckMultiVersionAdditionalDecl(
11473 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11474 MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
11475 const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
11476 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
11477 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11478 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11479 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11480 // Disallow mixing of multiversioning types.
11481 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
11482 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11483 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11484 NewFD->setInvalidDecl();
11485 return true;
11488 ParsedTargetAttr NewParsed;
11489 if (NewTA) {
11490 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
11491 NewTA->getFeaturesStr());
11492 llvm::sort(NewParsed.Features);
11494 llvm::SmallVector<StringRef, 8> NewFeats;
11495 if (NewTVA) {
11496 NewTVA->getFeatures(NewFeats);
11497 llvm::sort(NewFeats);
11500 bool UseMemberUsingDeclRules =
11501 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11503 bool MayNeedOverloadableChecks =
11504 AllowOverloadingOfFunction(Previous, S.Context, NewFD);
11506 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11507 // of a previous member of the MultiVersion set.
11508 for (NamedDecl *ND : Previous) {
11509 FunctionDecl *CurFD = ND->getAsFunction();
11510 if (!CurFD || CurFD->isInvalidDecl())
11511 continue;
11512 if (MayNeedOverloadableChecks &&
11513 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11514 continue;
11516 if (NewMVKind == MultiVersionKind::None &&
11517 OldMVKind == MultiVersionKind::TargetVersion) {
11518 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11519 S.Context, "default", NewFD->getSourceRange()));
11520 NewFD->setIsMultiVersion();
11521 NewMVKind = MultiVersionKind::TargetVersion;
11522 if (!NewTVA) {
11523 NewTVA = NewFD->getAttr<TargetVersionAttr>();
11524 NewTVA->getFeatures(NewFeats);
11525 llvm::sort(NewFeats);
11529 switch (NewMVKind) {
11530 case MultiVersionKind::None:
11531 assert(OldMVKind == MultiVersionKind::TargetClones &&
11532 "Only target_clones can be omitted in subsequent declarations");
11533 break;
11534 case MultiVersionKind::Target: {
11535 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11536 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11537 NewFD->setIsMultiVersion();
11538 Redeclaration = true;
11539 OldDecl = ND;
11540 return false;
11543 ParsedTargetAttr CurParsed =
11544 S.getASTContext().getTargetInfo().parseTargetAttr(
11545 CurTA->getFeaturesStr());
11546 llvm::sort(CurParsed.Features);
11547 if (CurParsed == NewParsed) {
11548 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11549 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11550 NewFD->setInvalidDecl();
11551 return true;
11553 break;
11555 case MultiVersionKind::TargetVersion: {
11556 const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
11557 if (CurTVA->getName() == NewTVA->getName()) {
11558 NewFD->setIsMultiVersion();
11559 Redeclaration = true;
11560 OldDecl = ND;
11561 return false;
11563 llvm::SmallVector<StringRef, 8> CurFeats;
11564 if (CurTVA) {
11565 CurTVA->getFeatures(CurFeats);
11566 llvm::sort(CurFeats);
11568 if (CurFeats == NewFeats) {
11569 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11570 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11571 NewFD->setInvalidDecl();
11572 return true;
11574 break;
11576 case MultiVersionKind::TargetClones: {
11577 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
11578 Redeclaration = true;
11579 OldDecl = CurFD;
11580 NewFD->setIsMultiVersion();
11582 if (CurClones && NewClones &&
11583 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11584 !std::equal(CurClones->featuresStrs_begin(),
11585 CurClones->featuresStrs_end(),
11586 NewClones->featuresStrs_begin()))) {
11587 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11588 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11589 NewFD->setInvalidDecl();
11590 return true;
11593 return false;
11595 case MultiVersionKind::CPUSpecific:
11596 case MultiVersionKind::CPUDispatch: {
11597 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11598 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11599 // Handle CPUDispatch/CPUSpecific versions.
11600 // Only 1 CPUDispatch function is allowed, this will make it go through
11601 // the redeclaration errors.
11602 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11603 CurFD->hasAttr<CPUDispatchAttr>()) {
11604 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11605 std::equal(
11606 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11607 NewCPUDisp->cpus_begin(),
11608 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11609 return Cur->getName() == New->getName();
11610 })) {
11611 NewFD->setIsMultiVersion();
11612 Redeclaration = true;
11613 OldDecl = ND;
11614 return false;
11617 // If the declarations don't match, this is an error condition.
11618 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11619 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11620 NewFD->setInvalidDecl();
11621 return true;
11623 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11624 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11625 std::equal(
11626 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11627 NewCPUSpec->cpus_begin(),
11628 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11629 return Cur->getName() == New->getName();
11630 })) {
11631 NewFD->setIsMultiVersion();
11632 Redeclaration = true;
11633 OldDecl = ND;
11634 return false;
11637 // Only 1 version of CPUSpecific is allowed for each CPU.
11638 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11639 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11640 if (CurII == NewII) {
11641 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11642 << NewII;
11643 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11644 NewFD->setInvalidDecl();
11645 return true;
11650 break;
11655 // Else, this is simply a non-redecl case. Checking the 'value' is only
11656 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11657 // handled in the attribute adding step.
11658 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11659 NewMVKind == MultiVersionKind::Target) &&
11660 CheckMultiVersionValue(S, NewFD)) {
11661 NewFD->setInvalidDecl();
11662 return true;
11665 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11666 !OldFD->isMultiVersion(), NewMVKind)) {
11667 NewFD->setInvalidDecl();
11668 return true;
11671 // Permit forward declarations in the case where these two are compatible.
11672 if (!OldFD->isMultiVersion()) {
11673 OldFD->setIsMultiVersion();
11674 NewFD->setIsMultiVersion();
11675 Redeclaration = true;
11676 OldDecl = OldFD;
11677 return false;
11680 NewFD->setIsMultiVersion();
11681 Redeclaration = false;
11682 OldDecl = nullptr;
11683 Previous.clear();
11684 return false;
11687 /// Check the validity of a mulitversion function declaration.
11688 /// Also sets the multiversion'ness' of the function itself.
11690 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11692 /// Returns true if there was an error, false otherwise.
11693 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
11694 bool &Redeclaration, NamedDecl *&OldDecl,
11695 LookupResult &Previous) {
11696 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11697 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11698 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11699 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11700 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11701 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11703 // Main isn't allowed to become a multiversion function, however it IS
11704 // permitted to have 'main' be marked with the 'target' optimization hint,
11705 // for 'target_version' only default is allowed.
11706 if (NewFD->isMain()) {
11707 if (MVKind != MultiVersionKind::None &&
11708 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11709 !(MVKind == MultiVersionKind::TargetVersion &&
11710 NewTVA->isDefaultVersion())) {
11711 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11712 NewFD->setInvalidDecl();
11713 return true;
11715 return false;
11718 // Target attribute on AArch64 is not used for multiversioning
11719 if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64())
11720 return false;
11722 if (!OldDecl || !OldDecl->getAsFunction() ||
11723 OldDecl->getDeclContext()->getRedeclContext() !=
11724 NewFD->getDeclContext()->getRedeclContext()) {
11725 // If there's no previous declaration, AND this isn't attempting to cause
11726 // multiversioning, this isn't an error condition.
11727 if (MVKind == MultiVersionKind::None)
11728 return false;
11729 return CheckMultiVersionFirstFunction(S, NewFD);
11732 FunctionDecl *OldFD = OldDecl->getAsFunction();
11734 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
11735 if (NewTVA || !OldFD->getAttr<TargetVersionAttr>())
11736 return false;
11737 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
11738 // Multiversion declaration doesn't have prototype.
11739 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
11740 NewFD->setInvalidDecl();
11741 } else {
11742 // No "target_version" attribute is equivalent to "default" attribute.
11743 NewFD->addAttr(TargetVersionAttr::CreateImplicit(
11744 S.Context, "default", NewFD->getSourceRange()));
11745 NewFD->setIsMultiVersion();
11746 OldFD->setIsMultiVersion();
11747 OldDecl = OldFD;
11748 Redeclaration = true;
11750 return true;
11753 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11754 // for target_clones and target_version.
11755 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11756 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
11757 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
11758 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11759 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
11760 NewFD->setInvalidDecl();
11761 return true;
11764 if (!OldFD->isMultiVersion()) {
11765 switch (MVKind) {
11766 case MultiVersionKind::Target:
11767 case MultiVersionKind::TargetVersion:
11768 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
11769 OldDecl, Previous);
11770 case MultiVersionKind::TargetClones:
11771 if (OldFD->isUsed(false)) {
11772 NewFD->setInvalidDecl();
11773 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11775 OldFD->setIsMultiVersion();
11776 break;
11778 case MultiVersionKind::CPUDispatch:
11779 case MultiVersionKind::CPUSpecific:
11780 case MultiVersionKind::None:
11781 break;
11785 // At this point, we have a multiversion function decl (in OldFD) AND an
11786 // appropriate attribute in the current function decl. Resolve that these are
11787 // still compatible with previous declarations.
11788 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
11789 NewCPUSpec, NewClones, Redeclaration,
11790 OldDecl, Previous);
11793 /// Perform semantic checking of a new function declaration.
11795 /// Performs semantic analysis of the new function declaration
11796 /// NewFD. This routine performs all semantic checking that does not
11797 /// require the actual declarator involved in the declaration, and is
11798 /// used both for the declaration of functions as they are parsed
11799 /// (called via ActOnDeclarator) and for the declaration of functions
11800 /// that have been instantiated via C++ template instantiation (called
11801 /// via InstantiateDecl).
11803 /// \param IsMemberSpecialization whether this new function declaration is
11804 /// a member specialization (that replaces any definition provided by the
11805 /// previous declaration).
11807 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11809 /// \returns true if the function declaration is a redeclaration.
11810 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
11811 LookupResult &Previous,
11812 bool IsMemberSpecialization,
11813 bool DeclIsDefn) {
11814 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11815 "Variably modified return types are not handled here");
11817 // Determine whether the type of this function should be merged with
11818 // a previous visible declaration. This never happens for functions in C++,
11819 // and always happens in C if the previous declaration was visible.
11820 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11821 !Previous.isShadowed();
11823 bool Redeclaration = false;
11824 NamedDecl *OldDecl = nullptr;
11825 bool MayNeedOverloadableChecks = false;
11827 // Merge or overload the declaration with an existing declaration of
11828 // the same name, if appropriate.
11829 if (!Previous.empty()) {
11830 // Determine whether NewFD is an overload of PrevDecl or
11831 // a declaration that requires merging. If it's an overload,
11832 // there's no more work to do here; we'll just add the new
11833 // function to the scope.
11834 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11835 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11836 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11837 Redeclaration = true;
11838 OldDecl = Candidate;
11840 } else {
11841 MayNeedOverloadableChecks = true;
11842 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11843 /*NewIsUsingDecl*/ false)) {
11844 case Ovl_Match:
11845 Redeclaration = true;
11846 break;
11848 case Ovl_NonFunction:
11849 Redeclaration = true;
11850 break;
11852 case Ovl_Overload:
11853 Redeclaration = false;
11854 break;
11859 // Check for a previous extern "C" declaration with this name.
11860 if (!Redeclaration &&
11861 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
11862 if (!Previous.empty()) {
11863 // This is an extern "C" declaration with the same name as a previous
11864 // declaration, and thus redeclares that entity...
11865 Redeclaration = true;
11866 OldDecl = Previous.getFoundDecl();
11867 MergeTypeWithPrevious = false;
11869 // ... except in the presence of __attribute__((overloadable)).
11870 if (OldDecl->hasAttr<OverloadableAttr>() ||
11871 NewFD->hasAttr<OverloadableAttr>()) {
11872 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11873 MayNeedOverloadableChecks = true;
11874 Redeclaration = false;
11875 OldDecl = nullptr;
11881 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11882 return Redeclaration;
11884 // PPC MMA non-pointer types are not allowed as function return types.
11885 if (Context.getTargetInfo().getTriple().isPPC64() &&
11886 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11887 NewFD->setInvalidDecl();
11890 // C++11 [dcl.constexpr]p8:
11891 // A constexpr specifier for a non-static member function that is not
11892 // a constructor declares that member function to be const.
11894 // This needs to be delayed until we know whether this is an out-of-line
11895 // definition of a static member function.
11897 // This rule is not present in C++1y, so we produce a backwards
11898 // compatibility warning whenever it happens in C++11.
11899 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11900 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11901 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11902 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11903 CXXMethodDecl *OldMD = nullptr;
11904 if (OldDecl)
11905 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11906 if (!OldMD || !OldMD->isStatic()) {
11907 const FunctionProtoType *FPT =
11908 MD->getType()->castAs<FunctionProtoType>();
11909 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11910 EPI.TypeQuals.addConst();
11911 MD->setType(Context.getFunctionType(FPT->getReturnType(),
11912 FPT->getParamTypes(), EPI));
11914 // Warn that we did this, if we're not performing template instantiation.
11915 // In that case, we'll have warned already when the template was defined.
11916 if (!inTemplateInstantiation()) {
11917 SourceLocation AddConstLoc;
11918 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11919 .IgnoreParens().getAs<FunctionTypeLoc>())
11920 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11922 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11923 << FixItHint::CreateInsertion(AddConstLoc, " const");
11928 if (Redeclaration) {
11929 // NewFD and OldDecl represent declarations that need to be
11930 // merged.
11931 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11932 DeclIsDefn)) {
11933 NewFD->setInvalidDecl();
11934 return Redeclaration;
11937 Previous.clear();
11938 Previous.addDecl(OldDecl);
11940 if (FunctionTemplateDecl *OldTemplateDecl =
11941 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11942 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11943 FunctionTemplateDecl *NewTemplateDecl
11944 = NewFD->getDescribedFunctionTemplate();
11945 assert(NewTemplateDecl && "Template/non-template mismatch");
11947 // The call to MergeFunctionDecl above may have created some state in
11948 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11949 // can add it as a redeclaration.
11950 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11952 NewFD->setPreviousDeclaration(OldFD);
11953 if (NewFD->isCXXClassMember()) {
11954 NewFD->setAccess(OldTemplateDecl->getAccess());
11955 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11958 // If this is an explicit specialization of a member that is a function
11959 // template, mark it as a member specialization.
11960 if (IsMemberSpecialization &&
11961 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11962 NewTemplateDecl->setMemberSpecialization();
11963 assert(OldTemplateDecl->isMemberSpecialization());
11964 // Explicit specializations of a member template do not inherit deleted
11965 // status from the parent member template that they are specializing.
11966 if (OldFD->isDeleted()) {
11967 // FIXME: This assert will not hold in the presence of modules.
11968 assert(OldFD->getCanonicalDecl() == OldFD);
11969 // FIXME: We need an update record for this AST mutation.
11970 OldFD->setDeletedAsWritten(false);
11974 } else {
11975 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11976 auto *OldFD = cast<FunctionDecl>(OldDecl);
11977 // This needs to happen first so that 'inline' propagates.
11978 NewFD->setPreviousDeclaration(OldFD);
11979 if (NewFD->isCXXClassMember())
11980 NewFD->setAccess(OldFD->getAccess());
11983 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11984 !NewFD->getAttr<OverloadableAttr>()) {
11985 assert((Previous.empty() ||
11986 llvm::any_of(Previous,
11987 [](const NamedDecl *ND) {
11988 return ND->hasAttr<OverloadableAttr>();
11989 })) &&
11990 "Non-redecls shouldn't happen without overloadable present");
11992 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11993 const auto *FD = dyn_cast<FunctionDecl>(ND);
11994 return FD && !FD->hasAttr<OverloadableAttr>();
11997 if (OtherUnmarkedIter != Previous.end()) {
11998 Diag(NewFD->getLocation(),
11999 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12000 Diag((*OtherUnmarkedIter)->getLocation(),
12001 diag::note_attribute_overloadable_prev_overload)
12002 << false;
12004 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12008 if (LangOpts.OpenMP)
12009 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
12011 // Semantic checking for this function declaration (in isolation).
12013 if (getLangOpts().CPlusPlus) {
12014 // C++-specific checks.
12015 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12016 CheckConstructor(Constructor);
12017 } else if (CXXDestructorDecl *Destructor =
12018 dyn_cast<CXXDestructorDecl>(NewFD)) {
12019 // We check here for invalid destructor names.
12020 // If we have a friend destructor declaration that is dependent, we can't
12021 // diagnose right away because cases like this are still valid:
12022 // template <class T> struct A { friend T::X::~Y(); };
12023 // struct B { struct Y { ~Y(); }; using X = Y; };
12024 // template struct A<B>;
12025 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
12026 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12027 CXXRecordDecl *Record = Destructor->getParent();
12028 QualType ClassType = Context.getTypeDeclType(Record);
12030 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
12031 Context.getCanonicalType(ClassType));
12032 if (NewFD->getDeclName() != Name) {
12033 Diag(NewFD->getLocation(), diag::err_destructor_name);
12034 NewFD->setInvalidDecl();
12035 return Redeclaration;
12038 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12039 if (auto *TD = Guide->getDescribedFunctionTemplate())
12040 CheckDeductionGuideTemplate(TD);
12042 // A deduction guide is not on the list of entities that can be
12043 // explicitly specialized.
12044 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12045 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12046 << /*explicit specialization*/ 1;
12049 // Find any virtual functions that this function overrides.
12050 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12051 if (!Method->isFunctionTemplateSpecialization() &&
12052 !Method->getDescribedFunctionTemplate() &&
12053 Method->isCanonicalDecl()) {
12054 AddOverriddenMethods(Method->getParent(), Method);
12056 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12057 // C++2a [class.virtual]p6
12058 // A virtual method shall not have a requires-clause.
12059 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
12060 diag::err_constrained_virtual_method);
12062 if (Method->isStatic())
12063 checkThisInStaticMemberFunctionType(Method);
12066 // C++20: dcl.decl.general p4:
12067 // The optional requires-clause ([temp.pre]) in an init-declarator or
12068 // member-declarator shall be present only if the declarator declares a
12069 // templated function ([dcl.fct]).
12070 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
12071 // [temp.pre]/8:
12072 // An entity is templated if it is
12073 // - a template,
12074 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
12075 // templated entity,
12076 // - a member of a templated entity,
12077 // - an enumerator for an enumeration that is a templated entity, or
12078 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
12079 // appearing in the declaration of a templated entity. [Note 6: A local
12080 // class, a local or block variable, or a friend function defined in a
12081 // templated entity is a templated entity. — end note]
12083 // A templated function is a function template or a function that is
12084 // templated. A templated class is a class template or a class that is
12085 // templated. A templated variable is a variable template or a variable
12086 // that is templated.
12088 if (!NewFD->getDescribedFunctionTemplate() && // -a template
12089 // defined... in a templated entity
12090 !(DeclIsDefn && NewFD->isTemplated()) &&
12091 // a member of a templated entity
12092 !(isa<CXXMethodDecl>(NewFD) && NewFD->isTemplated()) &&
12093 // Don't complain about instantiations, they've already had these
12094 // rules + others enforced.
12095 !NewFD->isTemplateInstantiation()) {
12096 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
12100 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12101 ActOnConversionDeclarator(Conversion);
12103 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12104 if (NewFD->isOverloadedOperator() &&
12105 CheckOverloadedOperatorDeclaration(NewFD)) {
12106 NewFD->setInvalidDecl();
12107 return Redeclaration;
12110 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12111 if (NewFD->getLiteralIdentifier() &&
12112 CheckLiteralOperatorDeclaration(NewFD)) {
12113 NewFD->setInvalidDecl();
12114 return Redeclaration;
12117 // In C++, check default arguments now that we have merged decls. Unless
12118 // the lexical context is the class, because in this case this is done
12119 // during delayed parsing anyway.
12120 if (!CurContext->isRecord())
12121 CheckCXXDefaultArguments(NewFD);
12123 // If this function is declared as being extern "C", then check to see if
12124 // the function returns a UDT (class, struct, or union type) that is not C
12125 // compatible, and if it does, warn the user.
12126 // But, issue any diagnostic on the first declaration only.
12127 if (Previous.empty() && NewFD->isExternC()) {
12128 QualType R = NewFD->getReturnType();
12129 if (R->isIncompleteType() && !R->isVoidType())
12130 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12131 << NewFD << R;
12132 else if (!R.isPODType(Context) && !R->isVoidType() &&
12133 !R->isObjCObjectPointerType())
12134 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12137 // C++1z [dcl.fct]p6:
12138 // [...] whether the function has a non-throwing exception-specification
12139 // [is] part of the function type
12141 // This results in an ABI break between C++14 and C++17 for functions whose
12142 // declared type includes an exception-specification in a parameter or
12143 // return type. (Exception specifications on the function itself are OK in
12144 // most cases, and exception specifications are not permitted in most other
12145 // contexts where they could make it into a mangling.)
12146 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12147 auto HasNoexcept = [&](QualType T) -> bool {
12148 // Strip off declarator chunks that could be between us and a function
12149 // type. We don't need to look far, exception specifications are very
12150 // restricted prior to C++17.
12151 if (auto *RT = T->getAs<ReferenceType>())
12152 T = RT->getPointeeType();
12153 else if (T->isAnyPointerType())
12154 T = T->getPointeeType();
12155 else if (auto *MPT = T->getAs<MemberPointerType>())
12156 T = MPT->getPointeeType();
12157 if (auto *FPT = T->getAs<FunctionProtoType>())
12158 if (FPT->isNothrow())
12159 return true;
12160 return false;
12163 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12164 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12165 for (QualType T : FPT->param_types())
12166 AnyNoexcept |= HasNoexcept(T);
12167 if (AnyNoexcept)
12168 Diag(NewFD->getLocation(),
12169 diag::warn_cxx17_compat_exception_spec_in_signature)
12170 << NewFD;
12173 if (!Redeclaration && LangOpts.CUDA)
12174 checkCUDATargetOverload(NewFD, Previous);
12177 // Check if the function definition uses any AArch64 SME features without
12178 // having the '+sme' feature enabled.
12179 if (DeclIsDefn) {
12180 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12181 bool UsesZA = NewFD->hasAttr<ArmNewZAAttr>();
12182 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12183 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12184 UsesSM |=
12185 EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
12186 UsesZA |= EPI.AArch64SMEAttributes & FunctionType::SME_PStateZASharedMask;
12189 if (UsesSM || UsesZA) {
12190 llvm::StringMap<bool> FeatureMap;
12191 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12192 if (!FeatureMap.contains("sme")) {
12193 if (UsesSM)
12194 Diag(NewFD->getLocation(),
12195 diag::err_sme_definition_using_sm_in_non_sme_target);
12196 else
12197 Diag(NewFD->getLocation(),
12198 diag::err_sme_definition_using_za_in_non_sme_target);
12203 return Redeclaration;
12206 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
12207 // C++11 [basic.start.main]p3:
12208 // A program that [...] declares main to be inline, static or
12209 // constexpr is ill-formed.
12210 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12211 // appear in a declaration of main.
12212 // static main is not an error under C99, but we should warn about it.
12213 // We accept _Noreturn main as an extension.
12214 if (FD->getStorageClass() == SC_Static)
12215 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
12216 ? diag::err_static_main : diag::warn_static_main)
12217 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12218 if (FD->isInlineSpecified())
12219 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12220 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
12221 if (DS.isNoreturnSpecified()) {
12222 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12223 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12224 Diag(NoreturnLoc, diag::ext_noreturn_main);
12225 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12226 << FixItHint::CreateRemoval(NoreturnRange);
12228 if (FD->isConstexpr()) {
12229 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12230 << FD->isConsteval()
12231 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
12232 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
12235 if (getLangOpts().OpenCL) {
12236 Diag(FD->getLocation(), diag::err_opencl_no_main)
12237 << FD->hasAttr<OpenCLKernelAttr>();
12238 FD->setInvalidDecl();
12239 return;
12242 // Functions named main in hlsl are default entries, but don't have specific
12243 // signatures they are required to conform to.
12244 if (getLangOpts().HLSL)
12245 return;
12247 QualType T = FD->getType();
12248 assert(T->isFunctionType() && "function decl is not of function type");
12249 const FunctionType* FT = T->castAs<FunctionType>();
12251 // Set default calling convention for main()
12252 if (FT->getCallConv() != CC_C) {
12253 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12254 FD->setType(QualType(FT, 0));
12255 T = Context.getCanonicalType(FD->getType());
12258 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12259 // In C with GNU extensions we allow main() to have non-integer return
12260 // type, but we should warn about the extension, and we disable the
12261 // implicit-return-zero rule.
12263 // GCC in C mode accepts qualified 'int'.
12264 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12265 FD->setHasImplicitReturnZero(true);
12266 else {
12267 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12268 SourceRange RTRange = FD->getReturnTypeSourceRange();
12269 if (RTRange.isValid())
12270 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12271 << FixItHint::CreateReplacement(RTRange, "int");
12273 } else {
12274 // In C and C++, main magically returns 0 if you fall off the end;
12275 // set the flag which tells us that.
12276 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12278 // All the standards say that main() should return 'int'.
12279 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12280 FD->setHasImplicitReturnZero(true);
12281 else {
12282 // Otherwise, this is just a flat-out error.
12283 SourceRange RTRange = FD->getReturnTypeSourceRange();
12284 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12285 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12286 : FixItHint());
12287 FD->setInvalidDecl(true);
12291 // Treat protoless main() as nullary.
12292 if (isa<FunctionNoProtoType>(FT)) return;
12294 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12295 unsigned nparams = FTP->getNumParams();
12296 assert(FD->getNumParams() == nparams);
12298 bool HasExtraParameters = (nparams > 3);
12300 if (FTP->isVariadic()) {
12301 Diag(FD->getLocation(), diag::ext_variadic_main);
12302 // FIXME: if we had information about the location of the ellipsis, we
12303 // could add a FixIt hint to remove it as a parameter.
12306 // Darwin passes an undocumented fourth argument of type char**. If
12307 // other platforms start sprouting these, the logic below will start
12308 // getting shifty.
12309 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12310 HasExtraParameters = false;
12312 if (HasExtraParameters) {
12313 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12314 FD->setInvalidDecl(true);
12315 nparams = 3;
12318 // FIXME: a lot of the following diagnostics would be improved
12319 // if we had some location information about types.
12321 QualType CharPP =
12322 Context.getPointerType(Context.getPointerType(Context.CharTy));
12323 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12325 for (unsigned i = 0; i < nparams; ++i) {
12326 QualType AT = FTP->getParamType(i);
12328 bool mismatch = true;
12330 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12331 mismatch = false;
12332 else if (Expected[i] == CharPP) {
12333 // As an extension, the following forms are okay:
12334 // char const **
12335 // char const * const *
12336 // char * const *
12338 QualifierCollector qs;
12339 const PointerType* PT;
12340 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12341 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12342 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12343 Context.CharTy)) {
12344 qs.removeConst();
12345 mismatch = !qs.empty();
12349 if (mismatch) {
12350 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12351 // TODO: suggest replacing given type with expected type
12352 FD->setInvalidDecl(true);
12356 if (nparams == 1 && !FD->isInvalidDecl()) {
12357 Diag(FD->getLocation(), diag::warn_main_one_arg);
12360 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12361 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12362 FD->setInvalidDecl();
12366 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12368 // Default calling convention for main and wmain is __cdecl
12369 if (FD->getName() == "main" || FD->getName() == "wmain")
12370 return false;
12372 // Default calling convention for MinGW is __cdecl
12373 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12374 if (T.isWindowsGNUEnvironment())
12375 return false;
12377 // Default calling convention for WinMain, wWinMain and DllMain
12378 // is __stdcall on 32 bit Windows
12379 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12380 return true;
12382 return false;
12385 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
12386 QualType T = FD->getType();
12387 assert(T->isFunctionType() && "function decl is not of function type");
12388 const FunctionType *FT = T->castAs<FunctionType>();
12390 // Set an implicit return of 'zero' if the function can return some integral,
12391 // enumeration, pointer or nullptr type.
12392 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
12393 FT->getReturnType()->isAnyPointerType() ||
12394 FT->getReturnType()->isNullPtrType())
12395 // DllMain is exempt because a return value of zero means it failed.
12396 if (FD->getName() != "DllMain")
12397 FD->setHasImplicitReturnZero(true);
12399 // Explicity specified calling conventions are applied to MSVC entry points
12400 if (!hasExplicitCallingConv(T)) {
12401 if (isDefaultStdCall(FD, *this)) {
12402 if (FT->getCallConv() != CC_X86StdCall) {
12403 FT = Context.adjustFunctionType(
12404 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
12405 FD->setType(QualType(FT, 0));
12407 } else if (FT->getCallConv() != CC_C) {
12408 FT = Context.adjustFunctionType(FT,
12409 FT->getExtInfo().withCallingConv(CC_C));
12410 FD->setType(QualType(FT, 0));
12414 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12415 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12416 FD->setInvalidDecl();
12420 void Sema::ActOnHLSLTopLevelFunction(FunctionDecl *FD) {
12421 auto &TargetInfo = getASTContext().getTargetInfo();
12423 if (FD->getName() != TargetInfo.getTargetOpts().HLSLEntry)
12424 return;
12426 StringRef Env = TargetInfo.getTriple().getEnvironmentName();
12427 HLSLShaderAttr::ShaderType ShaderType;
12428 if (HLSLShaderAttr::ConvertStrToShaderType(Env, ShaderType)) {
12429 if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) {
12430 // The entry point is already annotated - check that it matches the
12431 // triple.
12432 if (Shader->getType() != ShaderType) {
12433 Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
12434 << Shader;
12435 FD->setInvalidDecl();
12437 } else {
12438 // Implicitly add the shader attribute if the entry function isn't
12439 // explicitly annotated.
12440 FD->addAttr(HLSLShaderAttr::CreateImplicit(Context, ShaderType,
12441 FD->getBeginLoc()));
12443 } else {
12444 switch (TargetInfo.getTriple().getEnvironment()) {
12445 case llvm::Triple::UnknownEnvironment:
12446 case llvm::Triple::Library:
12447 break;
12448 default:
12449 llvm_unreachable("Unhandled environment in triple");
12454 void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
12455 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
12456 assert(ShaderAttr && "Entry point has no shader attribute");
12457 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12459 switch (ST) {
12460 case HLSLShaderAttr::Pixel:
12461 case HLSLShaderAttr::Vertex:
12462 case HLSLShaderAttr::Geometry:
12463 case HLSLShaderAttr::Hull:
12464 case HLSLShaderAttr::Domain:
12465 case HLSLShaderAttr::RayGeneration:
12466 case HLSLShaderAttr::Intersection:
12467 case HLSLShaderAttr::AnyHit:
12468 case HLSLShaderAttr::ClosestHit:
12469 case HLSLShaderAttr::Miss:
12470 case HLSLShaderAttr::Callable:
12471 if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) {
12472 DiagnoseHLSLAttrStageMismatch(NT, ST,
12473 {HLSLShaderAttr::Compute,
12474 HLSLShaderAttr::Amplification,
12475 HLSLShaderAttr::Mesh});
12476 FD->setInvalidDecl();
12478 break;
12480 case HLSLShaderAttr::Compute:
12481 case HLSLShaderAttr::Amplification:
12482 case HLSLShaderAttr::Mesh:
12483 if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
12484 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
12485 << HLSLShaderAttr::ConvertShaderTypeToStr(ST);
12486 FD->setInvalidDecl();
12488 break;
12491 for (ParmVarDecl *Param : FD->parameters()) {
12492 if (const auto *AnnotationAttr = Param->getAttr<HLSLAnnotationAttr>()) {
12493 CheckHLSLSemanticAnnotation(FD, Param, AnnotationAttr);
12494 } else {
12495 // FIXME: Handle struct parameters where annotations are on struct fields.
12496 // See: https://github.com/llvm/llvm-project/issues/57875
12497 Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
12498 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
12499 FD->setInvalidDecl();
12502 // FIXME: Verify return type semantic annotation.
12505 void Sema::CheckHLSLSemanticAnnotation(
12506 FunctionDecl *EntryPoint, const Decl *Param,
12507 const HLSLAnnotationAttr *AnnotationAttr) {
12508 auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>();
12509 assert(ShaderAttr && "Entry point has no shader attribute");
12510 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType();
12512 switch (AnnotationAttr->getKind()) {
12513 case attr::HLSLSV_DispatchThreadID:
12514 case attr::HLSLSV_GroupIndex:
12515 if (ST == HLSLShaderAttr::Compute)
12516 return;
12517 DiagnoseHLSLAttrStageMismatch(AnnotationAttr, ST,
12518 {HLSLShaderAttr::Compute});
12519 break;
12520 default:
12521 llvm_unreachable("Unknown HLSLAnnotationAttr");
12525 void Sema::DiagnoseHLSLAttrStageMismatch(
12526 const Attr *A, HLSLShaderAttr::ShaderType Stage,
12527 std::initializer_list<HLSLShaderAttr::ShaderType> AllowedStages) {
12528 SmallVector<StringRef, 8> StageStrings;
12529 llvm::transform(AllowedStages, std::back_inserter(StageStrings),
12530 [](HLSLShaderAttr::ShaderType ST) {
12531 return StringRef(
12532 HLSLShaderAttr::ConvertShaderTypeToStr(ST));
12534 Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
12535 << A << HLSLShaderAttr::ConvertShaderTypeToStr(Stage)
12536 << (AllowedStages.size() != 1) << join(StageStrings, ", ");
12539 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
12540 // FIXME: Need strict checking. In C89, we need to check for
12541 // any assignment, increment, decrement, function-calls, or
12542 // commas outside of a sizeof. In C99, it's the same list,
12543 // except that the aforementioned are allowed in unevaluated
12544 // expressions. Everything else falls under the
12545 // "may accept other forms of constant expressions" exception.
12547 // Regular C++ code will not end up here (exceptions: language extensions,
12548 // OpenCL C++ etc), so the constant expression rules there don't matter.
12549 if (Init->isValueDependent()) {
12550 assert(Init->containsErrors() &&
12551 "Dependent code should only occur in error-recovery path.");
12552 return true;
12554 const Expr *Culprit;
12555 if (Init->isConstantInitializer(Context, false, &Culprit))
12556 return false;
12557 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
12558 << Culprit->getSourceRange();
12559 return true;
12562 namespace {
12563 // Visits an initialization expression to see if OrigDecl is evaluated in
12564 // its own initialization and throws a warning if it does.
12565 class SelfReferenceChecker
12566 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12567 Sema &S;
12568 Decl *OrigDecl;
12569 bool isRecordType;
12570 bool isPODType;
12571 bool isReferenceType;
12573 bool isInitList;
12574 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12576 public:
12577 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
12579 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12580 S(S), OrigDecl(OrigDecl) {
12581 isPODType = false;
12582 isRecordType = false;
12583 isReferenceType = false;
12584 isInitList = false;
12585 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12586 isPODType = VD->getType().isPODType(S.Context);
12587 isRecordType = VD->getType()->isRecordType();
12588 isReferenceType = VD->getType()->isReferenceType();
12592 // For most expressions, just call the visitor. For initializer lists,
12593 // track the index of the field being initialized since fields are
12594 // initialized in order allowing use of previously initialized fields.
12595 void CheckExpr(Expr *E) {
12596 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12597 if (!InitList) {
12598 Visit(E);
12599 return;
12602 // Track and increment the index here.
12603 isInitList = true;
12604 InitFieldIndex.push_back(0);
12605 for (auto *Child : InitList->children()) {
12606 CheckExpr(cast<Expr>(Child));
12607 ++InitFieldIndex.back();
12609 InitFieldIndex.pop_back();
12612 // Returns true if MemberExpr is checked and no further checking is needed.
12613 // Returns false if additional checking is required.
12614 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12615 llvm::SmallVector<FieldDecl*, 4> Fields;
12616 Expr *Base = E;
12617 bool ReferenceField = false;
12619 // Get the field members used.
12620 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12621 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12622 if (!FD)
12623 return false;
12624 Fields.push_back(FD);
12625 if (FD->getType()->isReferenceType())
12626 ReferenceField = true;
12627 Base = ME->getBase()->IgnoreParenImpCasts();
12630 // Keep checking only if the base Decl is the same.
12631 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12632 if (!DRE || DRE->getDecl() != OrigDecl)
12633 return false;
12635 // A reference field can be bound to an unininitialized field.
12636 if (CheckReference && !ReferenceField)
12637 return true;
12639 // Convert FieldDecls to their index number.
12640 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12641 for (const FieldDecl *I : llvm::reverse(Fields))
12642 UsedFieldIndex.push_back(I->getFieldIndex());
12644 // See if a warning is needed by checking the first difference in index
12645 // numbers. If field being used has index less than the field being
12646 // initialized, then the use is safe.
12647 for (auto UsedIter = UsedFieldIndex.begin(),
12648 UsedEnd = UsedFieldIndex.end(),
12649 OrigIter = InitFieldIndex.begin(),
12650 OrigEnd = InitFieldIndex.end();
12651 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12652 if (*UsedIter < *OrigIter)
12653 return true;
12654 if (*UsedIter > *OrigIter)
12655 break;
12658 // TODO: Add a different warning which will print the field names.
12659 HandleDeclRefExpr(DRE);
12660 return true;
12663 // For most expressions, the cast is directly above the DeclRefExpr.
12664 // For conditional operators, the cast can be outside the conditional
12665 // operator if both expressions are DeclRefExpr's.
12666 void HandleValue(Expr *E) {
12667 E = E->IgnoreParens();
12668 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12669 HandleDeclRefExpr(DRE);
12670 return;
12673 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12674 Visit(CO->getCond());
12675 HandleValue(CO->getTrueExpr());
12676 HandleValue(CO->getFalseExpr());
12677 return;
12680 if (BinaryConditionalOperator *BCO =
12681 dyn_cast<BinaryConditionalOperator>(E)) {
12682 Visit(BCO->getCond());
12683 HandleValue(BCO->getFalseExpr());
12684 return;
12687 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12688 HandleValue(OVE->getSourceExpr());
12689 return;
12692 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12693 if (BO->getOpcode() == BO_Comma) {
12694 Visit(BO->getLHS());
12695 HandleValue(BO->getRHS());
12696 return;
12700 if (isa<MemberExpr>(E)) {
12701 if (isInitList) {
12702 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12703 false /*CheckReference*/))
12704 return;
12707 Expr *Base = E->IgnoreParenImpCasts();
12708 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12709 // Check for static member variables and don't warn on them.
12710 if (!isa<FieldDecl>(ME->getMemberDecl()))
12711 return;
12712 Base = ME->getBase()->IgnoreParenImpCasts();
12714 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12715 HandleDeclRefExpr(DRE);
12716 return;
12719 Visit(E);
12722 // Reference types not handled in HandleValue are handled here since all
12723 // uses of references are bad, not just r-value uses.
12724 void VisitDeclRefExpr(DeclRefExpr *E) {
12725 if (isReferenceType)
12726 HandleDeclRefExpr(E);
12729 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12730 if (E->getCastKind() == CK_LValueToRValue) {
12731 HandleValue(E->getSubExpr());
12732 return;
12735 Inherited::VisitImplicitCastExpr(E);
12738 void VisitMemberExpr(MemberExpr *E) {
12739 if (isInitList) {
12740 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12741 return;
12744 // Don't warn on arrays since they can be treated as pointers.
12745 if (E->getType()->canDecayToPointerType()) return;
12747 // Warn when a non-static method call is followed by non-static member
12748 // field accesses, which is followed by a DeclRefExpr.
12749 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12750 bool Warn = (MD && !MD->isStatic());
12751 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12752 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12753 if (!isa<FieldDecl>(ME->getMemberDecl()))
12754 Warn = false;
12755 Base = ME->getBase()->IgnoreParenImpCasts();
12758 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12759 if (Warn)
12760 HandleDeclRefExpr(DRE);
12761 return;
12764 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12765 // Visit that expression.
12766 Visit(Base);
12769 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12770 Expr *Callee = E->getCallee();
12772 if (isa<UnresolvedLookupExpr>(Callee))
12773 return Inherited::VisitCXXOperatorCallExpr(E);
12775 Visit(Callee);
12776 for (auto Arg: E->arguments())
12777 HandleValue(Arg->IgnoreParenImpCasts());
12780 void VisitUnaryOperator(UnaryOperator *E) {
12781 // For POD record types, addresses of its own members are well-defined.
12782 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12783 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12784 if (!isPODType)
12785 HandleValue(E->getSubExpr());
12786 return;
12789 if (E->isIncrementDecrementOp()) {
12790 HandleValue(E->getSubExpr());
12791 return;
12794 Inherited::VisitUnaryOperator(E);
12797 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12799 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12800 if (E->getConstructor()->isCopyConstructor()) {
12801 Expr *ArgExpr = E->getArg(0);
12802 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12803 if (ILE->getNumInits() == 1)
12804 ArgExpr = ILE->getInit(0);
12805 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12806 if (ICE->getCastKind() == CK_NoOp)
12807 ArgExpr = ICE->getSubExpr();
12808 HandleValue(ArgExpr);
12809 return;
12811 Inherited::VisitCXXConstructExpr(E);
12814 void VisitCallExpr(CallExpr *E) {
12815 // Treat std::move as a use.
12816 if (E->isCallToStdMove()) {
12817 HandleValue(E->getArg(0));
12818 return;
12821 Inherited::VisitCallExpr(E);
12824 void VisitBinaryOperator(BinaryOperator *E) {
12825 if (E->isCompoundAssignmentOp()) {
12826 HandleValue(E->getLHS());
12827 Visit(E->getRHS());
12828 return;
12831 Inherited::VisitBinaryOperator(E);
12834 // A custom visitor for BinaryConditionalOperator is needed because the
12835 // regular visitor would check the condition and true expression separately
12836 // but both point to the same place giving duplicate diagnostics.
12837 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12838 Visit(E->getCond());
12839 Visit(E->getFalseExpr());
12842 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12843 Decl* ReferenceDecl = DRE->getDecl();
12844 if (OrigDecl != ReferenceDecl) return;
12845 unsigned diag;
12846 if (isReferenceType) {
12847 diag = diag::warn_uninit_self_reference_in_reference_init;
12848 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12849 diag = diag::warn_static_self_reference_in_init;
12850 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12851 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12852 DRE->getDecl()->getType()->isRecordType()) {
12853 diag = diag::warn_uninit_self_reference_in_init;
12854 } else {
12855 // Local variables will be handled by the CFG analysis.
12856 return;
12859 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12860 S.PDiag(diag)
12861 << DRE->getDecl() << OrigDecl->getLocation()
12862 << DRE->getSourceRange());
12866 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12867 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12868 bool DirectInit) {
12869 // Parameters arguments are occassionially constructed with itself,
12870 // for instance, in recursive functions. Skip them.
12871 if (isa<ParmVarDecl>(OrigDecl))
12872 return;
12874 E = E->IgnoreParens();
12876 // Skip checking T a = a where T is not a record or reference type.
12877 // Doing so is a way to silence uninitialized warnings.
12878 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12879 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12880 if (ICE->getCastKind() == CK_LValueToRValue)
12881 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12882 if (DRE->getDecl() == OrigDecl)
12883 return;
12885 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12887 } // end anonymous namespace
12889 namespace {
12890 // Simple wrapper to add the name of a variable or (if no variable is
12891 // available) a DeclarationName into a diagnostic.
12892 struct VarDeclOrName {
12893 VarDecl *VDecl;
12894 DeclarationName Name;
12896 friend const Sema::SemaDiagnosticBuilder &
12897 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12898 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12901 } // end anonymous namespace
12903 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
12904 DeclarationName Name, QualType Type,
12905 TypeSourceInfo *TSI,
12906 SourceRange Range, bool DirectInit,
12907 Expr *Init) {
12908 bool IsInitCapture = !VDecl;
12909 assert((!VDecl || !VDecl->isInitCapture()) &&
12910 "init captures are expected to be deduced prior to initialization");
12912 VarDeclOrName VN{VDecl, Name};
12914 DeducedType *Deduced = Type->getContainedDeducedType();
12915 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12917 // Diagnose auto array declarations in C23, unless it's a supported extension.
12918 if (getLangOpts().C23 && Type->isArrayType() &&
12919 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12920 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12921 << (int)Deduced->getContainedAutoType()->getKeyword()
12922 << /*in array decl*/ 23 << Range;
12923 return QualType();
12926 // C++11 [dcl.spec.auto]p3
12927 if (!Init) {
12928 assert(VDecl && "no init for init capture deduction?");
12930 // Except for class argument deduction, and then for an initializing
12931 // declaration only, i.e. no static at class scope or extern.
12932 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12933 VDecl->hasExternalStorage() ||
12934 VDecl->isStaticDataMember()) {
12935 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12936 << VDecl->getDeclName() << Type;
12937 return QualType();
12941 ArrayRef<Expr*> DeduceInits;
12942 if (Init)
12943 DeduceInits = Init;
12945 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12946 if (DirectInit && PL)
12947 DeduceInits = PL->exprs();
12949 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12950 assert(VDecl && "non-auto type for init capture deduction?");
12951 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12952 InitializationKind Kind = InitializationKind::CreateForInit(
12953 VDecl->getLocation(), DirectInit, Init);
12954 // FIXME: Initialization should not be taking a mutable list of inits.
12955 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12956 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12957 InitsCopy);
12960 if (DirectInit) {
12961 if (auto *IL = dyn_cast<InitListExpr>(Init))
12962 DeduceInits = IL->inits();
12965 // Deduction only works if we have exactly one source expression.
12966 if (DeduceInits.empty()) {
12967 // It isn't possible to write this directly, but it is possible to
12968 // end up in this situation with "auto x(some_pack...);"
12969 Diag(Init->getBeginLoc(), IsInitCapture
12970 ? diag::err_init_capture_no_expression
12971 : diag::err_auto_var_init_no_expression)
12972 << VN << Type << Range;
12973 return QualType();
12976 if (DeduceInits.size() > 1) {
12977 Diag(DeduceInits[1]->getBeginLoc(),
12978 IsInitCapture ? diag::err_init_capture_multiple_expressions
12979 : diag::err_auto_var_init_multiple_expressions)
12980 << VN << Type << Range;
12981 return QualType();
12984 Expr *DeduceInit = DeduceInits[0];
12985 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12986 Diag(Init->getBeginLoc(), IsInitCapture
12987 ? diag::err_init_capture_paren_braces
12988 : diag::err_auto_var_init_paren_braces)
12989 << isa<InitListExpr>(Init) << VN << Type << Range;
12990 return QualType();
12993 // Expressions default to 'id' when we're in a debugger.
12994 bool DefaultedAnyToId = false;
12995 if (getLangOpts().DebuggerCastResultToId &&
12996 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12997 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12998 if (Result.isInvalid()) {
12999 return QualType();
13001 Init = Result.get();
13002 DefaultedAnyToId = true;
13005 // C++ [dcl.decomp]p1:
13006 // If the assignment-expression [...] has array type A and no ref-qualifier
13007 // is present, e has type cv A
13008 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13009 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13010 DeduceInit->getType()->isConstantArrayType())
13011 return Context.getQualifiedType(DeduceInit->getType(),
13012 Type.getQualifiers());
13014 QualType DeducedType;
13015 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13016 TemplateDeductionResult Result =
13017 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13018 if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) {
13019 if (!IsInitCapture)
13020 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13021 else if (isa<InitListExpr>(Init))
13022 Diag(Range.getBegin(),
13023 diag::err_init_capture_deduction_failure_from_init_list)
13024 << VN
13025 << (DeduceInit->getType().isNull() ? TSI->getType()
13026 : DeduceInit->getType())
13027 << DeduceInit->getSourceRange();
13028 else
13029 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13030 << VN << TSI->getType()
13031 << (DeduceInit->getType().isNull() ? TSI->getType()
13032 : DeduceInit->getType())
13033 << DeduceInit->getSourceRange();
13036 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13037 // 'id' instead of a specific object type prevents most of our usual
13038 // checks.
13039 // We only want to warn outside of template instantiations, though:
13040 // inside a template, the 'id' could have come from a parameter.
13041 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13042 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13043 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13044 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13047 return DeducedType;
13050 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
13051 Expr *Init) {
13052 assert(!Init || !Init->containsErrors());
13053 QualType DeducedType = deduceVarTypeFromInitializer(
13054 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13055 VDecl->getSourceRange(), DirectInit, Init);
13056 if (DeducedType.isNull()) {
13057 VDecl->setInvalidDecl();
13058 return true;
13061 VDecl->setType(DeducedType);
13062 assert(VDecl->isLinkageValid());
13064 // In ARC, infer lifetime.
13065 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
13066 VDecl->setInvalidDecl();
13068 if (getLangOpts().OpenCL)
13069 deduceOpenCLAddressSpace(VDecl);
13071 // If this is a redeclaration, check that the type we just deduced matches
13072 // the previously declared type.
13073 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13074 // We never need to merge the type, because we cannot form an incomplete
13075 // array of auto, nor deduce such a type.
13076 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13079 // Check the deduced type is valid for a variable declaration.
13080 CheckVariableDeclarationType(VDecl);
13081 return VDecl->isInvalidDecl();
13084 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
13085 SourceLocation Loc) {
13086 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13087 Init = EWC->getSubExpr();
13089 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13090 Init = CE->getSubExpr();
13092 QualType InitType = Init->getType();
13093 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13094 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
13095 "shouldn't be called if type doesn't have a non-trivial C struct");
13096 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13097 for (auto *I : ILE->inits()) {
13098 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13099 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13100 continue;
13101 SourceLocation SL = I->getExprLoc();
13102 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13104 return;
13107 if (isa<ImplicitValueInitExpr>(Init)) {
13108 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13109 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
13110 NTCUK_Init);
13111 } else {
13112 // Assume all other explicit initializers involving copying some existing
13113 // object.
13114 // TODO: ignore any explicit initializers where we can guarantee
13115 // copy-elision.
13116 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
13117 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
13121 namespace {
13123 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13124 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13125 // in the source code or implicitly by the compiler if it is in a union
13126 // defined in a system header and has non-trivial ObjC ownership
13127 // qualifications. We don't want those fields to participate in determining
13128 // whether the containing union is non-trivial.
13129 return FD->hasAttr<UnavailableAttr>();
13132 struct DiagNonTrivalCUnionDefaultInitializeVisitor
13133 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13134 void> {
13135 using Super =
13136 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13137 void>;
13139 DiagNonTrivalCUnionDefaultInitializeVisitor(
13140 QualType OrigTy, SourceLocation OrigLoc,
13141 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13142 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13144 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13145 const FieldDecl *FD, bool InNonTrivialUnion) {
13146 if (const auto *AT = S.Context.getAsArrayType(QT))
13147 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13148 InNonTrivialUnion);
13149 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13152 void visitARCStrong(QualType QT, const FieldDecl *FD,
13153 bool InNonTrivialUnion) {
13154 if (InNonTrivialUnion)
13155 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13156 << 1 << 0 << QT << FD->getName();
13159 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13160 if (InNonTrivialUnion)
13161 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13162 << 1 << 0 << QT << FD->getName();
13165 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13166 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13167 if (RD->isUnion()) {
13168 if (OrigLoc.isValid()) {
13169 bool IsUnion = false;
13170 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13171 IsUnion = OrigRD->isUnion();
13172 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13173 << 0 << OrigTy << IsUnion << UseContext;
13174 // Reset OrigLoc so that this diagnostic is emitted only once.
13175 OrigLoc = SourceLocation();
13177 InNonTrivialUnion = true;
13180 if (InNonTrivialUnion)
13181 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13182 << 0 << 0 << QT.getUnqualifiedType() << "";
13184 for (const FieldDecl *FD : RD->fields())
13185 if (!shouldIgnoreForRecordTriviality(FD))
13186 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13189 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13191 // The non-trivial C union type or the struct/union type that contains a
13192 // non-trivial C union.
13193 QualType OrigTy;
13194 SourceLocation OrigLoc;
13195 Sema::NonTrivialCUnionContext UseContext;
13196 Sema &S;
13199 struct DiagNonTrivalCUnionDestructedTypeVisitor
13200 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13201 using Super =
13202 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13204 DiagNonTrivalCUnionDestructedTypeVisitor(
13205 QualType OrigTy, SourceLocation OrigLoc,
13206 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13207 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13209 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13210 const FieldDecl *FD, bool InNonTrivialUnion) {
13211 if (const auto *AT = S.Context.getAsArrayType(QT))
13212 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13213 InNonTrivialUnion);
13214 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13217 void visitARCStrong(QualType QT, const FieldDecl *FD,
13218 bool InNonTrivialUnion) {
13219 if (InNonTrivialUnion)
13220 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13221 << 1 << 1 << QT << FD->getName();
13224 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13225 if (InNonTrivialUnion)
13226 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13227 << 1 << 1 << QT << FD->getName();
13230 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13231 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13232 if (RD->isUnion()) {
13233 if (OrigLoc.isValid()) {
13234 bool IsUnion = false;
13235 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13236 IsUnion = OrigRD->isUnion();
13237 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13238 << 1 << OrigTy << IsUnion << UseContext;
13239 // Reset OrigLoc so that this diagnostic is emitted only once.
13240 OrigLoc = SourceLocation();
13242 InNonTrivialUnion = true;
13245 if (InNonTrivialUnion)
13246 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13247 << 0 << 1 << QT.getUnqualifiedType() << "";
13249 for (const FieldDecl *FD : RD->fields())
13250 if (!shouldIgnoreForRecordTriviality(FD))
13251 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13254 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13255 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13256 bool InNonTrivialUnion) {}
13258 // The non-trivial C union type or the struct/union type that contains a
13259 // non-trivial C union.
13260 QualType OrigTy;
13261 SourceLocation OrigLoc;
13262 Sema::NonTrivialCUnionContext UseContext;
13263 Sema &S;
13266 struct DiagNonTrivalCUnionCopyVisitor
13267 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13268 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13270 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13271 Sema::NonTrivialCUnionContext UseContext,
13272 Sema &S)
13273 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13275 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13276 const FieldDecl *FD, bool InNonTrivialUnion) {
13277 if (const auto *AT = S.Context.getAsArrayType(QT))
13278 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13279 InNonTrivialUnion);
13280 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13283 void visitARCStrong(QualType QT, const FieldDecl *FD,
13284 bool InNonTrivialUnion) {
13285 if (InNonTrivialUnion)
13286 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13287 << 1 << 2 << QT << FD->getName();
13290 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13291 if (InNonTrivialUnion)
13292 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13293 << 1 << 2 << QT << FD->getName();
13296 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13297 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13298 if (RD->isUnion()) {
13299 if (OrigLoc.isValid()) {
13300 bool IsUnion = false;
13301 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13302 IsUnion = OrigRD->isUnion();
13303 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13304 << 2 << OrigTy << IsUnion << UseContext;
13305 // Reset OrigLoc so that this diagnostic is emitted only once.
13306 OrigLoc = SourceLocation();
13308 InNonTrivialUnion = true;
13311 if (InNonTrivialUnion)
13312 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13313 << 0 << 2 << QT.getUnqualifiedType() << "";
13315 for (const FieldDecl *FD : RD->fields())
13316 if (!shouldIgnoreForRecordTriviality(FD))
13317 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13320 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13321 const FieldDecl *FD, bool InNonTrivialUnion) {}
13322 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13323 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13324 bool InNonTrivialUnion) {}
13326 // The non-trivial C union type or the struct/union type that contains a
13327 // non-trivial C union.
13328 QualType OrigTy;
13329 SourceLocation OrigLoc;
13330 Sema::NonTrivialCUnionContext UseContext;
13331 Sema &S;
13334 } // namespace
13336 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
13337 NonTrivialCUnionContext UseContext,
13338 unsigned NonTrivialKind) {
13339 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13340 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
13341 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
13342 "shouldn't be called if type doesn't have a non-trivial C union");
13344 if ((NonTrivialKind & NTCUK_Init) &&
13345 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13346 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13347 .visit(QT, nullptr, false);
13348 if ((NonTrivialKind & NTCUK_Destruct) &&
13349 QT.hasNonTrivialToPrimitiveDestructCUnion())
13350 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13351 .visit(QT, nullptr, false);
13352 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13353 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13354 .visit(QT, nullptr, false);
13357 /// AddInitializerToDecl - Adds the initializer Init to the
13358 /// declaration dcl. If DirectInit is true, this is C++ direct
13359 /// initialization rather than copy initialization.
13360 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
13361 // If there is no declaration, there was an error parsing it. Just ignore
13362 // the initializer.
13363 if (!RealDecl || RealDecl->isInvalidDecl()) {
13364 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13365 return;
13368 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13369 // Pure-specifiers are handled in ActOnPureSpecifier.
13370 Diag(Method->getLocation(), diag::err_member_function_initialization)
13371 << Method->getDeclName() << Init->getSourceRange();
13372 Method->setInvalidDecl();
13373 return;
13376 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13377 if (!VDecl) {
13378 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13379 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13380 RealDecl->setInvalidDecl();
13381 return;
13384 // WebAssembly tables can't be used to initialise a variable.
13385 if (Init && !Init->getType().isNull() &&
13386 Init->getType()->isWebAssemblyTableType()) {
13387 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13388 VDecl->setInvalidDecl();
13389 return;
13392 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13393 if (VDecl->getType()->isUndeducedType()) {
13394 // Attempt typo correction early so that the type of the init expression can
13395 // be deduced based on the chosen correction if the original init contains a
13396 // TypoExpr.
13397 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
13398 if (!Res.isUsable()) {
13399 // There are unresolved typos in Init, just drop them.
13400 // FIXME: improve the recovery strategy to preserve the Init.
13401 RealDecl->setInvalidDecl();
13402 return;
13404 if (Res.get()->containsErrors()) {
13405 // Invalidate the decl as we don't know the type for recovery-expr yet.
13406 RealDecl->setInvalidDecl();
13407 VDecl->setInit(Res.get());
13408 return;
13410 Init = Res.get();
13412 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
13413 return;
13416 // dllimport cannot be used on variable definitions.
13417 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13418 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13419 VDecl->setInvalidDecl();
13420 return;
13423 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13424 // the identifier has external or internal linkage, the declaration shall
13425 // have no initializer for the identifier.
13426 // C++14 [dcl.init]p5 is the same restriction for C++.
13427 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13428 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13429 VDecl->setInvalidDecl();
13430 return;
13433 if (!VDecl->getType()->isDependentType()) {
13434 // A definition must end up with a complete type, which means it must be
13435 // complete with the restriction that an array type might be completed by
13436 // the initializer; note that later code assumes this restriction.
13437 QualType BaseDeclType = VDecl->getType();
13438 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13439 BaseDeclType = Array->getElementType();
13440 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13441 diag::err_typecheck_decl_incomplete_type)) {
13442 RealDecl->setInvalidDecl();
13443 return;
13446 // The variable can not have an abstract class type.
13447 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13448 diag::err_abstract_type_in_decl,
13449 AbstractVariableType))
13450 VDecl->setInvalidDecl();
13453 // C++ [module.import/6] external definitions are not permitted in header
13454 // units.
13455 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13456 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13457 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13458 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl)) {
13459 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13460 VDecl->setInvalidDecl();
13463 // If adding the initializer will turn this declaration into a definition,
13464 // and we already have a definition for this variable, diagnose or otherwise
13465 // handle the situation.
13466 if (VarDecl *Def = VDecl->getDefinition())
13467 if (Def != VDecl &&
13468 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13469 !VDecl->isThisDeclarationADemotedDefinition() &&
13470 checkVarDeclRedefinition(Def, VDecl))
13471 return;
13473 if (getLangOpts().CPlusPlus) {
13474 // C++ [class.static.data]p4
13475 // If a static data member is of const integral or const
13476 // enumeration type, its declaration in the class definition can
13477 // specify a constant-initializer which shall be an integral
13478 // constant expression (5.19). In that case, the member can appear
13479 // in integral constant expressions. The member shall still be
13480 // defined in a namespace scope if it is used in the program and the
13481 // namespace scope definition shall not contain an initializer.
13483 // We already performed a redefinition check above, but for static
13484 // data members we also need to check whether there was an in-class
13485 // declaration with an initializer.
13486 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13487 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13488 << VDecl->getDeclName();
13489 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13490 diag::note_previous_initializer)
13491 << 0;
13492 return;
13495 if (VDecl->hasLocalStorage())
13496 setFunctionHasBranchProtectedScope();
13498 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
13499 VDecl->setInvalidDecl();
13500 return;
13504 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13505 // a kernel function cannot be initialized."
13506 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13507 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13508 VDecl->setInvalidDecl();
13509 return;
13512 // The LoaderUninitialized attribute acts as a definition (of undef).
13513 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13514 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13515 VDecl->setInvalidDecl();
13516 return;
13519 // Get the decls type and save a reference for later, since
13520 // CheckInitializerTypes may change it.
13521 QualType DclT = VDecl->getType(), SavT = DclT;
13523 // Expressions default to 'id' when we're in a debugger
13524 // and we are assigning it to a variable of Objective-C pointer type.
13525 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13526 Init->getType() == Context.UnknownAnyTy) {
13527 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
13528 if (Result.isInvalid()) {
13529 VDecl->setInvalidDecl();
13530 return;
13532 Init = Result.get();
13535 // Perform the initialization.
13536 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13537 bool IsParenListInit = false;
13538 if (!VDecl->isInvalidDecl()) {
13539 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
13540 InitializationKind Kind = InitializationKind::CreateForInit(
13541 VDecl->getLocation(), DirectInit, Init);
13543 MultiExprArg Args = Init;
13544 if (CXXDirectInit)
13545 Args = MultiExprArg(CXXDirectInit->getExprs(),
13546 CXXDirectInit->getNumExprs());
13548 // Try to correct any TypoExprs in the initialization arguments.
13549 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13550 ExprResult Res = CorrectDelayedTyposInExpr(
13551 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13552 [this, Entity, Kind](Expr *E) {
13553 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13554 return Init.Failed() ? ExprError() : E;
13556 if (Res.isInvalid()) {
13557 VDecl->setInvalidDecl();
13558 } else if (Res.get() != Args[Idx]) {
13559 Args[Idx] = Res.get();
13562 if (VDecl->isInvalidDecl())
13563 return;
13565 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13566 /*TopLevelOfInitList=*/false,
13567 /*TreatUnavailableAsInvalid=*/false);
13568 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13569 if (Result.isInvalid()) {
13570 // If the provided initializer fails to initialize the var decl,
13571 // we attach a recovery expr for better recovery.
13572 auto RecoveryExpr =
13573 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13574 if (RecoveryExpr.get())
13575 VDecl->setInit(RecoveryExpr.get());
13576 return;
13579 Init = Result.getAs<Expr>();
13580 IsParenListInit = !InitSeq.steps().empty() &&
13581 InitSeq.step_begin()->Kind ==
13582 InitializationSequence::SK_ParenthesizedListInit;
13583 QualType VDeclType = VDecl->getType();
13584 if (Init && !Init->getType().isNull() &&
13585 !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13586 Context.getAsIncompleteArrayType(VDeclType) &&
13587 Context.getAsIncompleteArrayType(Init->getType())) {
13588 // Bail out if it is not possible to deduce array size from the
13589 // initializer.
13590 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13591 << VDeclType;
13592 VDecl->setInvalidDecl();
13593 return;
13597 // Check for self-references within variable initializers.
13598 // Variables declared within a function/method body (except for references)
13599 // are handled by a dataflow analysis.
13600 // This is undefined behavior in C++, but valid in C.
13601 if (getLangOpts().CPlusPlus)
13602 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13603 VDecl->getType()->isReferenceType())
13604 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13606 // If the type changed, it means we had an incomplete type that was
13607 // completed by the initializer. For example:
13608 // int ary[] = { 1, 3, 5 };
13609 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13610 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13611 VDecl->setType(DclT);
13613 if (!VDecl->isInvalidDecl()) {
13614 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13616 if (VDecl->hasAttr<BlocksAttr>())
13617 checkRetainCycles(VDecl, Init);
13619 // It is safe to assign a weak reference into a strong variable.
13620 // Although this code can still have problems:
13621 // id x = self.weakProp;
13622 // id y = self.weakProp;
13623 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13624 // paths through the function. This should be revisited if
13625 // -Wrepeated-use-of-weak is made flow-sensitive.
13626 if (FunctionScopeInfo *FSI = getCurFunction())
13627 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13628 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
13629 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13630 Init->getBeginLoc()))
13631 FSI->markSafeWeakUse(Init);
13634 // The initialization is usually a full-expression.
13636 // FIXME: If this is a braced initialization of an aggregate, it is not
13637 // an expression, and each individual field initializer is a separate
13638 // full-expression. For instance, in:
13640 // struct Temp { ~Temp(); };
13641 // struct S { S(Temp); };
13642 // struct T { S a, b; } t = { Temp(), Temp() }
13644 // we should destroy the first Temp before constructing the second.
13645 ExprResult Result =
13646 ActOnFinishFullExpr(Init, VDecl->getLocation(),
13647 /*DiscardedValue*/ false, VDecl->isConstexpr());
13648 if (Result.isInvalid()) {
13649 VDecl->setInvalidDecl();
13650 return;
13652 Init = Result.get();
13654 // Attach the initializer to the decl.
13655 VDecl->setInit(Init);
13657 if (VDecl->isLocalVarDecl()) {
13658 // Don't check the initializer if the declaration is malformed.
13659 if (VDecl->isInvalidDecl()) {
13660 // do nothing
13662 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13663 // This is true even in C++ for OpenCL.
13664 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13665 CheckForConstantInitializer(Init, DclT);
13667 // Otherwise, C++ does not restrict the initializer.
13668 } else if (getLangOpts().CPlusPlus) {
13669 // do nothing
13671 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13672 // static storage duration shall be constant expressions or string literals.
13673 } else if (VDecl->getStorageClass() == SC_Static) {
13674 CheckForConstantInitializer(Init, DclT);
13676 // C89 is stricter than C99 for aggregate initializers.
13677 // C89 6.5.7p3: All the expressions [...] in an initializer list
13678 // for an object that has aggregate or union type shall be
13679 // constant expressions.
13680 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13681 isa<InitListExpr>(Init)) {
13682 const Expr *Culprit;
13683 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
13684 Diag(Culprit->getExprLoc(),
13685 diag::ext_aggregate_init_not_constant)
13686 << Culprit->getSourceRange();
13690 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13691 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13692 if (VDecl->hasLocalStorage())
13693 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13694 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13695 VDecl->getLexicalDeclContext()->isRecord()) {
13696 // This is an in-class initialization for a static data member, e.g.,
13698 // struct S {
13699 // static const int value = 17;
13700 // };
13702 // C++ [class.mem]p4:
13703 // A member-declarator can contain a constant-initializer only
13704 // if it declares a static member (9.4) of const integral or
13705 // const enumeration type, see 9.4.2.
13707 // C++11 [class.static.data]p3:
13708 // If a non-volatile non-inline const static data member is of integral
13709 // or enumeration type, its declaration in the class definition can
13710 // specify a brace-or-equal-initializer in which every initializer-clause
13711 // that is an assignment-expression is a constant expression. A static
13712 // data member of literal type can be declared in the class definition
13713 // with the constexpr specifier; if so, its declaration shall specify a
13714 // brace-or-equal-initializer in which every initializer-clause that is
13715 // an assignment-expression is a constant expression.
13717 // Do nothing on dependent types.
13718 if (DclT->isDependentType()) {
13720 // Allow any 'static constexpr' members, whether or not they are of literal
13721 // type. We separately check that every constexpr variable is of literal
13722 // type.
13723 } else if (VDecl->isConstexpr()) {
13725 // Require constness.
13726 } else if (!DclT.isConstQualified()) {
13727 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13728 << Init->getSourceRange();
13729 VDecl->setInvalidDecl();
13731 // We allow integer constant expressions in all cases.
13732 } else if (DclT->isIntegralOrEnumerationType()) {
13733 // Check whether the expression is a constant expression.
13734 SourceLocation Loc;
13735 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
13736 // In C++11, a non-constexpr const static data member with an
13737 // in-class initializer cannot be volatile.
13738 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13739 else if (Init->isValueDependent())
13740 ; // Nothing to check.
13741 else if (Init->isIntegerConstantExpr(Context, &Loc))
13742 ; // Ok, it's an ICE!
13743 else if (Init->getType()->isScopedEnumeralType() &&
13744 Init->isCXX11ConstantExpr(Context))
13745 ; // Ok, it is a scoped-enum constant expression.
13746 else if (Init->isEvaluatable(Context)) {
13747 // If we can constant fold the initializer through heroics, accept it,
13748 // but report this as a use of an extension for -pedantic.
13749 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13750 << Init->getSourceRange();
13751 } else {
13752 // Otherwise, this is some crazy unknown case. Report the issue at the
13753 // location provided by the isIntegerConstantExpr failed check.
13754 Diag(Loc, diag::err_in_class_initializer_non_constant)
13755 << Init->getSourceRange();
13756 VDecl->setInvalidDecl();
13759 // We allow foldable floating-point constants as an extension.
13760 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13761 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13762 // it anyway and provide a fixit to add the 'constexpr'.
13763 if (getLangOpts().CPlusPlus11) {
13764 Diag(VDecl->getLocation(),
13765 diag::ext_in_class_initializer_float_type_cxx11)
13766 << DclT << Init->getSourceRange();
13767 Diag(VDecl->getBeginLoc(),
13768 diag::note_in_class_initializer_float_type_cxx11)
13769 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13770 } else {
13771 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13772 << DclT << Init->getSourceRange();
13774 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13775 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13776 << Init->getSourceRange();
13777 VDecl->setInvalidDecl();
13781 // Suggest adding 'constexpr' in C++11 for literal types.
13782 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13783 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13784 << DclT << Init->getSourceRange()
13785 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13786 VDecl->setConstexpr(true);
13788 } else {
13789 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13790 << DclT << Init->getSourceRange();
13791 VDecl->setInvalidDecl();
13793 } else if (VDecl->isFileVarDecl()) {
13794 // In C, extern is typically used to avoid tentative definitions when
13795 // declaring variables in headers, but adding an intializer makes it a
13796 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13797 // In C++, extern is often used to give implictly static const variables
13798 // external linkage, so don't warn in that case. If selectany is present,
13799 // this might be header code intended for C and C++ inclusion, so apply the
13800 // C++ rules.
13801 if (VDecl->getStorageClass() == SC_Extern &&
13802 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13803 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
13804 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13805 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
13806 Diag(VDecl->getLocation(), diag::warn_extern_init);
13808 // In Microsoft C++ mode, a const variable defined in namespace scope has
13809 // external linkage by default if the variable is declared with
13810 // __declspec(dllexport).
13811 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13812 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
13813 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13814 VDecl->setStorageClass(SC_Extern);
13816 // C99 6.7.8p4. All file scoped initializers need to be constant.
13817 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
13818 CheckForConstantInitializer(Init, DclT);
13821 QualType InitType = Init->getType();
13822 if (!InitType.isNull() &&
13823 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
13824 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
13825 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
13827 // We will represent direct-initialization similarly to copy-initialization:
13828 // int x(1); -as-> int x = 1;
13829 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13831 // Clients that want to distinguish between the two forms, can check for
13832 // direct initializer using VarDecl::getInitStyle().
13833 // A major benefit is that clients that don't particularly care about which
13834 // exactly form was it (like the CodeGen) can handle both cases without
13835 // special case code.
13837 // C++ 8.5p11:
13838 // The form of initialization (using parentheses or '=') is generally
13839 // insignificant, but does matter when the entity being initialized has a
13840 // class type.
13841 if (CXXDirectInit) {
13842 assert(DirectInit && "Call-style initializer must be direct init.");
13843 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13844 : VarDecl::CallInit);
13845 } else if (DirectInit) {
13846 // This must be list-initialization. No other way is direct-initialization.
13847 VDecl->setInitStyle(VarDecl::ListInit);
13850 if (LangOpts.OpenMP &&
13851 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13852 VDecl->isFileVarDecl())
13853 DeclsToCheckForDeferredDiags.insert(VDecl);
13854 CheckCompleteVariableDeclaration(VDecl);
13857 /// ActOnInitializerError - Given that there was an error parsing an
13858 /// initializer for the given declaration, try to at least re-establish
13859 /// invariants such as whether a variable's type is either dependent or
13860 /// complete.
13861 void Sema::ActOnInitializerError(Decl *D) {
13862 // Our main concern here is re-establishing invariants like "a
13863 // variable's type is either dependent or complete".
13864 if (!D || D->isInvalidDecl()) return;
13866 VarDecl *VD = dyn_cast<VarDecl>(D);
13867 if (!VD) return;
13869 // Bindings are not usable if we can't make sense of the initializer.
13870 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13871 for (auto *BD : DD->bindings())
13872 BD->setInvalidDecl();
13874 // Auto types are meaningless if we can't make sense of the initializer.
13875 if (VD->getType()->isUndeducedType()) {
13876 D->setInvalidDecl();
13877 return;
13880 QualType Ty = VD->getType();
13881 if (Ty->isDependentType()) return;
13883 // Require a complete type.
13884 if (RequireCompleteType(VD->getLocation(),
13885 Context.getBaseElementType(Ty),
13886 diag::err_typecheck_decl_incomplete_type)) {
13887 VD->setInvalidDecl();
13888 return;
13891 // Require a non-abstract type.
13892 if (RequireNonAbstractType(VD->getLocation(), Ty,
13893 diag::err_abstract_type_in_decl,
13894 AbstractVariableType)) {
13895 VD->setInvalidDecl();
13896 return;
13899 // Don't bother complaining about constructors or destructors,
13900 // though.
13903 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
13904 // If there is no declaration, there was an error parsing it. Just ignore it.
13905 if (!RealDecl)
13906 return;
13908 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13909 QualType Type = Var->getType();
13911 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13912 if (isa<DecompositionDecl>(RealDecl)) {
13913 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13914 Var->setInvalidDecl();
13915 return;
13918 if (Type->isUndeducedType() &&
13919 DeduceVariableDeclarationType(Var, false, nullptr))
13920 return;
13922 // C++11 [class.static.data]p3: A static data member can be declared with
13923 // the constexpr specifier; if so, its declaration shall specify
13924 // a brace-or-equal-initializer.
13925 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13926 // the definition of a variable [...] or the declaration of a static data
13927 // member.
13928 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13929 !Var->isThisDeclarationADemotedDefinition()) {
13930 if (Var->isStaticDataMember()) {
13931 // C++1z removes the relevant rule; the in-class declaration is always
13932 // a definition there.
13933 if (!getLangOpts().CPlusPlus17 &&
13934 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13935 Diag(Var->getLocation(),
13936 diag::err_constexpr_static_mem_var_requires_init)
13937 << Var;
13938 Var->setInvalidDecl();
13939 return;
13941 } else {
13942 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13943 Var->setInvalidDecl();
13944 return;
13948 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13949 // be initialized.
13950 if (!Var->isInvalidDecl() &&
13951 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13952 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13953 bool HasConstExprDefaultConstructor = false;
13954 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13955 for (auto *Ctor : RD->ctors()) {
13956 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13957 Ctor->getMethodQualifiers().getAddressSpace() ==
13958 LangAS::opencl_constant) {
13959 HasConstExprDefaultConstructor = true;
13963 if (!HasConstExprDefaultConstructor) {
13964 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13965 Var->setInvalidDecl();
13966 return;
13970 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13971 if (Var->getStorageClass() == SC_Extern) {
13972 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13973 << Var;
13974 Var->setInvalidDecl();
13975 return;
13977 if (RequireCompleteType(Var->getLocation(), Var->getType(),
13978 diag::err_typecheck_decl_incomplete_type)) {
13979 Var->setInvalidDecl();
13980 return;
13982 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13983 if (!RD->hasTrivialDefaultConstructor()) {
13984 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13985 Var->setInvalidDecl();
13986 return;
13989 // The declaration is unitialized, no need for further checks.
13990 return;
13993 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13994 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13995 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13996 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13997 NTCUC_DefaultInitializedObject, NTCUK_Init);
14000 switch (DefKind) {
14001 case VarDecl::Definition:
14002 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14003 break;
14005 // We have an out-of-line definition of a static data member
14006 // that has an in-class initializer, so we type-check this like
14007 // a declaration.
14009 [[fallthrough]];
14011 case VarDecl::DeclarationOnly:
14012 // It's only a declaration.
14014 // Block scope. C99 6.7p7: If an identifier for an object is
14015 // declared with no linkage (C99 6.2.2p6), the type for the
14016 // object shall be complete.
14017 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14018 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14019 RequireCompleteType(Var->getLocation(), Type,
14020 diag::err_typecheck_decl_incomplete_type))
14021 Var->setInvalidDecl();
14023 // Make sure that the type is not abstract.
14024 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14025 RequireNonAbstractType(Var->getLocation(), Type,
14026 diag::err_abstract_type_in_decl,
14027 AbstractVariableType))
14028 Var->setInvalidDecl();
14029 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14030 Var->getStorageClass() == SC_PrivateExtern) {
14031 Diag(Var->getLocation(), diag::warn_private_extern);
14032 Diag(Var->getLocation(), diag::note_private_extern);
14035 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14036 !Var->isInvalidDecl())
14037 ExternalDeclarations.push_back(Var);
14039 return;
14041 case VarDecl::TentativeDefinition:
14042 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14043 // object that has file scope without an initializer, and without a
14044 // storage-class specifier or with the storage-class specifier "static",
14045 // constitutes a tentative definition. Note: A tentative definition with
14046 // external linkage is valid (C99 6.2.2p5).
14047 if (!Var->isInvalidDecl()) {
14048 if (const IncompleteArrayType *ArrayT
14049 = Context.getAsIncompleteArrayType(Type)) {
14050 if (RequireCompleteSizedType(
14051 Var->getLocation(), ArrayT->getElementType(),
14052 diag::err_array_incomplete_or_sizeless_type))
14053 Var->setInvalidDecl();
14054 } else if (Var->getStorageClass() == SC_Static) {
14055 // C99 6.9.2p3: If the declaration of an identifier for an object is
14056 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14057 // declared type shall not be an incomplete type.
14058 // NOTE: code such as the following
14059 // static struct s;
14060 // struct s { int a; };
14061 // is accepted by gcc. Hence here we issue a warning instead of
14062 // an error and we do not invalidate the static declaration.
14063 // NOTE: to avoid multiple warnings, only check the first declaration.
14064 if (Var->isFirstDecl())
14065 RequireCompleteType(Var->getLocation(), Type,
14066 diag::ext_typecheck_decl_incomplete_type);
14070 // Record the tentative definition; we're done.
14071 if (!Var->isInvalidDecl())
14072 TentativeDefinitions.push_back(Var);
14073 return;
14076 // Provide a specific diagnostic for uninitialized variable
14077 // definitions with incomplete array type.
14078 if (Type->isIncompleteArrayType()) {
14079 if (Var->isConstexpr())
14080 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14081 << Var;
14082 else
14083 Diag(Var->getLocation(),
14084 diag::err_typecheck_incomplete_array_needs_initializer);
14085 Var->setInvalidDecl();
14086 return;
14089 // Provide a specific diagnostic for uninitialized variable
14090 // definitions with reference type.
14091 if (Type->isReferenceType()) {
14092 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14093 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14094 return;
14097 // Do not attempt to type-check the default initializer for a
14098 // variable with dependent type.
14099 if (Type->isDependentType())
14100 return;
14102 if (Var->isInvalidDecl())
14103 return;
14105 if (!Var->hasAttr<AliasAttr>()) {
14106 if (RequireCompleteType(Var->getLocation(),
14107 Context.getBaseElementType(Type),
14108 diag::err_typecheck_decl_incomplete_type)) {
14109 Var->setInvalidDecl();
14110 return;
14112 } else {
14113 return;
14116 // The variable can not have an abstract class type.
14117 if (RequireNonAbstractType(Var->getLocation(), Type,
14118 diag::err_abstract_type_in_decl,
14119 AbstractVariableType)) {
14120 Var->setInvalidDecl();
14121 return;
14124 // Check for jumps past the implicit initializer. C++0x
14125 // clarifies that this applies to a "variable with automatic
14126 // storage duration", not a "local variable".
14127 // C++11 [stmt.dcl]p3
14128 // A program that jumps from a point where a variable with automatic
14129 // storage duration is not in scope to a point where it is in scope is
14130 // ill-formed unless the variable has scalar type, class type with a
14131 // trivial default constructor and a trivial destructor, a cv-qualified
14132 // version of one of these types, or an array of one of the preceding
14133 // types and is declared without an initializer.
14134 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14135 if (const RecordType *Record
14136 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
14137 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14138 // Mark the function (if we're in one) for further checking even if the
14139 // looser rules of C++11 do not require such checks, so that we can
14140 // diagnose incompatibilities with C++98.
14141 if (!CXXRecord->isPOD())
14142 setFunctionHasBranchProtectedScope();
14145 // In OpenCL, we can't initialize objects in the __local address space,
14146 // even implicitly, so don't synthesize an implicit initializer.
14147 if (getLangOpts().OpenCL &&
14148 Var->getType().getAddressSpace() == LangAS::opencl_local)
14149 return;
14150 // C++03 [dcl.init]p9:
14151 // If no initializer is specified for an object, and the
14152 // object is of (possibly cv-qualified) non-POD class type (or
14153 // array thereof), the object shall be default-initialized; if
14154 // the object is of const-qualified type, the underlying class
14155 // type shall have a user-declared default
14156 // constructor. Otherwise, if no initializer is specified for
14157 // a non- static object, the object and its subobjects, if
14158 // any, have an indeterminate initial value); if the object
14159 // or any of its subobjects are of const-qualified type, the
14160 // program is ill-formed.
14161 // C++0x [dcl.init]p11:
14162 // If no initializer is specified for an object, the object is
14163 // default-initialized; [...].
14164 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
14165 InitializationKind Kind
14166 = InitializationKind::CreateDefault(Var->getLocation());
14168 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14169 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14171 if (Init.get()) {
14172 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14173 // This is important for template substitution.
14174 Var->setInitStyle(VarDecl::CallInit);
14175 } else if (Init.isInvalid()) {
14176 // If default-init fails, attach a recovery-expr initializer to track
14177 // that initialization was attempted and failed.
14178 auto RecoveryExpr =
14179 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14180 if (RecoveryExpr.get())
14181 Var->setInit(RecoveryExpr.get());
14184 CheckCompleteVariableDeclaration(Var);
14188 void Sema::ActOnCXXForRangeDecl(Decl *D) {
14189 // If there is no declaration, there was an error parsing it. Ignore it.
14190 if (!D)
14191 return;
14193 VarDecl *VD = dyn_cast<VarDecl>(D);
14194 if (!VD) {
14195 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14196 D->setInvalidDecl();
14197 return;
14200 VD->setCXXForRangeDecl(true);
14202 // for-range-declaration cannot be given a storage class specifier.
14203 int Error = -1;
14204 switch (VD->getStorageClass()) {
14205 case SC_None:
14206 break;
14207 case SC_Extern:
14208 Error = 0;
14209 break;
14210 case SC_Static:
14211 Error = 1;
14212 break;
14213 case SC_PrivateExtern:
14214 Error = 2;
14215 break;
14216 case SC_Auto:
14217 Error = 3;
14218 break;
14219 case SC_Register:
14220 Error = 4;
14221 break;
14224 // for-range-declaration cannot be given a storage class specifier con't.
14225 switch (VD->getTSCSpec()) {
14226 case TSCS_thread_local:
14227 Error = 6;
14228 break;
14229 case TSCS___thread:
14230 case TSCS__Thread_local:
14231 case TSCS_unspecified:
14232 break;
14235 if (Error != -1) {
14236 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14237 << VD << Error;
14238 D->setInvalidDecl();
14242 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
14243 IdentifierInfo *Ident,
14244 ParsedAttributes &Attrs) {
14245 // C++1y [stmt.iter]p1:
14246 // A range-based for statement of the form
14247 // for ( for-range-identifier : for-range-initializer ) statement
14248 // is equivalent to
14249 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14250 DeclSpec DS(Attrs.getPool().getFactory());
14252 const char *PrevSpec;
14253 unsigned DiagID;
14254 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14255 getPrintingPolicy());
14257 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
14258 D.SetIdentifier(Ident, IdentLoc);
14259 D.takeAttributes(Attrs);
14261 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14262 IdentLoc);
14263 Decl *Var = ActOnDeclarator(S, D);
14264 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14265 FinalizeDeclaration(Var);
14266 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14267 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14268 : IdentLoc);
14271 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
14272 if (var->isInvalidDecl()) return;
14274 MaybeAddCUDAConstantAttr(var);
14276 if (getLangOpts().OpenCL) {
14277 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14278 // initialiser
14279 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14280 !var->hasInit()) {
14281 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14282 << 1 /*Init*/;
14283 var->setInvalidDecl();
14284 return;
14288 // In Objective-C, don't allow jumps past the implicit initialization of a
14289 // local retaining variable.
14290 if (getLangOpts().ObjC &&
14291 var->hasLocalStorage()) {
14292 switch (var->getType().getObjCLifetime()) {
14293 case Qualifiers::OCL_None:
14294 case Qualifiers::OCL_ExplicitNone:
14295 case Qualifiers::OCL_Autoreleasing:
14296 break;
14298 case Qualifiers::OCL_Weak:
14299 case Qualifiers::OCL_Strong:
14300 setFunctionHasBranchProtectedScope();
14301 break;
14305 if (var->hasLocalStorage() &&
14306 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14307 setFunctionHasBranchProtectedScope();
14309 // Warn about externally-visible variables being defined without a
14310 // prior declaration. We only want to do this for global
14311 // declarations, but we also specifically need to avoid doing it for
14312 // class members because the linkage of an anonymous class can
14313 // change if it's later given a typedef name.
14314 if (var->isThisDeclarationADefinition() &&
14315 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14316 var->isExternallyVisible() && var->hasLinkage() &&
14317 !var->isInline() && !var->getDescribedVarTemplate() &&
14318 var->getStorageClass() != SC_Register &&
14319 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14320 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14321 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14322 var->getLocation())) {
14323 // Find a previous declaration that's not a definition.
14324 VarDecl *prev = var->getPreviousDecl();
14325 while (prev && prev->isThisDeclarationADefinition())
14326 prev = prev->getPreviousDecl();
14328 if (!prev) {
14329 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14330 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14331 << /* variable */ 0;
14335 // Cache the result of checking for constant initialization.
14336 std::optional<bool> CacheHasConstInit;
14337 const Expr *CacheCulprit = nullptr;
14338 auto checkConstInit = [&]() mutable {
14339 if (!CacheHasConstInit)
14340 CacheHasConstInit = var->getInit()->isConstantInitializer(
14341 Context, var->getType()->isReferenceType(), &CacheCulprit);
14342 return *CacheHasConstInit;
14345 if (var->getTLSKind() == VarDecl::TLS_Static) {
14346 if (var->getType().isDestructedType()) {
14347 // GNU C++98 edits for __thread, [basic.start.term]p3:
14348 // The type of an object with thread storage duration shall not
14349 // have a non-trivial destructor.
14350 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14351 if (getLangOpts().CPlusPlus11)
14352 Diag(var->getLocation(), diag::note_use_thread_local);
14353 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14354 if (!checkConstInit()) {
14355 // GNU C++98 edits for __thread, [basic.start.init]p4:
14356 // An object of thread storage duration shall not require dynamic
14357 // initialization.
14358 // FIXME: Need strict checking here.
14359 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14360 << CacheCulprit->getSourceRange();
14361 if (getLangOpts().CPlusPlus11)
14362 Diag(var->getLocation(), diag::note_use_thread_local);
14368 if (!var->getType()->isStructureType() && var->hasInit() &&
14369 isa<InitListExpr>(var->getInit())) {
14370 const auto *ILE = cast<InitListExpr>(var->getInit());
14371 unsigned NumInits = ILE->getNumInits();
14372 if (NumInits > 2)
14373 for (unsigned I = 0; I < NumInits; ++I) {
14374 const auto *Init = ILE->getInit(I);
14375 if (!Init)
14376 break;
14377 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14378 if (!SL)
14379 break;
14381 unsigned NumConcat = SL->getNumConcatenated();
14382 // Diagnose missing comma in string array initialization.
14383 // Do not warn when all the elements in the initializer are concatenated
14384 // together. Do not warn for macros too.
14385 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14386 bool OnlyOneMissingComma = true;
14387 for (unsigned J = I + 1; J < NumInits; ++J) {
14388 const auto *Init = ILE->getInit(J);
14389 if (!Init)
14390 break;
14391 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14392 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14393 OnlyOneMissingComma = false;
14394 break;
14398 if (OnlyOneMissingComma) {
14399 SmallVector<FixItHint, 1> Hints;
14400 for (unsigned i = 0; i < NumConcat - 1; ++i)
14401 Hints.push_back(FixItHint::CreateInsertion(
14402 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14404 Diag(SL->getStrTokenLoc(1),
14405 diag::warn_concatenated_literal_array_init)
14406 << Hints;
14407 Diag(SL->getBeginLoc(),
14408 diag::note_concatenated_string_literal_silence);
14410 // In any case, stop now.
14411 break;
14417 QualType type = var->getType();
14419 if (var->hasAttr<BlocksAttr>())
14420 getCurFunction()->addByrefBlockVar(var);
14422 Expr *Init = var->getInit();
14423 bool GlobalStorage = var->hasGlobalStorage();
14424 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14425 QualType baseType = Context.getBaseElementType(type);
14426 bool HasConstInit = true;
14428 // Check whether the initializer is sufficiently constant.
14429 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
14430 !Init->isValueDependent() &&
14431 (GlobalStorage || var->isConstexpr() ||
14432 var->mightBeUsableInConstantExpressions(Context))) {
14433 // If this variable might have a constant initializer or might be usable in
14434 // constant expressions, check whether or not it actually is now. We can't
14435 // do this lazily, because the result might depend on things that change
14436 // later, such as which constexpr functions happen to be defined.
14437 SmallVector<PartialDiagnosticAt, 8> Notes;
14438 if (!getLangOpts().CPlusPlus11) {
14439 // Prior to C++11, in contexts where a constant initializer is required,
14440 // the set of valid constant initializers is described by syntactic rules
14441 // in [expr.const]p2-6.
14442 // FIXME: Stricter checking for these rules would be useful for constinit /
14443 // -Wglobal-constructors.
14444 HasConstInit = checkConstInit();
14446 // Compute and cache the constant value, and remember that we have a
14447 // constant initializer.
14448 if (HasConstInit) {
14449 (void)var->checkForConstantInitialization(Notes);
14450 Notes.clear();
14451 } else if (CacheCulprit) {
14452 Notes.emplace_back(CacheCulprit->getExprLoc(),
14453 PDiag(diag::note_invalid_subexpr_in_const_expr));
14454 Notes.back().second << CacheCulprit->getSourceRange();
14456 } else {
14457 // Evaluate the initializer to see if it's a constant initializer.
14458 HasConstInit = var->checkForConstantInitialization(Notes);
14461 if (HasConstInit) {
14462 // FIXME: Consider replacing the initializer with a ConstantExpr.
14463 } else if (var->isConstexpr()) {
14464 SourceLocation DiagLoc = var->getLocation();
14465 // If the note doesn't add any useful information other than a source
14466 // location, fold it into the primary diagnostic.
14467 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14468 diag::note_invalid_subexpr_in_const_expr) {
14469 DiagLoc = Notes[0].first;
14470 Notes.clear();
14472 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14473 << var << Init->getSourceRange();
14474 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14475 Diag(Notes[I].first, Notes[I].second);
14476 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14477 auto *Attr = var->getAttr<ConstInitAttr>();
14478 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14479 << Init->getSourceRange();
14480 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14481 << Attr->getRange() << Attr->isConstinit();
14482 for (auto &it : Notes)
14483 Diag(it.first, it.second);
14484 } else if (IsGlobal &&
14485 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14486 var->getLocation())) {
14487 // Warn about globals which don't have a constant initializer. Don't
14488 // warn about globals with a non-trivial destructor because we already
14489 // warned about them.
14490 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14491 if (!(RD && !RD->hasTrivialDestructor())) {
14492 // checkConstInit() here permits trivial default initialization even in
14493 // C++11 onwards, where such an initializer is not a constant initializer
14494 // but nonetheless doesn't require a global constructor.
14495 if (!checkConstInit())
14496 Diag(var->getLocation(), diag::warn_global_constructor)
14497 << Init->getSourceRange();
14502 // Apply section attributes and pragmas to global variables.
14503 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14504 !inTemplateInstantiation()) {
14505 PragmaStack<StringLiteral *> *Stack = nullptr;
14506 int SectionFlags = ASTContext::PSF_Read;
14507 bool MSVCEnv =
14508 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14509 std::optional<QualType::NonConstantStorageReason> Reason;
14510 if (HasConstInit &&
14511 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14512 Stack = &ConstSegStack;
14513 } else {
14514 SectionFlags |= ASTContext::PSF_Write;
14515 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14517 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14518 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14519 SectionFlags |= ASTContext::PSF_Implicit;
14520 UnifySection(SA->getName(), SectionFlags, var);
14521 } else if (Stack->CurrentValue) {
14522 if (Stack != &ConstSegStack && MSVCEnv &&
14523 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14524 var->getType().isConstQualified()) {
14525 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14526 NonConstNonReferenceType) &&
14527 "This case should've already been handled elsewhere");
14528 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14529 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14530 ? QualType::NonConstantStorageReason::NonTrivialCtor
14531 : *Reason);
14533 SectionFlags |= ASTContext::PSF_Implicit;
14534 auto SectionName = Stack->CurrentValue->getString();
14535 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14536 Stack->CurrentPragmaLocation,
14537 SectionAttr::Declspec_allocate));
14538 if (UnifySection(SectionName, SectionFlags, var))
14539 var->dropAttr<SectionAttr>();
14542 // Apply the init_seg attribute if this has an initializer. If the
14543 // initializer turns out to not be dynamic, we'll end up ignoring this
14544 // attribute.
14545 if (CurInitSeg && var->getInit())
14546 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14547 CurInitSegLoc));
14550 // All the following checks are C++ only.
14551 if (!getLangOpts().CPlusPlus) {
14552 // If this variable must be emitted, add it as an initializer for the
14553 // current module.
14554 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14555 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14556 return;
14559 // Require the destructor.
14560 if (!type->isDependentType())
14561 if (const RecordType *recordType = baseType->getAs<RecordType>())
14562 FinalizeVarWithDestructor(var, recordType);
14564 // If this variable must be emitted, add it as an initializer for the current
14565 // module.
14566 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14567 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14569 // Build the bindings if this is a structured binding declaration.
14570 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14571 CheckCompleteDecompositionDeclaration(DD);
14574 /// Check if VD needs to be dllexport/dllimport due to being in a
14575 /// dllexport/import function.
14576 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
14577 assert(VD->isStaticLocal());
14579 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14581 // Find outermost function when VD is in lambda function.
14582 while (FD && !getDLLAttr(FD) &&
14583 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14584 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14585 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14588 if (!FD)
14589 return;
14591 // Static locals inherit dll attributes from their function.
14592 if (Attr *A = getDLLAttr(FD)) {
14593 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14594 NewAttr->setInherited(true);
14595 VD->addAttr(NewAttr);
14596 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14597 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14598 NewAttr->setInherited(true);
14599 VD->addAttr(NewAttr);
14601 // Export this function to enforce exporting this static variable even
14602 // if it is not used in this compilation unit.
14603 if (!FD->hasAttr<DLLExportAttr>())
14604 FD->addAttr(NewAttr);
14606 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14607 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14608 NewAttr->setInherited(true);
14609 VD->addAttr(NewAttr);
14613 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
14614 assert(VD->getTLSKind());
14616 // Perform TLS alignment check here after attributes attached to the variable
14617 // which may affect the alignment have been processed. Only perform the check
14618 // if the target has a maximum TLS alignment (zero means no constraints).
14619 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14620 // Protect the check so that it's not performed on dependent types and
14621 // dependent alignments (we can't determine the alignment in that case).
14622 if (!VD->hasDependentAlignment()) {
14623 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14624 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14625 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14626 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
14627 << (unsigned)MaxAlignChars.getQuantity();
14633 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
14634 /// any semantic actions necessary after any initializer has been attached.
14635 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
14636 // Note that we are no longer parsing the initializer for this declaration.
14637 ParsingInitForAutoVars.erase(ThisDecl);
14639 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14640 if (!VD)
14641 return;
14643 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14644 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
14645 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14646 if (PragmaClangBSSSection.Valid)
14647 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14648 Context, PragmaClangBSSSection.SectionName,
14649 PragmaClangBSSSection.PragmaLocation));
14650 if (PragmaClangDataSection.Valid)
14651 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14652 Context, PragmaClangDataSection.SectionName,
14653 PragmaClangDataSection.PragmaLocation));
14654 if (PragmaClangRodataSection.Valid)
14655 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14656 Context, PragmaClangRodataSection.SectionName,
14657 PragmaClangRodataSection.PragmaLocation));
14658 if (PragmaClangRelroSection.Valid)
14659 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14660 Context, PragmaClangRelroSection.SectionName,
14661 PragmaClangRelroSection.PragmaLocation));
14664 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14665 for (auto *BD : DD->bindings()) {
14666 FinalizeDeclaration(BD);
14670 checkAttributesAfterMerging(*this, *VD);
14672 if (VD->isStaticLocal())
14673 CheckStaticLocalForDllExport(VD);
14675 if (VD->getTLSKind())
14676 CheckThreadLocalForLargeAlignment(VD);
14678 // Perform check for initializers of device-side global variables.
14679 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14680 // 7.5). We must also apply the same checks to all __shared__
14681 // variables whether they are local or not. CUDA also allows
14682 // constant initializers for __constant__ and __device__ variables.
14683 if (getLangOpts().CUDA)
14684 checkAllowedCUDAInitializer(VD);
14686 // Grab the dllimport or dllexport attribute off of the VarDecl.
14687 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14689 // Imported static data members cannot be defined out-of-line.
14690 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14691 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14692 VD->isThisDeclarationADefinition()) {
14693 // We allow definitions of dllimport class template static data members
14694 // with a warning.
14695 CXXRecordDecl *Context =
14696 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14697 bool IsClassTemplateMember =
14698 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14699 Context->getDescribedClassTemplate();
14701 Diag(VD->getLocation(),
14702 IsClassTemplateMember
14703 ? diag::warn_attribute_dllimport_static_field_definition
14704 : diag::err_attribute_dllimport_static_field_definition);
14705 Diag(IA->getLocation(), diag::note_attribute);
14706 if (!IsClassTemplateMember)
14707 VD->setInvalidDecl();
14711 // dllimport/dllexport variables cannot be thread local, their TLS index
14712 // isn't exported with the variable.
14713 if (DLLAttr && VD->getTLSKind()) {
14714 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14715 if (F && getDLLAttr(F)) {
14716 assert(VD->isStaticLocal());
14717 // But if this is a static local in a dlimport/dllexport function, the
14718 // function will never be inlined, which means the var would never be
14719 // imported, so having it marked import/export is safe.
14720 } else {
14721 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14722 << DLLAttr;
14723 VD->setInvalidDecl();
14727 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14728 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14729 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14730 << Attr;
14731 VD->dropAttr<UsedAttr>();
14734 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14735 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14736 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14737 << Attr;
14738 VD->dropAttr<RetainAttr>();
14742 const DeclContext *DC = VD->getDeclContext();
14743 // If there's a #pragma GCC visibility in scope, and this isn't a class
14744 // member, set the visibility of this variable.
14745 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
14746 AddPushedVisibilityAttribute(VD);
14748 // FIXME: Warn on unused var template partial specializations.
14749 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14750 MarkUnusedFileScopedDecl(VD);
14752 // Now we have parsed the initializer and can update the table of magic
14753 // tag values.
14754 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14755 !VD->getType()->isIntegralOrEnumerationType())
14756 return;
14758 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14759 const Expr *MagicValueExpr = VD->getInit();
14760 if (!MagicValueExpr) {
14761 continue;
14763 std::optional<llvm::APSInt> MagicValueInt;
14764 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14765 Diag(I->getRange().getBegin(),
14766 diag::err_type_tag_for_datatype_not_ice)
14767 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14768 continue;
14770 if (MagicValueInt->getActiveBits() > 64) {
14771 Diag(I->getRange().getBegin(),
14772 diag::err_type_tag_for_datatype_too_large)
14773 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14774 continue;
14776 uint64_t MagicValue = MagicValueInt->getZExtValue();
14777 RegisterTypeTagForDatatype(I->getArgumentKind(),
14778 MagicValue,
14779 I->getMatchingCType(),
14780 I->getLayoutCompatible(),
14781 I->getMustBeNull());
14785 static bool hasDeducedAuto(DeclaratorDecl *DD) {
14786 auto *VD = dyn_cast<VarDecl>(DD);
14787 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14790 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
14791 ArrayRef<Decl *> Group) {
14792 SmallVector<Decl*, 8> Decls;
14794 if (DS.isTypeSpecOwned())
14795 Decls.push_back(DS.getRepAsDecl());
14797 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14798 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14799 bool DiagnosedMultipleDecomps = false;
14800 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14801 bool DiagnosedNonDeducedAuto = false;
14803 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14804 if (Decl *D = Group[i]) {
14805 // Check if the Decl has been declared in '#pragma omp declare target'
14806 // directive and has static storage duration.
14807 if (auto *VD = dyn_cast<VarDecl>(D);
14808 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14809 VD->hasGlobalStorage())
14810 ActOnOpenMPDeclareTargetInitializer(D);
14811 // For declarators, there are some additional syntactic-ish checks we need
14812 // to perform.
14813 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14814 if (!FirstDeclaratorInGroup)
14815 FirstDeclaratorInGroup = DD;
14816 if (!FirstDecompDeclaratorInGroup)
14817 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14818 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14819 !hasDeducedAuto(DD))
14820 FirstNonDeducedAutoInGroup = DD;
14822 if (FirstDeclaratorInGroup != DD) {
14823 // A decomposition declaration cannot be combined with any other
14824 // declaration in the same group.
14825 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14826 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14827 diag::err_decomp_decl_not_alone)
14828 << FirstDeclaratorInGroup->getSourceRange()
14829 << DD->getSourceRange();
14830 DiagnosedMultipleDecomps = true;
14833 // A declarator that uses 'auto' in any way other than to declare a
14834 // variable with a deduced type cannot be combined with any other
14835 // declarator in the same group.
14836 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14837 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14838 diag::err_auto_non_deduced_not_alone)
14839 << FirstNonDeducedAutoInGroup->getType()
14840 ->hasAutoForTrailingReturnType()
14841 << FirstDeclaratorInGroup->getSourceRange()
14842 << DD->getSourceRange();
14843 DiagnosedNonDeducedAuto = true;
14848 Decls.push_back(D);
14852 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
14853 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14854 handleTagNumbering(Tag, S);
14855 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14856 getLangOpts().CPlusPlus)
14857 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14861 return BuildDeclaratorGroup(Decls);
14864 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
14865 /// group, performing any necessary semantic checking.
14866 Sema::DeclGroupPtrTy
14867 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
14868 // C++14 [dcl.spec.auto]p7: (DR1347)
14869 // If the type that replaces the placeholder type is not the same in each
14870 // deduction, the program is ill-formed.
14871 if (Group.size() > 1) {
14872 QualType Deduced;
14873 VarDecl *DeducedDecl = nullptr;
14874 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14875 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14876 if (!D || D->isInvalidDecl())
14877 break;
14878 DeducedType *DT = D->getType()->getContainedDeducedType();
14879 if (!DT || DT->getDeducedType().isNull())
14880 continue;
14881 if (Deduced.isNull()) {
14882 Deduced = DT->getDeducedType();
14883 DeducedDecl = D;
14884 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14885 auto *AT = dyn_cast<AutoType>(DT);
14886 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14887 diag::err_auto_different_deductions)
14888 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14889 << DeducedDecl->getDeclName() << DT->getDeducedType()
14890 << D->getDeclName();
14891 if (DeducedDecl->hasInit())
14892 Dia << DeducedDecl->getInit()->getSourceRange();
14893 if (D->getInit())
14894 Dia << D->getInit()->getSourceRange();
14895 D->setInvalidDecl();
14896 break;
14901 ActOnDocumentableDecls(Group);
14903 return DeclGroupPtrTy::make(
14904 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14907 void Sema::ActOnDocumentableDecl(Decl *D) {
14908 ActOnDocumentableDecls(D);
14911 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
14912 // Don't parse the comment if Doxygen diagnostics are ignored.
14913 if (Group.empty() || !Group[0])
14914 return;
14916 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14917 Group[0]->getLocation()) &&
14918 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14919 Group[0]->getLocation()))
14920 return;
14922 if (Group.size() >= 2) {
14923 // This is a decl group. Normally it will contain only declarations
14924 // produced from declarator list. But in case we have any definitions or
14925 // additional declaration references:
14926 // 'typedef struct S {} S;'
14927 // 'typedef struct S *S;'
14928 // 'struct S *pS;'
14929 // FinalizeDeclaratorGroup adds these as separate declarations.
14930 Decl *MaybeTagDecl = Group[0];
14931 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14932 Group = Group.slice(1);
14936 // FIMXE: We assume every Decl in the group is in the same file.
14937 // This is false when preprocessor constructs the group from decls in
14938 // different files (e. g. macros or #include).
14939 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
14942 /// Common checks for a parameter-declaration that should apply to both function
14943 /// parameters and non-type template parameters.
14944 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
14945 // Check that there are no default arguments inside the type of this
14946 // parameter.
14947 if (getLangOpts().CPlusPlus)
14948 CheckExtraCXXDefaultArguments(D);
14950 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14951 if (D.getCXXScopeSpec().isSet()) {
14952 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14953 << D.getCXXScopeSpec().getRange();
14956 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14957 // simple identifier except [...irrelevant cases...].
14958 switch (D.getName().getKind()) {
14959 case UnqualifiedIdKind::IK_Identifier:
14960 break;
14962 case UnqualifiedIdKind::IK_OperatorFunctionId:
14963 case UnqualifiedIdKind::IK_ConversionFunctionId:
14964 case UnqualifiedIdKind::IK_LiteralOperatorId:
14965 case UnqualifiedIdKind::IK_ConstructorName:
14966 case UnqualifiedIdKind::IK_DestructorName:
14967 case UnqualifiedIdKind::IK_ImplicitSelfParam:
14968 case UnqualifiedIdKind::IK_DeductionGuideName:
14969 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14970 << GetNameForDeclarator(D).getName();
14971 break;
14973 case UnqualifiedIdKind::IK_TemplateId:
14974 case UnqualifiedIdKind::IK_ConstructorTemplateId:
14975 // GetNameForDeclarator would not produce a useful name in this case.
14976 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14977 break;
14981 static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P,
14982 SourceLocation ExplicitThisLoc) {
14983 if (!ExplicitThisLoc.isValid())
14984 return;
14985 assert(S.getLangOpts().CPlusPlus &&
14986 "explicit parameter in non-cplusplus mode");
14987 if (!S.getLangOpts().CPlusPlus23)
14988 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
14989 << P->getSourceRange();
14991 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
14992 // parameter pack.
14993 if (P->isParameterPack()) {
14994 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
14995 << P->getSourceRange();
14996 return;
14998 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
14999 if (LambdaScopeInfo *LSI = S.getCurLambda())
15000 LSI->ExplicitObjectParameter = P;
15003 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
15004 /// to introduce parameters into function prototype scope.
15005 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D,
15006 SourceLocation ExplicitThisLoc) {
15007 const DeclSpec &DS = D.getDeclSpec();
15009 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15011 // C++03 [dcl.stc]p2 also permits 'auto'.
15012 StorageClass SC = SC_None;
15013 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
15014 SC = SC_Register;
15015 // In C++11, the 'register' storage class specifier is deprecated.
15016 // In C++17, it is not allowed, but we tolerate it as an extension.
15017 if (getLangOpts().CPlusPlus11) {
15018 Diag(DS.getStorageClassSpecLoc(),
15019 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
15020 : diag::warn_deprecated_register)
15021 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
15023 } else if (getLangOpts().CPlusPlus &&
15024 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
15025 SC = SC_Auto;
15026 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
15027 Diag(DS.getStorageClassSpecLoc(),
15028 diag::err_invalid_storage_class_in_func_decl);
15029 D.getMutableDeclSpec().ClearStorageClassSpecs();
15032 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
15033 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15034 << DeclSpec::getSpecifierName(TSCS);
15035 if (DS.isInlineSpecified())
15036 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15037 << getLangOpts().CPlusPlus17;
15038 if (DS.hasConstexprSpecifier())
15039 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15040 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15042 DiagnoseFunctionSpecifiers(DS);
15044 CheckFunctionOrTemplateParamDeclarator(S, D);
15046 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15047 QualType parmDeclType = TInfo->getType();
15049 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15050 IdentifierInfo *II = D.getIdentifier();
15051 if (II) {
15052 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15053 ForVisibleRedeclaration);
15054 LookupName(R, S);
15055 if (!R.empty()) {
15056 NamedDecl *PrevDecl = *R.begin();
15057 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15058 // Maybe we will complain about the shadowed template parameter.
15059 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15060 // Just pretend that we didn't see the previous declaration.
15061 PrevDecl = nullptr;
15063 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15064 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15065 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15066 // Recover by removing the name
15067 II = nullptr;
15068 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15069 D.setInvalidType(true);
15074 // Temporarily put parameter variables in the translation unit, not
15075 // the enclosing context. This prevents them from accidentally
15076 // looking like class members in C++.
15077 ParmVarDecl *New =
15078 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15079 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15081 if (D.isInvalidType())
15082 New->setInvalidDecl();
15084 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15086 assert(S->isFunctionPrototypeScope());
15087 assert(S->getFunctionPrototypeDepth() >= 1);
15088 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15089 S->getNextFunctionPrototypeIndex());
15091 // Add the parameter declaration into this scope.
15092 S->AddDecl(New);
15093 if (II)
15094 IdResolver.AddDecl(New);
15096 ProcessDeclAttributes(S, New, D);
15098 if (D.getDeclSpec().isModulePrivateSpecified())
15099 Diag(New->getLocation(), diag::err_module_private_local)
15100 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15101 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15103 if (New->hasAttr<BlocksAttr>()) {
15104 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15107 if (getLangOpts().OpenCL)
15108 deduceOpenCLAddressSpace(New);
15110 return New;
15113 /// Synthesizes a variable for a parameter arising from a
15114 /// typedef.
15115 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
15116 SourceLocation Loc,
15117 QualType T) {
15118 /* FIXME: setting StartLoc == Loc.
15119 Would it be worth to modify callers so as to provide proper source
15120 location for the unnamed parameters, embedding the parameter's type? */
15121 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15122 T, Context.getTrivialTypeSourceInfo(T, Loc),
15123 SC_None, nullptr);
15124 Param->setImplicit();
15125 return Param;
15128 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
15129 // Don't diagnose unused-parameter errors in template instantiations; we
15130 // will already have done so in the template itself.
15131 if (inTemplateInstantiation())
15132 return;
15134 for (const ParmVarDecl *Parameter : Parameters) {
15135 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15136 !Parameter->hasAttr<UnusedAttr>() &&
15137 !Parameter->getIdentifier()->isPlaceholder()) {
15138 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15139 << Parameter->getDeclName();
15144 void Sema::DiagnoseSizeOfParametersAndReturnValue(
15145 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15146 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15147 return;
15149 // Warn if the return value is pass-by-value and larger than the specified
15150 // threshold.
15151 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15152 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15153 if (Size > LangOpts.NumLargeByValueCopy)
15154 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15157 // Warn if any parameter is pass-by-value and larger than the specified
15158 // threshold.
15159 for (const ParmVarDecl *Parameter : Parameters) {
15160 QualType T = Parameter->getType();
15161 if (T->isDependentType() || !T.isPODType(Context))
15162 continue;
15163 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15164 if (Size > LangOpts.NumLargeByValueCopy)
15165 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15166 << Parameter << Size;
15170 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
15171 SourceLocation NameLoc, IdentifierInfo *Name,
15172 QualType T, TypeSourceInfo *TSInfo,
15173 StorageClass SC) {
15174 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15175 if (getLangOpts().ObjCAutoRefCount &&
15176 T.getObjCLifetime() == Qualifiers::OCL_None &&
15177 T->isObjCLifetimeType()) {
15179 Qualifiers::ObjCLifetime lifetime;
15181 // Special cases for arrays:
15182 // - if it's const, use __unsafe_unretained
15183 // - otherwise, it's an error
15184 if (T->isArrayType()) {
15185 if (!T.isConstQualified()) {
15186 if (DelayedDiagnostics.shouldDelayDiagnostics())
15187 DelayedDiagnostics.add(
15188 sema::DelayedDiagnostic::makeForbiddenType(
15189 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15190 else
15191 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15192 << TSInfo->getTypeLoc().getSourceRange();
15194 lifetime = Qualifiers::OCL_ExplicitNone;
15195 } else {
15196 lifetime = T->getObjCARCImplicitLifetime();
15198 T = Context.getLifetimeQualifiedType(T, lifetime);
15201 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15202 Context.getAdjustedParameterType(T),
15203 TSInfo, SC, nullptr);
15205 // Make a note if we created a new pack in the scope of a lambda, so that
15206 // we know that references to that pack must also be expanded within the
15207 // lambda scope.
15208 if (New->isParameterPack())
15209 if (auto *LSI = getEnclosingLambda())
15210 LSI->LocalPacks.push_back(New);
15212 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15213 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15214 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15215 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
15217 // Parameter declarators cannot be interface types. All ObjC objects are
15218 // passed by reference.
15219 if (T->isObjCObjectType()) {
15220 SourceLocation TypeEndLoc =
15221 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
15222 Diag(NameLoc,
15223 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15224 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15225 T = Context.getObjCObjectPointerType(T);
15226 New->setType(T);
15229 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15230 // duration shall not be qualified by an address-space qualifier."
15231 // Since all parameters have automatic store duration, they can not have
15232 // an address space.
15233 if (T.getAddressSpace() != LangAS::Default &&
15234 // OpenCL allows function arguments declared to be an array of a type
15235 // to be qualified with an address space.
15236 !(getLangOpts().OpenCL &&
15237 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15238 // WebAssembly allows reference types as parameters. Funcref in particular
15239 // lives in a different address space.
15240 !(T->isFunctionPointerType() &&
15241 T.getAddressSpace() == LangAS::wasm_funcref)) {
15242 Diag(NameLoc, diag::err_arg_with_address_space);
15243 New->setInvalidDecl();
15246 // PPC MMA non-pointer types are not allowed as function argument types.
15247 if (Context.getTargetInfo().getTriple().isPPC64() &&
15248 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15249 New->setInvalidDecl();
15252 return New;
15255 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
15256 SourceLocation LocAfterDecls) {
15257 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15259 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15260 // in the declaration list shall have at least one declarator, those
15261 // declarators shall only declare identifiers from the identifier list, and
15262 // every identifier in the identifier list shall be declared.
15264 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15265 // identifiers it names shall be declared in the declaration list."
15267 // This is why we only diagnose in C99 and later. Note, the other conditions
15268 // listed are checked elsewhere.
15269 if (!FTI.hasPrototype) {
15270 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15271 --i;
15272 if (FTI.Params[i].Param == nullptr) {
15273 if (getLangOpts().C99) {
15274 SmallString<256> Code;
15275 llvm::raw_svector_ostream(Code)
15276 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15277 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15278 << FTI.Params[i].Ident
15279 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15282 // Implicitly declare the argument as type 'int' for lack of a better
15283 // type.
15284 AttributeFactory attrs;
15285 DeclSpec DS(attrs);
15286 const char* PrevSpec; // unused
15287 unsigned DiagID; // unused
15288 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15289 DiagID, Context.getPrintingPolicy());
15290 // Use the identifier location for the type source range.
15291 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15292 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15293 Declarator ParamD(DS, ParsedAttributesView::none(),
15294 DeclaratorContext::KNRTypeList);
15295 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15296 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15302 Decl *
15303 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
15304 MultiTemplateParamsArg TemplateParameterLists,
15305 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15306 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15307 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15308 Scope *ParentScope = FnBodyScope->getParent();
15310 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15311 // we define a non-templated function definition, we will create a declaration
15312 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15313 // The base function declaration will have the equivalent of an `omp declare
15314 // variant` annotation which specifies the mangled definition as a
15315 // specialization function under the OpenMP context defined as part of the
15316 // `omp begin declare variant`.
15317 SmallVector<FunctionDecl *, 4> Bases;
15318 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
15319 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
15320 ParentScope, D, TemplateParameterLists, Bases);
15322 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15323 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15324 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15326 if (!Bases.empty())
15327 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
15329 return Dcl;
15332 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
15333 Consumer.HandleInlineFunctionDefinition(D);
15336 static bool FindPossiblePrototype(const FunctionDecl *FD,
15337 const FunctionDecl *&PossiblePrototype) {
15338 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15339 Prev = Prev->getPreviousDecl()) {
15340 // Ignore any declarations that occur in function or method
15341 // scope, because they aren't visible from the header.
15342 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15343 continue;
15345 PossiblePrototype = Prev;
15346 return Prev->getType()->isFunctionProtoType();
15348 return false;
15351 static bool
15352 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
15353 const FunctionDecl *&PossiblePrototype) {
15354 // Don't warn about invalid declarations.
15355 if (FD->isInvalidDecl())
15356 return false;
15358 // Or declarations that aren't global.
15359 if (!FD->isGlobal())
15360 return false;
15362 // Don't warn about C++ member functions.
15363 if (isa<CXXMethodDecl>(FD))
15364 return false;
15366 // Don't warn about 'main'.
15367 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15368 if (IdentifierInfo *II = FD->getIdentifier())
15369 if (II->isStr("main") || II->isStr("efi_main"))
15370 return false;
15372 // Don't warn about inline functions.
15373 if (FD->isInlined())
15374 return false;
15376 // Don't warn about function templates.
15377 if (FD->getDescribedFunctionTemplate())
15378 return false;
15380 // Don't warn about function template specializations.
15381 if (FD->isFunctionTemplateSpecialization())
15382 return false;
15384 // Don't warn for OpenCL kernels.
15385 if (FD->hasAttr<OpenCLKernelAttr>())
15386 return false;
15388 // Don't warn on explicitly deleted functions.
15389 if (FD->isDeleted())
15390 return false;
15392 // Don't warn on implicitly local functions (such as having local-typed
15393 // parameters).
15394 if (!FD->isExternallyVisible())
15395 return false;
15397 // If we were able to find a potential prototype, don't warn.
15398 if (FindPossiblePrototype(FD, PossiblePrototype))
15399 return false;
15401 return true;
15404 void
15405 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
15406 const FunctionDecl *EffectiveDefinition,
15407 SkipBodyInfo *SkipBody) {
15408 const FunctionDecl *Definition = EffectiveDefinition;
15409 if (!Definition &&
15410 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15411 return;
15413 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15414 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15415 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15416 // A merged copy of the same function, instantiated as a member of
15417 // the same class, is OK.
15418 if (declaresSameEntity(OrigFD, OrigDef) &&
15419 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15420 cast<Decl>(FD->getLexicalDeclContext())))
15421 return;
15426 if (canRedefineFunction(Definition, getLangOpts()))
15427 return;
15429 // Don't emit an error when this is redefinition of a typo-corrected
15430 // definition.
15431 if (TypoCorrectedFunctionDefinitions.count(Definition))
15432 return;
15434 // If we don't have a visible definition of the function, and it's inline or
15435 // a template, skip the new definition.
15436 if (SkipBody && !hasVisibleDefinition(Definition) &&
15437 (Definition->getFormalLinkage() == Linkage::Internal ||
15438 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15439 Definition->getNumTemplateParameterLists())) {
15440 SkipBody->ShouldSkip = true;
15441 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15442 if (auto *TD = Definition->getDescribedFunctionTemplate())
15443 makeMergedDefinitionVisible(TD);
15444 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
15445 return;
15448 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15449 Definition->getStorageClass() == SC_Extern)
15450 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15451 << FD << getLangOpts().CPlusPlus;
15452 else
15453 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15455 Diag(Definition->getLocation(), diag::note_previous_definition);
15456 FD->setInvalidDecl();
15459 LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
15460 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15462 LambdaScopeInfo *LSI = PushLambdaScope();
15463 LSI->CallOperator = CallOperator;
15464 LSI->Lambda = LambdaClass;
15465 LSI->ReturnType = CallOperator->getReturnType();
15466 // This function in calls in situation where the context of the call operator
15467 // is not entered, so we set AfterParameterList to false, so that
15468 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15469 LSI->AfterParameterList = false;
15470 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15472 if (LCD == LCD_None)
15473 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
15474 else if (LCD == LCD_ByCopy)
15475 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
15476 else if (LCD == LCD_ByRef)
15477 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
15478 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15480 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
15481 LSI->Mutable = !CallOperator->isConst();
15482 if (CallOperator->isExplicitObjectMemberFunction())
15483 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15485 // Add the captures to the LSI so they can be noted as already
15486 // captured within tryCaptureVar.
15487 auto I = LambdaClass->field_begin();
15488 for (const auto &C : LambdaClass->captures()) {
15489 if (C.capturesVariable()) {
15490 ValueDecl *VD = C.getCapturedVar();
15491 if (VD->isInitCapture())
15492 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
15493 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15494 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15495 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15496 /*EllipsisLoc*/C.isPackExpansion()
15497 ? C.getEllipsisLoc() : SourceLocation(),
15498 I->getType(), /*Invalid*/false);
15500 } else if (C.capturesThis()) {
15501 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15502 C.getCaptureKind() == LCK_StarThis);
15503 } else {
15504 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15505 I->getType());
15507 ++I;
15509 return LSI;
15512 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
15513 SkipBodyInfo *SkipBody,
15514 FnBodyKind BodyKind) {
15515 if (!D) {
15516 // Parsing the function declaration failed in some way. Push on a fake scope
15517 // anyway so we can try to parse the function body.
15518 PushFunctionScope();
15519 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15520 return D;
15523 FunctionDecl *FD = nullptr;
15525 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15526 FD = FunTmpl->getTemplatedDecl();
15527 else
15528 FD = cast<FunctionDecl>(D);
15530 // Do not push if it is a lambda because one is already pushed when building
15531 // the lambda in ActOnStartOfLambdaDefinition().
15532 if (!isLambdaCallOperator(FD))
15533 // [expr.const]/p14.1
15534 // An expression or conversion is in an immediate function context if it is
15535 // potentially evaluated and either: its innermost enclosing non-block scope
15536 // is a function parameter scope of an immediate function.
15537 PushExpressionEvaluationContext(
15538 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
15539 : ExprEvalContexts.back().Context);
15541 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15542 // context is nested in an immediate function context, so smaller contexts
15543 // that appear inside immediate functions (like variable initializers) are
15544 // considered to be inside an immediate function context even though by
15545 // themselves they are not immediate function contexts. But when a new
15546 // function is entered, we need to reset this tracking, since the entered
15547 // function might be not an immediate function.
15548 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15549 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15550 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15552 // Check for defining attributes before the check for redefinition.
15553 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15554 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15555 FD->dropAttr<AliasAttr>();
15556 FD->setInvalidDecl();
15558 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15559 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15560 FD->dropAttr<IFuncAttr>();
15561 FD->setInvalidDecl();
15563 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15564 if (!Context.getTargetInfo().hasFeature("fmv") &&
15565 !Attr->isDefaultVersion()) {
15566 // If function multi versioning disabled skip parsing function body
15567 // defined with non-default target_version attribute
15568 if (SkipBody)
15569 SkipBody->ShouldSkip = true;
15570 return nullptr;
15574 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15575 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15576 Ctor->isDefaultConstructor() &&
15577 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15578 // If this is an MS ABI dllexport default constructor, instantiate any
15579 // default arguments.
15580 InstantiateDefaultCtorDefaultArgs(Ctor);
15584 // See if this is a redefinition. If 'will have body' (or similar) is already
15585 // set, then these checks were already performed when it was set.
15586 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15587 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
15588 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15590 // If we're skipping the body, we're done. Don't enter the scope.
15591 if (SkipBody && SkipBody->ShouldSkip)
15592 return D;
15595 // Mark this function as "will have a body eventually". This lets users to
15596 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15597 // this function.
15598 FD->setWillHaveBody();
15600 // If we are instantiating a generic lambda call operator, push
15601 // a LambdaScopeInfo onto the function stack. But use the information
15602 // that's already been calculated (ActOnLambdaExpr) to prime the current
15603 // LambdaScopeInfo.
15604 // When the template operator is being specialized, the LambdaScopeInfo,
15605 // has to be properly restored so that tryCaptureVariable doesn't try
15606 // and capture any new variables. In addition when calculating potential
15607 // captures during transformation of nested lambdas, it is necessary to
15608 // have the LSI properly restored.
15609 if (isGenericLambdaCallOperatorSpecialization(FD)) {
15610 assert(inTemplateInstantiation() &&
15611 "There should be an active template instantiation on the stack "
15612 "when instantiating a generic lambda!");
15613 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15614 } else {
15615 // Enter a new function scope
15616 PushFunctionScope();
15619 // Builtin functions cannot be defined.
15620 if (unsigned BuiltinID = FD->getBuiltinID()) {
15621 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
15622 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
15623 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15624 FD->setInvalidDecl();
15628 // The return type of a function definition must be complete (C99 6.9.1p3).
15629 // C++23 [dcl.fct.def.general]/p2
15630 // The type of [...] the return for a function definition
15631 // shall not be a (possibly cv-qualified) class type that is incomplete
15632 // or abstract within the function body unless the function is deleted.
15633 QualType ResultType = FD->getReturnType();
15634 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15635 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15636 (RequireCompleteType(FD->getLocation(), ResultType,
15637 diag::err_func_def_incomplete_result) ||
15638 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(),
15639 diag::err_abstract_type_in_decl,
15640 AbstractReturnType)))
15641 FD->setInvalidDecl();
15643 if (FnBodyScope)
15644 PushDeclContext(FnBodyScope, FD);
15646 // Check the validity of our function parameters
15647 if (BodyKind != FnBodyKind::Delete)
15648 CheckParmsForFunctionDef(FD->parameters(),
15649 /*CheckParameterNames=*/true);
15651 // Add non-parameter declarations already in the function to the current
15652 // scope.
15653 if (FnBodyScope) {
15654 for (Decl *NPD : FD->decls()) {
15655 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15656 if (!NonParmDecl)
15657 continue;
15658 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15659 "parameters should not be in newly created FD yet");
15661 // If the decl has a name, make it accessible in the current scope.
15662 if (NonParmDecl->getDeclName())
15663 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15665 // Similarly, dive into enums and fish their constants out, making them
15666 // accessible in this scope.
15667 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15668 for (auto *EI : ED->enumerators())
15669 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15674 // Introduce our parameters into the function scope
15675 for (auto *Param : FD->parameters()) {
15676 Param->setOwningFunction(FD);
15678 // If this has an identifier, add it to the scope stack.
15679 if (Param->getIdentifier() && FnBodyScope) {
15680 CheckShadow(FnBodyScope, Param);
15682 PushOnScopeChains(Param, FnBodyScope);
15686 // C++ [module.import/6] external definitions are not permitted in header
15687 // units. Deleted and Defaulted functions are implicitly inline (but the
15688 // inline state is not set at this point, so check the BodyKind explicitly).
15689 // FIXME: Consider an alternate location for the test where the inlined()
15690 // state is complete.
15691 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15692 !FD->isInvalidDecl() && !FD->isInlined() &&
15693 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15694 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15695 !FD->isTemplateInstantiation()) {
15696 assert(FD->isThisDeclarationADefinition());
15697 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15698 FD->setInvalidDecl();
15701 // Ensure that the function's exception specification is instantiated.
15702 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15703 ResolveExceptionSpec(D->getLocation(), FPT);
15705 // dllimport cannot be applied to non-inline function definitions.
15706 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15707 !FD->isTemplateInstantiation()) {
15708 assert(!FD->hasAttr<DLLExportAttr>());
15709 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15710 FD->setInvalidDecl();
15711 return D;
15713 // We want to attach documentation to original Decl (which might be
15714 // a function template).
15715 ActOnDocumentableDecl(D);
15716 if (getCurLexicalContext()->isObjCContainer() &&
15717 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15718 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15719 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15721 return D;
15724 /// Given the set of return statements within a function body,
15725 /// compute the variables that are subject to the named return value
15726 /// optimization.
15728 /// Each of the variables that is subject to the named return value
15729 /// optimization will be marked as NRVO variables in the AST, and any
15730 /// return statement that has a marked NRVO variable as its NRVO candidate can
15731 /// use the named return value optimization.
15733 /// This function applies a very simplistic algorithm for NRVO: if every return
15734 /// statement in the scope of a variable has the same NRVO candidate, that
15735 /// candidate is an NRVO variable.
15736 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
15737 ReturnStmt **Returns = Scope->Returns.data();
15739 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15740 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15741 if (!NRVOCandidate->isNRVOVariable())
15742 Returns[I]->setNRVOCandidate(nullptr);
15747 bool Sema::canDelayFunctionBody(const Declarator &D) {
15748 // We can't delay parsing the body of a constexpr function template (yet).
15749 if (D.getDeclSpec().hasConstexprSpecifier())
15750 return false;
15752 // We can't delay parsing the body of a function template with a deduced
15753 // return type (yet).
15754 if (D.getDeclSpec().hasAutoTypeSpec()) {
15755 // If the placeholder introduces a non-deduced trailing return type,
15756 // we can still delay parsing it.
15757 if (D.getNumTypeObjects()) {
15758 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15759 if (Outer.Kind == DeclaratorChunk::Function &&
15760 Outer.Fun.hasTrailingReturnType()) {
15761 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15762 return Ty.isNull() || !Ty->isUndeducedType();
15765 return false;
15768 return true;
15771 bool Sema::canSkipFunctionBody(Decl *D) {
15772 // We cannot skip the body of a function (or function template) which is
15773 // constexpr, since we may need to evaluate its body in order to parse the
15774 // rest of the file.
15775 // We cannot skip the body of a function with an undeduced return type,
15776 // because any callers of that function need to know the type.
15777 if (const FunctionDecl *FD = D->getAsFunction()) {
15778 if (FD->isConstexpr())
15779 return false;
15780 // We can't simply call Type::isUndeducedType here, because inside template
15781 // auto can be deduced to a dependent type, which is not considered
15782 // "undeduced".
15783 if (FD->getReturnType()->getContainedDeducedType())
15784 return false;
15786 return Consumer.shouldSkipFunctionBody(D);
15789 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
15790 if (!Decl)
15791 return nullptr;
15792 if (FunctionDecl *FD = Decl->getAsFunction())
15793 FD->setHasSkippedBody();
15794 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15795 MD->setHasSkippedBody();
15796 return Decl;
15799 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
15800 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15803 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
15804 /// body.
15805 class ExitFunctionBodyRAII {
15806 public:
15807 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15808 ~ExitFunctionBodyRAII() {
15809 if (!IsLambda)
15810 S.PopExpressionEvaluationContext();
15813 private:
15814 Sema &S;
15815 bool IsLambda = false;
15818 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
15819 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15821 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15822 if (EscapeInfo.count(BD))
15823 return EscapeInfo[BD];
15825 bool R = false;
15826 const BlockDecl *CurBD = BD;
15828 do {
15829 R = !CurBD->doesNotEscape();
15830 if (R)
15831 break;
15832 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15833 } while (CurBD);
15835 return EscapeInfo[BD] = R;
15838 // If the location where 'self' is implicitly retained is inside a escaping
15839 // block, emit a diagnostic.
15840 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15841 S.ImplicitlyRetainedSelfLocs)
15842 if (IsOrNestedInEscapingBlock(P.second))
15843 S.Diag(P.first, diag::warn_implicitly_retains_self)
15844 << FixItHint::CreateInsertion(P.first, "self->");
15847 void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
15848 if (!FD)
15849 return;
15850 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
15851 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15852 return;
15853 // Allow `get_return_object()`.
15854 if (FD->getDeclName().isIdentifier() &&
15855 FD->getName().equals("get_return_object") && FD->param_empty())
15856 return;
15857 if (!FD->hasAttr<CoroWrapperAttr>())
15858 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15861 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
15862 bool IsInstantiation) {
15863 FunctionScopeInfo *FSI = getCurFunction();
15864 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15866 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15867 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15869 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15870 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15872 if (getLangOpts().Coroutines) {
15873 if (FSI->isCoroutine())
15874 CheckCompletedCoroutineBody(FD, Body);
15875 else
15876 CheckCoroutineWrapper(FD);
15880 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15881 // one is already popped when finishing the lambda in BuildLambdaExpr().
15882 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15883 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15884 if (FD) {
15885 FD->setBody(Body);
15886 FD->setWillHaveBody(false);
15887 CheckImmediateEscalatingFunctionDefinition(FD, FSI);
15889 if (getLangOpts().CPlusPlus14) {
15890 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15891 FD->getReturnType()->isUndeducedType()) {
15892 // For a function with a deduced result type to return void,
15893 // the result type as written must be 'auto' or 'decltype(auto)',
15894 // possibly cv-qualified or constrained, but not ref-qualified.
15895 if (!FD->getReturnType()->getAs<AutoType>()) {
15896 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15897 << FD->getReturnType();
15898 FD->setInvalidDecl();
15899 } else {
15900 // Falling off the end of the function is the same as 'return;'.
15901 Expr *Dummy = nullptr;
15902 if (DeduceFunctionTypeFromReturnExpr(
15903 FD, dcl->getLocation(), Dummy,
15904 FD->getReturnType()->getAs<AutoType>()))
15905 FD->setInvalidDecl();
15908 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
15909 // In C++11, we don't use 'auto' deduction rules for lambda call
15910 // operators because we don't support return type deduction.
15911 auto *LSI = getCurLambda();
15912 if (LSI->HasImplicitReturnType) {
15913 deduceClosureReturnType(*LSI);
15915 // C++11 [expr.prim.lambda]p4:
15916 // [...] if there are no return statements in the compound-statement
15917 // [the deduced type is] the type void
15918 QualType RetType =
15919 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15921 // Update the return type to the deduced type.
15922 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15923 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15924 Proto->getExtProtoInfo()));
15928 // If the function implicitly returns zero (like 'main') or is naked,
15929 // don't complain about missing return statements.
15930 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15931 WP.disableCheckFallThrough();
15933 // MSVC permits the use of pure specifier (=0) on function definition,
15934 // defined at class scope, warn about this non-standard construct.
15935 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
15936 Diag(FD->getLocation(), diag::ext_pure_function_definition);
15938 if (!FD->isInvalidDecl()) {
15939 // Don't diagnose unused parameters of defaulted, deleted or naked
15940 // functions.
15941 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15942 !FD->hasAttr<NakedAttr>())
15943 DiagnoseUnusedParameters(FD->parameters());
15944 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
15945 FD->getReturnType(), FD);
15947 // If this is a structor, we need a vtable.
15948 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15949 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15950 else if (CXXDestructorDecl *Destructor =
15951 dyn_cast<CXXDestructorDecl>(FD))
15952 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15954 // Try to apply the named return value optimization. We have to check
15955 // if we can do this here because lambdas keep return statements around
15956 // to deduce an implicit return type.
15957 if (FD->getReturnType()->isRecordType() &&
15958 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
15959 computeNRVO(Body, FSI);
15962 // GNU warning -Wmissing-prototypes:
15963 // Warn if a global function is defined without a previous
15964 // prototype declaration. This warning is issued even if the
15965 // definition itself provides a prototype. The aim is to detect
15966 // global functions that fail to be declared in header files.
15967 const FunctionDecl *PossiblePrototype = nullptr;
15968 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15969 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15971 if (PossiblePrototype) {
15972 // We found a declaration that is not a prototype,
15973 // but that could be a zero-parameter prototype
15974 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15975 TypeLoc TL = TI->getTypeLoc();
15976 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
15977 Diag(PossiblePrototype->getLocation(),
15978 diag::note_declaration_not_a_prototype)
15979 << (FD->getNumParams() != 0)
15980 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
15981 FTL.getRParenLoc(), "void")
15982 : FixItHint{});
15984 } else {
15985 // Returns true if the token beginning at this Loc is `const`.
15986 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15987 const LangOptions &LangOpts) {
15988 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15989 if (LocInfo.first.isInvalid())
15990 return false;
15992 bool Invalid = false;
15993 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15994 if (Invalid)
15995 return false;
15997 if (LocInfo.second > Buffer.size())
15998 return false;
16000 const char *LexStart = Buffer.data() + LocInfo.second;
16001 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16003 return StartTok.consume_front("const") &&
16004 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16005 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16008 auto findBeginLoc = [&]() {
16009 // If the return type has `const` qualifier, we want to insert
16010 // `static` before `const` (and not before the typename).
16011 if ((FD->getReturnType()->isAnyPointerType() &&
16012 FD->getReturnType()->getPointeeType().isConstQualified()) ||
16013 FD->getReturnType().isConstQualified()) {
16014 // But only do this if we can determine where the `const` is.
16016 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16017 getLangOpts()))
16019 return FD->getBeginLoc();
16021 return FD->getTypeSpecStartLoc();
16023 Diag(FD->getTypeSpecStartLoc(),
16024 diag::note_static_for_internal_linkage)
16025 << /* function */ 1
16026 << (FD->getStorageClass() == SC_None
16027 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16028 : FixItHint{});
16032 // We might not have found a prototype because we didn't wish to warn on
16033 // the lack of a missing prototype. Try again without the checks for
16034 // whether we want to warn on the missing prototype.
16035 if (!PossiblePrototype)
16036 (void)FindPossiblePrototype(FD, PossiblePrototype);
16038 // If the function being defined does not have a prototype, then we may
16039 // need to diagnose it as changing behavior in C23 because we now know
16040 // whether the function accepts arguments or not. This only handles the
16041 // case where the definition has no prototype but does have parameters
16042 // and either there is no previous potential prototype, or the previous
16043 // potential prototype also has no actual prototype. This handles cases
16044 // like:
16045 // void f(); void f(a) int a; {}
16046 // void g(a) int a; {}
16047 // See MergeFunctionDecl() for other cases of the behavior change
16048 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16049 // type without a prototype.
16050 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16051 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16052 !PossiblePrototype->isImplicit()))) {
16053 // The function definition has parameters, so this will change behavior
16054 // in C23. If there is a possible prototype, it comes before the
16055 // function definition.
16056 // FIXME: The declaration may have already been diagnosed as being
16057 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16058 // there's no way to test for the "changes behavior" condition in
16059 // SemaType.cpp when forming the declaration's function type. So, we do
16060 // this awkward dance instead.
16062 // If we have a possible prototype and it declares a function with a
16063 // prototype, we don't want to diagnose it; if we have a possible
16064 // prototype and it has no prototype, it may have already been
16065 // diagnosed in SemaType.cpp as deprecated depending on whether
16066 // -Wstrict-prototypes is enabled. If we already warned about it being
16067 // deprecated, add a note that it also changes behavior. If we didn't
16068 // warn about it being deprecated (because the diagnostic is not
16069 // enabled), warn now that it is deprecated and changes behavior.
16071 // This K&R C function definition definitely changes behavior in C23,
16072 // so diagnose it.
16073 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16074 << /*definition*/ 1 << /* not supported in C23 */ 0;
16076 // If we have a possible prototype for the function which is a user-
16077 // visible declaration, we already tested that it has no prototype.
16078 // This will change behavior in C23. This gets a warning rather than a
16079 // note because it's the same behavior-changing problem as with the
16080 // definition.
16081 if (PossiblePrototype)
16082 Diag(PossiblePrototype->getLocation(),
16083 diag::warn_non_prototype_changes_behavior)
16084 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16085 << /*definition*/ 1;
16088 // Warn on CPUDispatch with an actual body.
16089 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16090 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16091 if (!CmpndBody->body_empty())
16092 Diag(CmpndBody->body_front()->getBeginLoc(),
16093 diag::warn_dispatch_body_ignored);
16095 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16096 const CXXMethodDecl *KeyFunction;
16097 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16098 MD->isVirtual() &&
16099 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16100 MD == KeyFunction->getCanonicalDecl()) {
16101 // Update the key-function state if necessary for this ABI.
16102 if (FD->isInlined() &&
16103 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16104 Context.setNonKeyFunction(MD);
16106 // If the newly-chosen key function is already defined, then we
16107 // need to mark the vtable as used retroactively.
16108 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16109 const FunctionDecl *Definition;
16110 if (KeyFunction && KeyFunction->isDefined(Definition))
16111 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16112 } else {
16113 // We just defined they key function; mark the vtable as used.
16114 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16119 assert(
16120 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
16121 "Function parsing confused");
16122 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16123 assert(MD == getCurMethodDecl() && "Method parsing confused");
16124 MD->setBody(Body);
16125 if (!MD->isInvalidDecl()) {
16126 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
16127 MD->getReturnType(), MD);
16129 if (Body)
16130 computeNRVO(Body, FSI);
16132 if (FSI->ObjCShouldCallSuper) {
16133 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16134 << MD->getSelector().getAsString();
16135 FSI->ObjCShouldCallSuper = false;
16137 if (FSI->ObjCWarnForNoDesignatedInitChain) {
16138 const ObjCMethodDecl *InitMethod = nullptr;
16139 bool isDesignated =
16140 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16141 assert(isDesignated && InitMethod);
16142 (void)isDesignated;
16144 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16145 auto IFace = MD->getClassInterface();
16146 if (!IFace)
16147 return false;
16148 auto SuperD = IFace->getSuperClass();
16149 if (!SuperD)
16150 return false;
16151 return SuperD->getIdentifier() ==
16152 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16154 // Don't issue this warning for unavailable inits or direct subclasses
16155 // of NSObject.
16156 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16157 Diag(MD->getLocation(),
16158 diag::warn_objc_designated_init_missing_super_call);
16159 Diag(InitMethod->getLocation(),
16160 diag::note_objc_designated_init_marked_here);
16162 FSI->ObjCWarnForNoDesignatedInitChain = false;
16164 if (FSI->ObjCWarnForNoInitDelegation) {
16165 // Don't issue this warning for unavaialable inits.
16166 if (!MD->isUnavailable())
16167 Diag(MD->getLocation(),
16168 diag::warn_objc_secondary_init_missing_init_call);
16169 FSI->ObjCWarnForNoInitDelegation = false;
16172 diagnoseImplicitlyRetainedSelf(*this);
16173 } else {
16174 // Parsing the function declaration failed in some way. Pop the fake scope
16175 // we pushed on.
16176 PopFunctionScopeInfo(ActivePolicy, dcl);
16177 return nullptr;
16180 if (Body && FSI->HasPotentialAvailabilityViolations)
16181 DiagnoseUnguardedAvailabilityViolations(dcl);
16183 assert(!FSI->ObjCShouldCallSuper &&
16184 "This should only be set for ObjC methods, which should have been "
16185 "handled in the block above.");
16187 // Verify and clean out per-function state.
16188 if (Body && (!FD || !FD->isDefaulted())) {
16189 // C++ constructors that have function-try-blocks can't have return
16190 // statements in the handlers of that block. (C++ [except.handle]p14)
16191 // Verify this.
16192 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16193 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16195 // Verify that gotos and switch cases don't jump into scopes illegally.
16196 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16197 DiagnoseInvalidJumps(Body);
16199 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16200 if (!Destructor->getParent()->isDependentType())
16201 CheckDestructor(Destructor);
16203 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
16204 Destructor->getParent());
16207 // If any errors have occurred, clear out any temporaries that may have
16208 // been leftover. This ensures that these temporaries won't be picked up
16209 // for deletion in some later function.
16210 if (hasUncompilableErrorOccurred() ||
16211 hasAnyUnrecoverableErrorsInThisFunction() ||
16212 getDiagnostics().getSuppressAllDiagnostics()) {
16213 DiscardCleanupsInEvaluationContext();
16215 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16216 // Since the body is valid, issue any analysis-based warnings that are
16217 // enabled.
16218 ActivePolicy = &WP;
16221 if (!IsInstantiation && FD &&
16222 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16223 !FD->isInvalidDecl() &&
16224 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
16225 FD->setInvalidDecl();
16227 if (FD && FD->hasAttr<NakedAttr>()) {
16228 for (const Stmt *S : Body->children()) {
16229 // Allow local register variables without initializer as they don't
16230 // require prologue.
16231 bool RegisterVariables = false;
16232 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16233 for (const auto *Decl : DS->decls()) {
16234 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16235 RegisterVariables =
16236 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16237 if (!RegisterVariables)
16238 break;
16242 if (RegisterVariables)
16243 continue;
16244 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16245 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16246 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16247 FD->setInvalidDecl();
16248 break;
16253 assert(ExprCleanupObjects.size() ==
16254 ExprEvalContexts.back().NumCleanupObjects &&
16255 "Leftover temporaries in function");
16256 assert(!Cleanup.exprNeedsCleanups() &&
16257 "Unaccounted cleanups in function");
16258 assert(MaybeODRUseExprs.empty() &&
16259 "Leftover expressions for odr-use checking");
16261 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16262 // the declaration context below. Otherwise, we're unable to transform
16263 // 'this' expressions when transforming immediate context functions.
16265 if (!IsInstantiation)
16266 PopDeclContext();
16268 PopFunctionScopeInfo(ActivePolicy, dcl);
16269 // If any errors have occurred, clear out any temporaries that may have
16270 // been leftover. This ensures that these temporaries won't be picked up for
16271 // deletion in some later function.
16272 if (hasUncompilableErrorOccurred()) {
16273 DiscardCleanupsInEvaluationContext();
16276 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16277 !LangOpts.OMPTargetTriples.empty())) ||
16278 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16279 auto ES = getEmissionStatus(FD);
16280 if (ES == Sema::FunctionEmissionStatus::Emitted ||
16281 ES == Sema::FunctionEmissionStatus::Unknown)
16282 DeclsToCheckForDeferredDiags.insert(FD);
16285 if (FD && !FD->isDeleted())
16286 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16288 return dcl;
16291 /// When we finish delayed parsing of an attribute, we must attach it to the
16292 /// relevant Decl.
16293 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
16294 ParsedAttributes &Attrs) {
16295 // Always attach attributes to the underlying decl.
16296 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16297 D = TD->getTemplatedDecl();
16298 ProcessDeclAttributeList(S, D, Attrs);
16300 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16301 if (Method->isStatic())
16302 checkThisInStaticMemberFunctionAttributes(Method);
16305 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
16306 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
16307 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
16308 IdentifierInfo &II, Scope *S) {
16309 // It is not valid to implicitly define a function in C23.
16310 assert(LangOpts.implicitFunctionsAllowed() &&
16311 "Implicit function declarations aren't allowed in this language mode");
16313 // Find the scope in which the identifier is injected and the corresponding
16314 // DeclContext.
16315 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16316 // In that case, we inject the declaration into the translation unit scope
16317 // instead.
16318 Scope *BlockScope = S;
16319 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16320 BlockScope = BlockScope->getParent();
16322 // Loop until we find a DeclContext that is either a function/method or the
16323 // translation unit, which are the only two valid places to implicitly define
16324 // a function. This avoids accidentally defining the function within a tag
16325 // declaration, for example.
16326 Scope *ContextScope = BlockScope;
16327 while (!ContextScope->getEntity() ||
16328 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16329 !ContextScope->getEntity()->isTranslationUnit()))
16330 ContextScope = ContextScope->getParent();
16331 ContextRAII SavedContext(*this, ContextScope->getEntity());
16333 // Before we produce a declaration for an implicitly defined
16334 // function, see whether there was a locally-scoped declaration of
16335 // this name as a function or variable. If so, use that
16336 // (non-visible) declaration, and complain about it.
16337 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16338 if (ExternCPrev) {
16339 // We still need to inject the function into the enclosing block scope so
16340 // that later (non-call) uses can see it.
16341 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16343 // C89 footnote 38:
16344 // If in fact it is not defined as having type "function returning int",
16345 // the behavior is undefined.
16346 if (!isa<FunctionDecl>(ExternCPrev) ||
16347 !Context.typesAreCompatible(
16348 cast<FunctionDecl>(ExternCPrev)->getType(),
16349 Context.getFunctionNoProtoType(Context.IntTy))) {
16350 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16351 << ExternCPrev << !getLangOpts().C99;
16352 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16353 return ExternCPrev;
16357 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16358 unsigned diag_id;
16359 if (II.getName().starts_with("__builtin_"))
16360 diag_id = diag::warn_builtin_unknown;
16361 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16362 else if (getLangOpts().C99)
16363 diag_id = diag::ext_implicit_function_decl_c99;
16364 else
16365 diag_id = diag::warn_implicit_function_decl;
16367 TypoCorrection Corrected;
16368 // Because typo correction is expensive, only do it if the implicit
16369 // function declaration is going to be treated as an error.
16371 // Perform the correction before issuing the main diagnostic, as some
16372 // consumers use typo-correction callbacks to enhance the main diagnostic.
16373 if (S && !ExternCPrev &&
16374 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
16375 DeclFilterCCC<FunctionDecl> CCC{};
16376 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
16377 S, nullptr, CCC, CTK_NonError);
16380 Diag(Loc, diag_id) << &II;
16381 if (Corrected) {
16382 // If the correction is going to suggest an implicitly defined function,
16383 // skip the correction as not being a particularly good idea.
16384 bool Diagnose = true;
16385 if (const auto *D = Corrected.getCorrectionDecl())
16386 Diagnose = !D->isImplicit();
16387 if (Diagnose)
16388 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16389 /*ErrorRecovery*/ false);
16392 // If we found a prior declaration of this function, don't bother building
16393 // another one. We've already pushed that one into scope, so there's nothing
16394 // more to do.
16395 if (ExternCPrev)
16396 return ExternCPrev;
16398 // Set a Declarator for the implicit definition: int foo();
16399 const char *Dummy;
16400 AttributeFactory attrFactory;
16401 DeclSpec DS(attrFactory);
16402 unsigned DiagID;
16403 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16404 Context.getPrintingPolicy());
16405 (void)Error; // Silence warning.
16406 assert(!Error && "Error setting up implicit decl!");
16407 SourceLocation NoLoc;
16408 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
16409 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16410 /*IsAmbiguous=*/false,
16411 /*LParenLoc=*/NoLoc,
16412 /*Params=*/nullptr,
16413 /*NumParams=*/0,
16414 /*EllipsisLoc=*/NoLoc,
16415 /*RParenLoc=*/NoLoc,
16416 /*RefQualifierIsLvalueRef=*/true,
16417 /*RefQualifierLoc=*/NoLoc,
16418 /*MutableLoc=*/NoLoc, EST_None,
16419 /*ESpecRange=*/SourceRange(),
16420 /*Exceptions=*/nullptr,
16421 /*ExceptionRanges=*/nullptr,
16422 /*NumExceptions=*/0,
16423 /*NoexceptExpr=*/nullptr,
16424 /*ExceptionSpecTokens=*/nullptr,
16425 /*DeclsInPrototype=*/std::nullopt,
16426 Loc, Loc, D),
16427 std::move(DS.getAttributes()), SourceLocation());
16428 D.SetIdentifier(&II, Loc);
16430 // Insert this function into the enclosing block scope.
16431 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16432 FD->setImplicit();
16434 AddKnownFunctionAttributes(FD);
16436 return FD;
16439 /// If this function is a C++ replaceable global allocation function
16440 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
16441 /// adds any function attributes that we know a priori based on the standard.
16443 /// We need to check for duplicate attributes both here and where user-written
16444 /// attributes are applied to declarations.
16445 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
16446 FunctionDecl *FD) {
16447 if (FD->isInvalidDecl())
16448 return;
16450 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16451 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16452 return;
16454 std::optional<unsigned> AlignmentParam;
16455 bool IsNothrow = false;
16456 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16457 return;
16459 // C++2a [basic.stc.dynamic.allocation]p4:
16460 // An allocation function that has a non-throwing exception specification
16461 // indicates failure by returning a null pointer value. Any other allocation
16462 // function never returns a null pointer value and indicates failure only by
16463 // throwing an exception [...]
16465 // However, -fcheck-new invalidates this possible assumption, so don't add
16466 // NonNull when that is enabled.
16467 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16468 !getLangOpts().CheckNew)
16469 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16471 // C++2a [basic.stc.dynamic.allocation]p2:
16472 // An allocation function attempts to allocate the requested amount of
16473 // storage. [...] If the request succeeds, the value returned by a
16474 // replaceable allocation function is a [...] pointer value p0 different
16475 // from any previously returned value p1 [...]
16477 // However, this particular information is being added in codegen,
16478 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16480 // C++2a [basic.stc.dynamic.allocation]p2:
16481 // An allocation function attempts to allocate the requested amount of
16482 // storage. If it is successful, it returns the address of the start of a
16483 // block of storage whose length in bytes is at least as large as the
16484 // requested size.
16485 if (!FD->hasAttr<AllocSizeAttr>()) {
16486 FD->addAttr(AllocSizeAttr::CreateImplicit(
16487 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16488 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16491 // C++2a [basic.stc.dynamic.allocation]p3:
16492 // For an allocation function [...], the pointer returned on a successful
16493 // call shall represent the address of storage that is aligned as follows:
16494 // (3.1) If the allocation function takes an argument of type
16495 // std​::​align_­val_­t, the storage will have the alignment
16496 // specified by the value of this argument.
16497 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16498 FD->addAttr(AllocAlignAttr::CreateImplicit(
16499 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16502 // FIXME:
16503 // C++2a [basic.stc.dynamic.allocation]p3:
16504 // For an allocation function [...], the pointer returned on a successful
16505 // call shall represent the address of storage that is aligned as follows:
16506 // (3.2) Otherwise, if the allocation function is named operator new[],
16507 // the storage is aligned for any object that does not have
16508 // new-extended alignment ([basic.align]) and is no larger than the
16509 // requested size.
16510 // (3.3) Otherwise, the storage is aligned for any object that does not
16511 // have new-extended alignment and is of the requested size.
16514 /// Adds any function attributes that we know a priori based on
16515 /// the declaration of this function.
16517 /// These attributes can apply both to implicitly-declared builtins
16518 /// (like __builtin___printf_chk) or to library-declared functions
16519 /// like NSLog or printf.
16521 /// We need to check for duplicate attributes both here and where user-written
16522 /// attributes are applied to declarations.
16523 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
16524 if (FD->isInvalidDecl())
16525 return;
16527 // If this is a built-in function, map its builtin attributes to
16528 // actual attributes.
16529 if (unsigned BuiltinID = FD->getBuiltinID()) {
16530 // Handle printf-formatting attributes.
16531 unsigned FormatIdx;
16532 bool HasVAListArg;
16533 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16534 if (!FD->hasAttr<FormatAttr>()) {
16535 const char *fmt = "printf";
16536 unsigned int NumParams = FD->getNumParams();
16537 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16538 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16539 fmt = "NSString";
16540 FD->addAttr(FormatAttr::CreateImplicit(Context,
16541 &Context.Idents.get(fmt),
16542 FormatIdx+1,
16543 HasVAListArg ? 0 : FormatIdx+2,
16544 FD->getLocation()));
16547 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16548 HasVAListArg)) {
16549 if (!FD->hasAttr<FormatAttr>())
16550 FD->addAttr(FormatAttr::CreateImplicit(Context,
16551 &Context.Idents.get("scanf"),
16552 FormatIdx+1,
16553 HasVAListArg ? 0 : FormatIdx+2,
16554 FD->getLocation()));
16557 // Handle automatically recognized callbacks.
16558 SmallVector<int, 4> Encoding;
16559 if (!FD->hasAttr<CallbackAttr>() &&
16560 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16561 FD->addAttr(CallbackAttr::CreateImplicit(
16562 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16564 // Mark const if we don't care about errno and/or floating point exceptions
16565 // that are the only thing preventing the function from being const. This
16566 // allows IRgen to use LLVM intrinsics for such functions.
16567 bool NoExceptions =
16568 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
16569 bool ConstWithoutErrnoAndExceptions =
16570 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
16571 bool ConstWithoutExceptions =
16572 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
16573 if (!FD->hasAttr<ConstAttr>() &&
16574 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16575 (!ConstWithoutErrnoAndExceptions ||
16576 (!getLangOpts().MathErrno && NoExceptions)) &&
16577 (!ConstWithoutExceptions || NoExceptions))
16578 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16580 // We make "fma" on GNU or Windows const because we know it does not set
16581 // errno in those environments even though it could set errno based on the
16582 // C standard.
16583 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16584 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16585 !FD->hasAttr<ConstAttr>()) {
16586 switch (BuiltinID) {
16587 case Builtin::BI__builtin_fma:
16588 case Builtin::BI__builtin_fmaf:
16589 case Builtin::BI__builtin_fmal:
16590 case Builtin::BIfma:
16591 case Builtin::BIfmaf:
16592 case Builtin::BIfmal:
16593 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16594 break;
16595 default:
16596 break;
16600 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16601 !FD->hasAttr<ReturnsTwiceAttr>())
16602 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16603 FD->getLocation()));
16604 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16605 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16606 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16607 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16608 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16609 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16610 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16611 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16612 // Add the appropriate attribute, depending on the CUDA compilation mode
16613 // and which target the builtin belongs to. For example, during host
16614 // compilation, aux builtins are __device__, while the rest are __host__.
16615 if (getLangOpts().CUDAIsDevice !=
16616 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
16617 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16618 else
16619 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16622 // Add known guaranteed alignment for allocation functions.
16623 switch (BuiltinID) {
16624 case Builtin::BImemalign:
16625 case Builtin::BIaligned_alloc:
16626 if (!FD->hasAttr<AllocAlignAttr>())
16627 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16628 FD->getLocation()));
16629 break;
16630 default:
16631 break;
16634 // Add allocsize attribute for allocation functions.
16635 switch (BuiltinID) {
16636 case Builtin::BIcalloc:
16637 FD->addAttr(AllocSizeAttr::CreateImplicit(
16638 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16639 break;
16640 case Builtin::BImemalign:
16641 case Builtin::BIaligned_alloc:
16642 case Builtin::BIrealloc:
16643 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16644 ParamIdx(), FD->getLocation()));
16645 break;
16646 case Builtin::BImalloc:
16647 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16648 ParamIdx(), FD->getLocation()));
16649 break;
16650 default:
16651 break;
16654 // Add lifetime attribute to std::move, std::fowrard et al.
16655 switch (BuiltinID) {
16656 case Builtin::BIaddressof:
16657 case Builtin::BI__addressof:
16658 case Builtin::BI__builtin_addressof:
16659 case Builtin::BIas_const:
16660 case Builtin::BIforward:
16661 case Builtin::BIforward_like:
16662 case Builtin::BImove:
16663 case Builtin::BImove_if_noexcept:
16664 if (ParmVarDecl *P = FD->getParamDecl(0u);
16665 !P->hasAttr<LifetimeBoundAttr>())
16666 P->addAttr(
16667 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16668 break;
16669 default:
16670 break;
16674 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
16676 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16677 // throw, add an implicit nothrow attribute to any extern "C" function we come
16678 // across.
16679 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16680 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16681 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16682 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16683 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16686 IdentifierInfo *Name = FD->getIdentifier();
16687 if (!Name)
16688 return;
16689 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) ||
16690 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16691 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16692 LinkageSpecLanguageIDs::C)) {
16693 // Okay: this could be a libc/libm/Objective-C function we know
16694 // about.
16695 } else
16696 return;
16698 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16699 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16700 // target-specific builtins, perhaps?
16701 if (!FD->hasAttr<FormatAttr>())
16702 FD->addAttr(FormatAttr::CreateImplicit(Context,
16703 &Context.Idents.get("printf"), 2,
16704 Name->isStr("vasprintf") ? 0 : 3,
16705 FD->getLocation()));
16708 if (Name->isStr("__CFStringMakeConstantString")) {
16709 // We already have a __builtin___CFStringMakeConstantString,
16710 // but builds that use -fno-constant-cfstrings don't go through that.
16711 if (!FD->hasAttr<FormatArgAttr>())
16712 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16713 FD->getLocation()));
16717 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
16718 TypeSourceInfo *TInfo) {
16719 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16720 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16722 if (!TInfo) {
16723 assert(D.isInvalidType() && "no declarator info for valid type");
16724 TInfo = Context.getTrivialTypeSourceInfo(T);
16727 // Scope manipulation handled by caller.
16728 TypedefDecl *NewTD =
16729 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
16730 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16732 // Bail out immediately if we have an invalid declaration.
16733 if (D.isInvalidType()) {
16734 NewTD->setInvalidDecl();
16735 return NewTD;
16738 if (D.getDeclSpec().isModulePrivateSpecified()) {
16739 if (CurContext->isFunctionOrMethod())
16740 Diag(NewTD->getLocation(), diag::err_module_private_local)
16741 << 2 << NewTD
16742 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16743 << FixItHint::CreateRemoval(
16744 D.getDeclSpec().getModulePrivateSpecLoc());
16745 else
16746 NewTD->setModulePrivate();
16749 // C++ [dcl.typedef]p8:
16750 // If the typedef declaration defines an unnamed class (or
16751 // enum), the first typedef-name declared by the declaration
16752 // to be that class type (or enum type) is used to denote the
16753 // class type (or enum type) for linkage purposes only.
16754 // We need to check whether the type was declared in the declaration.
16755 switch (D.getDeclSpec().getTypeSpecType()) {
16756 case TST_enum:
16757 case TST_struct:
16758 case TST_interface:
16759 case TST_union:
16760 case TST_class: {
16761 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16762 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16763 break;
16766 default:
16767 break;
16770 return NewTD;
16773 /// Check that this is a valid underlying type for an enum declaration.
16774 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
16775 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16776 QualType T = TI->getType();
16778 if (T->isDependentType())
16779 return false;
16781 // This doesn't use 'isIntegralType' despite the error message mentioning
16782 // integral type because isIntegralType would also allow enum types in C.
16783 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16784 if (BT->isInteger())
16785 return false;
16787 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16788 << T << T->isBitIntType();
16791 /// Check whether this is a valid redeclaration of a previous enumeration.
16792 /// \return true if the redeclaration was invalid.
16793 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
16794 QualType EnumUnderlyingTy, bool IsFixed,
16795 const EnumDecl *Prev) {
16796 if (IsScoped != Prev->isScoped()) {
16797 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16798 << Prev->isScoped();
16799 Diag(Prev->getLocation(), diag::note_previous_declaration);
16800 return true;
16803 if (IsFixed && Prev->isFixed()) {
16804 if (!EnumUnderlyingTy->isDependentType() &&
16805 !Prev->getIntegerType()->isDependentType() &&
16806 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16807 Prev->getIntegerType())) {
16808 // TODO: Highlight the underlying type of the redeclaration.
16809 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16810 << EnumUnderlyingTy << Prev->getIntegerType();
16811 Diag(Prev->getLocation(), diag::note_previous_declaration)
16812 << Prev->getIntegerTypeRange();
16813 return true;
16815 } else if (IsFixed != Prev->isFixed()) {
16816 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16817 << Prev->isFixed();
16818 Diag(Prev->getLocation(), diag::note_previous_declaration);
16819 return true;
16822 return false;
16825 /// Get diagnostic %select index for tag kind for
16826 /// redeclaration diagnostic message.
16827 /// WARNING: Indexes apply to particular diagnostics only!
16829 /// \returns diagnostic %select index.
16830 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
16831 switch (Tag) {
16832 case TagTypeKind::Struct:
16833 return 0;
16834 case TagTypeKind::Interface:
16835 return 1;
16836 case TagTypeKind::Class:
16837 return 2;
16838 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16842 /// Determine if tag kind is a class-key compatible with
16843 /// class for redeclaration (class, struct, or __interface).
16845 /// \returns true iff the tag kind is compatible.
16846 static bool isClassCompatTagKind(TagTypeKind Tag)
16848 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16849 Tag == TagTypeKind::Interface;
16852 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
16853 TagTypeKind TTK) {
16854 if (isa<TypedefDecl>(PrevDecl))
16855 return NTK_Typedef;
16856 else if (isa<TypeAliasDecl>(PrevDecl))
16857 return NTK_TypeAlias;
16858 else if (isa<ClassTemplateDecl>(PrevDecl))
16859 return NTK_Template;
16860 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16861 return NTK_TypeAliasTemplate;
16862 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16863 return NTK_TemplateTemplateArgument;
16864 switch (TTK) {
16865 case TagTypeKind::Struct:
16866 case TagTypeKind::Interface:
16867 case TagTypeKind::Class:
16868 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16869 case TagTypeKind::Union:
16870 return NTK_NonUnion;
16871 case TagTypeKind::Enum:
16872 return NTK_NonEnum;
16874 llvm_unreachable("invalid TTK");
16877 /// Determine whether a tag with a given kind is acceptable
16878 /// as a redeclaration of the given tag declaration.
16880 /// \returns true if the new tag kind is acceptable, false otherwise.
16881 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
16882 TagTypeKind NewTag, bool isDefinition,
16883 SourceLocation NewTagLoc,
16884 const IdentifierInfo *Name) {
16885 // C++ [dcl.type.elab]p3:
16886 // The class-key or enum keyword present in the
16887 // elaborated-type-specifier shall agree in kind with the
16888 // declaration to which the name in the elaborated-type-specifier
16889 // refers. This rule also applies to the form of
16890 // elaborated-type-specifier that declares a class-name or
16891 // friend class since it can be construed as referring to the
16892 // definition of the class. Thus, in any
16893 // elaborated-type-specifier, the enum keyword shall be used to
16894 // refer to an enumeration (7.2), the union class-key shall be
16895 // used to refer to a union (clause 9), and either the class or
16896 // struct class-key shall be used to refer to a class (clause 9)
16897 // declared using the class or struct class-key.
16898 TagTypeKind OldTag = Previous->getTagKind();
16899 if (OldTag != NewTag &&
16900 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16901 return false;
16903 // Tags are compatible, but we might still want to warn on mismatched tags.
16904 // Non-class tags can't be mismatched at this point.
16905 if (!isClassCompatTagKind(NewTag))
16906 return true;
16908 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16909 // by our warning analysis. We don't want to warn about mismatches with (eg)
16910 // declarations in system headers that are designed to be specialized, but if
16911 // a user asks us to warn, we should warn if their code contains mismatched
16912 // declarations.
16913 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16914 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16915 Loc);
16917 if (IsIgnoredLoc(NewTagLoc))
16918 return true;
16920 auto IsIgnored = [&](const TagDecl *Tag) {
16921 return IsIgnoredLoc(Tag->getLocation());
16923 while (IsIgnored(Previous)) {
16924 Previous = Previous->getPreviousDecl();
16925 if (!Previous)
16926 return true;
16927 OldTag = Previous->getTagKind();
16930 bool isTemplate = false;
16931 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16932 isTemplate = Record->getDescribedClassTemplate();
16934 if (inTemplateInstantiation()) {
16935 if (OldTag != NewTag) {
16936 // In a template instantiation, do not offer fix-its for tag mismatches
16937 // since they usually mess up the template instead of fixing the problem.
16938 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16939 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16940 << getRedeclDiagFromTagKind(OldTag);
16941 // FIXME: Note previous location?
16943 return true;
16946 if (isDefinition) {
16947 // On definitions, check all previous tags and issue a fix-it for each
16948 // one that doesn't match the current tag.
16949 if (Previous->getDefinition()) {
16950 // Don't suggest fix-its for redefinitions.
16951 return true;
16954 bool previousMismatch = false;
16955 for (const TagDecl *I : Previous->redecls()) {
16956 if (I->getTagKind() != NewTag) {
16957 // Ignore previous declarations for which the warning was disabled.
16958 if (IsIgnored(I))
16959 continue;
16961 if (!previousMismatch) {
16962 previousMismatch = true;
16963 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16964 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16965 << getRedeclDiagFromTagKind(I->getTagKind());
16967 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16968 << getRedeclDiagFromTagKind(NewTag)
16969 << FixItHint::CreateReplacement(I->getInnerLocStart(),
16970 TypeWithKeyword::getTagTypeKindName(NewTag));
16973 return true;
16976 // Identify the prevailing tag kind: this is the kind of the definition (if
16977 // there is a non-ignored definition), or otherwise the kind of the prior
16978 // (non-ignored) declaration.
16979 const TagDecl *PrevDef = Previous->getDefinition();
16980 if (PrevDef && IsIgnored(PrevDef))
16981 PrevDef = nullptr;
16982 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16983 if (Redecl->getTagKind() != NewTag) {
16984 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16985 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16986 << getRedeclDiagFromTagKind(OldTag);
16987 Diag(Redecl->getLocation(), diag::note_previous_use);
16989 // If there is a previous definition, suggest a fix-it.
16990 if (PrevDef) {
16991 Diag(NewTagLoc, diag::note_struct_class_suggestion)
16992 << getRedeclDiagFromTagKind(Redecl->getTagKind())
16993 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
16994 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
16998 return true;
17001 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17002 /// from an outer enclosing namespace or file scope inside a friend declaration.
17003 /// This should provide the commented out code in the following snippet:
17004 /// namespace N {
17005 /// struct X;
17006 /// namespace M {
17007 /// struct Y { friend struct /*N::*/ X; };
17008 /// }
17009 /// }
17010 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
17011 SourceLocation NameLoc) {
17012 // While the decl is in a namespace, do repeated lookup of that name and see
17013 // if we get the same namespace back. If we do not, continue until
17014 // translation unit scope, at which point we have a fully qualified NNS.
17015 SmallVector<IdentifierInfo *, 4> Namespaces;
17016 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17017 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17018 // This tag should be declared in a namespace, which can only be enclosed by
17019 // other namespaces. Bail if there's an anonymous namespace in the chain.
17020 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17021 if (!Namespace || Namespace->isAnonymousNamespace())
17022 return FixItHint();
17023 IdentifierInfo *II = Namespace->getIdentifier();
17024 Namespaces.push_back(II);
17025 NamedDecl *Lookup = SemaRef.LookupSingleName(
17026 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17027 if (Lookup == Namespace)
17028 break;
17031 // Once we have all the namespaces, reverse them to go outermost first, and
17032 // build an NNS.
17033 SmallString<64> Insertion;
17034 llvm::raw_svector_ostream OS(Insertion);
17035 if (DC->isTranslationUnit())
17036 OS << "::";
17037 std::reverse(Namespaces.begin(), Namespaces.end());
17038 for (auto *II : Namespaces)
17039 OS << II->getName() << "::";
17040 return FixItHint::CreateInsertion(NameLoc, Insertion);
17043 /// Determine whether a tag originally declared in context \p OldDC can
17044 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17045 /// found a declaration in \p OldDC as a previous decl, perhaps through a
17046 /// using-declaration).
17047 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
17048 DeclContext *NewDC) {
17049 OldDC = OldDC->getRedeclContext();
17050 NewDC = NewDC->getRedeclContext();
17052 if (OldDC->Equals(NewDC))
17053 return true;
17055 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17056 // encloses the other).
17057 if (S.getLangOpts().MSVCCompat &&
17058 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17059 return true;
17061 return false;
17064 /// This is invoked when we see 'struct foo' or 'struct {'. In the
17065 /// former case, Name will be non-null. In the later case, Name will be null.
17066 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
17067 /// reference/declaration/definition of a tag.
17069 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
17070 /// trailing-type-specifier) other than one in an alias-declaration.
17072 /// \param SkipBody If non-null, will be set to indicate if the caller should
17073 /// skip the definition of this tag and treat it as if it were a declaration.
17074 DeclResult
17075 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17076 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17077 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17078 SourceLocation ModulePrivateLoc,
17079 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17080 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17081 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17082 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17083 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17084 // If this is not a definition, it must have a name.
17085 IdentifierInfo *OrigName = Name;
17086 assert((Name != nullptr || TUK == TUK_Definition) &&
17087 "Nameless record must be a definition!");
17088 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
17090 OwnedDecl = false;
17091 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17092 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17094 // FIXME: Check member specializations more carefully.
17095 bool isMemberSpecialization = false;
17096 bool Invalid = false;
17098 // We only need to do this matching if we have template parameters
17099 // or a scope specifier, which also conveniently avoids this work
17100 // for non-C++ cases.
17101 if (TemplateParameterLists.size() > 0 ||
17102 (SS.isNotEmpty() && TUK != TUK_Reference)) {
17103 if (TemplateParameterList *TemplateParams =
17104 MatchTemplateParametersToScopeSpecifier(
17105 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17106 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
17107 if (Kind == TagTypeKind::Enum) {
17108 Diag(KWLoc, diag::err_enum_template);
17109 return true;
17112 if (TemplateParams->size() > 0) {
17113 // This is a declaration or definition of a class template (which may
17114 // be a member of another template).
17116 if (Invalid)
17117 return true;
17119 OwnedDecl = false;
17120 DeclResult Result = CheckClassTemplate(
17121 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17122 AS, ModulePrivateLoc,
17123 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17124 TemplateParameterLists.data(), SkipBody);
17125 return Result.get();
17126 } else {
17127 // The "template<>" header is extraneous.
17128 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17129 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17130 isMemberSpecialization = true;
17134 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17135 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17136 return true;
17139 // Figure out the underlying type if this a enum declaration. We need to do
17140 // this early, because it's needed to detect if this is an incompatible
17141 // redeclaration.
17142 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17143 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17145 if (Kind == TagTypeKind::Enum) {
17146 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17147 // No underlying type explicitly specified, or we failed to parse the
17148 // type, default to int.
17149 EnumUnderlying = Context.IntTy.getTypePtr();
17150 } else if (UnderlyingType.get()) {
17151 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17152 // integral type; any cv-qualification is ignored.
17153 TypeSourceInfo *TI = nullptr;
17154 GetTypeFromParser(UnderlyingType.get(), &TI);
17155 EnumUnderlying = TI;
17157 if (CheckEnumUnderlyingType(TI))
17158 // Recover by falling back to int.
17159 EnumUnderlying = Context.IntTy.getTypePtr();
17161 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
17162 UPPC_FixedUnderlyingType))
17163 EnumUnderlying = Context.IntTy.getTypePtr();
17165 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17166 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17167 // of 'int'. However, if this is an unfixed forward declaration, don't set
17168 // the underlying type unless the user enables -fms-compatibility. This
17169 // makes unfixed forward declared enums incomplete and is more conforming.
17170 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
17171 EnumUnderlying = Context.IntTy.getTypePtr();
17175 DeclContext *SearchDC = CurContext;
17176 DeclContext *DC = CurContext;
17177 bool isStdBadAlloc = false;
17178 bool isStdAlignValT = false;
17180 RedeclarationKind Redecl = forRedeclarationInCurContext();
17181 if (TUK == TUK_Friend || TUK == TUK_Reference)
17182 Redecl = NotForRedeclaration;
17184 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17185 /// implemented asks for structural equivalence checking, the returned decl
17186 /// here is passed back to the parser, allowing the tag body to be parsed.
17187 auto createTagFromNewDecl = [&]() -> TagDecl * {
17188 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17189 // If there is an identifier, use the location of the identifier as the
17190 // location of the decl, otherwise use the location of the struct/union
17191 // keyword.
17192 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17193 TagDecl *New = nullptr;
17195 if (Kind == TagTypeKind::Enum) {
17196 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17197 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17198 // If this is an undefined enum, bail.
17199 if (TUK != TUK_Definition && !Invalid)
17200 return nullptr;
17201 if (EnumUnderlying) {
17202 EnumDecl *ED = cast<EnumDecl>(New);
17203 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17204 ED->setIntegerTypeSourceInfo(TI);
17205 else
17206 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17207 QualType EnumTy = ED->getIntegerType();
17208 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17209 ? Context.getPromotedIntegerType(EnumTy)
17210 : EnumTy);
17212 } else { // struct/union
17213 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17214 nullptr);
17217 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17218 // Add alignment attributes if necessary; these attributes are checked
17219 // when the ASTContext lays out the structure.
17221 // It is important for implementing the correct semantics that this
17222 // happen here (in ActOnTag). The #pragma pack stack is
17223 // maintained as a result of parser callbacks which can occur at
17224 // many points during the parsing of a struct declaration (because
17225 // the #pragma tokens are effectively skipped over during the
17226 // parsing of the struct).
17227 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17228 AddAlignmentAttributesForRecord(RD);
17229 AddMsStructLayoutForRecord(RD);
17232 New->setLexicalDeclContext(CurContext);
17233 return New;
17236 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17237 if (Name && SS.isNotEmpty()) {
17238 // We have a nested-name tag ('struct foo::bar').
17240 // Check for invalid 'foo::'.
17241 if (SS.isInvalid()) {
17242 Name = nullptr;
17243 goto CreateNewDecl;
17246 // If this is a friend or a reference to a class in a dependent
17247 // context, don't try to make a decl for it.
17248 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17249 DC = computeDeclContext(SS, false);
17250 if (!DC) {
17251 IsDependent = true;
17252 return true;
17254 } else {
17255 DC = computeDeclContext(SS, true);
17256 if (!DC) {
17257 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17258 << SS.getRange();
17259 return true;
17263 if (RequireCompleteDeclContext(SS, DC))
17264 return true;
17266 SearchDC = DC;
17267 // Look-up name inside 'foo::'.
17268 LookupQualifiedName(Previous, DC);
17270 if (Previous.isAmbiguous())
17271 return true;
17273 if (Previous.empty()) {
17274 // Name lookup did not find anything. However, if the
17275 // nested-name-specifier refers to the current instantiation,
17276 // and that current instantiation has any dependent base
17277 // classes, we might find something at instantiation time: treat
17278 // this as a dependent elaborated-type-specifier.
17279 // But this only makes any sense for reference-like lookups.
17280 if (Previous.wasNotFoundInCurrentInstantiation() &&
17281 (TUK == TUK_Reference || TUK == TUK_Friend)) {
17282 IsDependent = true;
17283 return true;
17286 // A tag 'foo::bar' must already exist.
17287 Diag(NameLoc, diag::err_not_tag_in_scope)
17288 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17289 Name = nullptr;
17290 Invalid = true;
17291 goto CreateNewDecl;
17293 } else if (Name) {
17294 // C++14 [class.mem]p14:
17295 // If T is the name of a class, then each of the following shall have a
17296 // name different from T:
17297 // -- every member of class T that is itself a type
17298 if (TUK != TUK_Reference && TUK != TUK_Friend &&
17299 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17300 return true;
17302 // If this is a named struct, check to see if there was a previous forward
17303 // declaration or definition.
17304 // FIXME: We're looking into outer scopes here, even when we
17305 // shouldn't be. Doing so can result in ambiguities that we
17306 // shouldn't be diagnosing.
17307 LookupName(Previous, S);
17309 // When declaring or defining a tag, ignore ambiguities introduced
17310 // by types using'ed into this scope.
17311 if (Previous.isAmbiguous() &&
17312 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
17313 LookupResult::Filter F = Previous.makeFilter();
17314 while (F.hasNext()) {
17315 NamedDecl *ND = F.next();
17316 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17317 SearchDC->getRedeclContext()))
17318 F.erase();
17320 F.done();
17323 // C++11 [namespace.memdef]p3:
17324 // If the name in a friend declaration is neither qualified nor
17325 // a template-id and the declaration is a function or an
17326 // elaborated-type-specifier, the lookup to determine whether
17327 // the entity has been previously declared shall not consider
17328 // any scopes outside the innermost enclosing namespace.
17330 // MSVC doesn't implement the above rule for types, so a friend tag
17331 // declaration may be a redeclaration of a type declared in an enclosing
17332 // scope. They do implement this rule for friend functions.
17334 // Does it matter that this should be by scope instead of by
17335 // semantic context?
17336 if (!Previous.empty() && TUK == TUK_Friend) {
17337 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17338 LookupResult::Filter F = Previous.makeFilter();
17339 bool FriendSawTagOutsideEnclosingNamespace = false;
17340 while (F.hasNext()) {
17341 NamedDecl *ND = F.next();
17342 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
17343 if (DC->isFileContext() &&
17344 !EnclosingNS->Encloses(ND->getDeclContext())) {
17345 if (getLangOpts().MSVCCompat)
17346 FriendSawTagOutsideEnclosingNamespace = true;
17347 else
17348 F.erase();
17351 F.done();
17353 // Diagnose this MSVC extension in the easy case where lookup would have
17354 // unambiguously found something outside the enclosing namespace.
17355 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17356 NamedDecl *ND = Previous.getFoundDecl();
17357 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17358 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17362 // Note: there used to be some attempt at recovery here.
17363 if (Previous.isAmbiguous())
17364 return true;
17366 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
17367 // FIXME: This makes sure that we ignore the contexts associated
17368 // with C structs, unions, and enums when looking for a matching
17369 // tag declaration or definition. See the similar lookup tweak
17370 // in Sema::LookupName; is there a better way to deal with this?
17371 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17372 SearchDC = SearchDC->getParent();
17373 } else if (getLangOpts().CPlusPlus) {
17374 // Inside ObjCContainer want to keep it as a lexical decl context but go
17375 // past it (most often to TranslationUnit) to find the semantic decl
17376 // context.
17377 while (isa<ObjCContainerDecl>(SearchDC))
17378 SearchDC = SearchDC->getParent();
17380 } else if (getLangOpts().CPlusPlus) {
17381 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17382 // TagDecl the same way as we skip it for named TagDecl.
17383 while (isa<ObjCContainerDecl>(SearchDC))
17384 SearchDC = SearchDC->getParent();
17387 if (Previous.isSingleResult() &&
17388 Previous.getFoundDecl()->isTemplateParameter()) {
17389 // Maybe we will complain about the shadowed template parameter.
17390 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17391 // Just pretend that we didn't see the previous declaration.
17392 Previous.clear();
17395 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17396 DC->Equals(getStdNamespace())) {
17397 if (Name->isStr("bad_alloc")) {
17398 // This is a declaration of or a reference to "std::bad_alloc".
17399 isStdBadAlloc = true;
17401 // If std::bad_alloc has been implicitly declared (but made invisible to
17402 // name lookup), fill in this implicit declaration as the previous
17403 // declaration, so that the declarations get chained appropriately.
17404 if (Previous.empty() && StdBadAlloc)
17405 Previous.addDecl(getStdBadAlloc());
17406 } else if (Name->isStr("align_val_t")) {
17407 isStdAlignValT = true;
17408 if (Previous.empty() && StdAlignValT)
17409 Previous.addDecl(getStdAlignValT());
17413 // If we didn't find a previous declaration, and this is a reference
17414 // (or friend reference), move to the correct scope. In C++, we
17415 // also need to do a redeclaration lookup there, just in case
17416 // there's a shadow friend decl.
17417 if (Name && Previous.empty() &&
17418 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
17419 if (Invalid) goto CreateNewDecl;
17420 assert(SS.isEmpty());
17422 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
17423 // C++ [basic.scope.pdecl]p5:
17424 // -- for an elaborated-type-specifier of the form
17426 // class-key identifier
17428 // if the elaborated-type-specifier is used in the
17429 // decl-specifier-seq or parameter-declaration-clause of a
17430 // function defined in namespace scope, the identifier is
17431 // declared as a class-name in the namespace that contains
17432 // the declaration; otherwise, except as a friend
17433 // declaration, the identifier is declared in the smallest
17434 // non-class, non-function-prototype scope that contains the
17435 // declaration.
17437 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17438 // C structs and unions.
17440 // It is an error in C++ to declare (rather than define) an enum
17441 // type, including via an elaborated type specifier. We'll
17442 // diagnose that later; for now, declare the enum in the same
17443 // scope as we would have picked for any other tag type.
17445 // GNU C also supports this behavior as part of its incomplete
17446 // enum types extension, while GNU C++ does not.
17448 // Find the context where we'll be declaring the tag.
17449 // FIXME: We would like to maintain the current DeclContext as the
17450 // lexical context,
17451 SearchDC = getTagInjectionContext(SearchDC);
17453 // Find the scope where we'll be declaring the tag.
17454 S = getTagInjectionScope(S, getLangOpts());
17455 } else {
17456 assert(TUK == TUK_Friend);
17457 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17459 // C++ [namespace.memdef]p3:
17460 // If a friend declaration in a non-local class first declares a
17461 // class or function, the friend class or function is a member of
17462 // the innermost enclosing namespace.
17463 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17464 : SearchDC->getEnclosingNamespaceContext();
17467 // In C++, we need to do a redeclaration lookup to properly
17468 // diagnose some problems.
17469 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17470 // hidden declaration so that we don't get ambiguity errors when using a
17471 // type declared by an elaborated-type-specifier. In C that is not correct
17472 // and we should instead merge compatible types found by lookup.
17473 if (getLangOpts().CPlusPlus) {
17474 // FIXME: This can perform qualified lookups into function contexts,
17475 // which are meaningless.
17476 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17477 LookupQualifiedName(Previous, SearchDC);
17478 } else {
17479 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17480 LookupName(Previous, S);
17484 // If we have a known previous declaration to use, then use it.
17485 if (Previous.empty() && SkipBody && SkipBody->Previous)
17486 Previous.addDecl(SkipBody->Previous);
17488 if (!Previous.empty()) {
17489 NamedDecl *PrevDecl = Previous.getFoundDecl();
17490 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17492 // It's okay to have a tag decl in the same scope as a typedef
17493 // which hides a tag decl in the same scope. Finding this
17494 // with a redeclaration lookup can only actually happen in C++.
17496 // This is also okay for elaborated-type-specifiers, which is
17497 // technically forbidden by the current standard but which is
17498 // okay according to the likely resolution of an open issue;
17499 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17500 if (getLangOpts().CPlusPlus) {
17501 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17502 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17503 TagDecl *Tag = TT->getDecl();
17504 if (Tag->getDeclName() == Name &&
17505 Tag->getDeclContext()->getRedeclContext()
17506 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17507 PrevDecl = Tag;
17508 Previous.clear();
17509 Previous.addDecl(Tag);
17510 Previous.resolveKind();
17516 // If this is a redeclaration of a using shadow declaration, it must
17517 // declare a tag in the same context. In MSVC mode, we allow a
17518 // redefinition if either context is within the other.
17519 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17520 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17521 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
17522 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17523 !(OldTag && isAcceptableTagRedeclContext(
17524 *this, OldTag->getDeclContext(), SearchDC))) {
17525 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17526 Diag(Shadow->getTargetDecl()->getLocation(),
17527 diag::note_using_decl_target);
17528 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17529 << 0;
17530 // Recover by ignoring the old declaration.
17531 Previous.clear();
17532 goto CreateNewDecl;
17536 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17537 // If this is a use of a previous tag, or if the tag is already declared
17538 // in the same scope (so that the definition/declaration completes or
17539 // rementions the tag), reuse the decl.
17540 if (TUK == TUK_Reference || TUK == TUK_Friend ||
17541 isDeclInScope(DirectPrevDecl, SearchDC, S,
17542 SS.isNotEmpty() || isMemberSpecialization)) {
17543 // Make sure that this wasn't declared as an enum and now used as a
17544 // struct or something similar.
17545 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17546 TUK == TUK_Definition, KWLoc,
17547 Name)) {
17548 bool SafeToContinue =
17549 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17550 Kind != TagTypeKind::Enum);
17551 if (SafeToContinue)
17552 Diag(KWLoc, diag::err_use_with_wrong_tag)
17553 << Name
17554 << FixItHint::CreateReplacement(SourceRange(KWLoc),
17555 PrevTagDecl->getKindName());
17556 else
17557 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17558 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17560 if (SafeToContinue)
17561 Kind = PrevTagDecl->getTagKind();
17562 else {
17563 // Recover by making this an anonymous redefinition.
17564 Name = nullptr;
17565 Previous.clear();
17566 Invalid = true;
17570 if (Kind == TagTypeKind::Enum &&
17571 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17572 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17573 if (TUK == TUK_Reference || TUK == TUK_Friend)
17574 return PrevTagDecl;
17576 QualType EnumUnderlyingTy;
17577 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17578 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17579 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17580 EnumUnderlyingTy = QualType(T, 0);
17582 // All conflicts with previous declarations are recovered by
17583 // returning the previous declaration, unless this is a definition,
17584 // in which case we want the caller to bail out.
17585 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17586 ScopedEnum, EnumUnderlyingTy,
17587 IsFixed, PrevEnum))
17588 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
17591 // C++11 [class.mem]p1:
17592 // A member shall not be declared twice in the member-specification,
17593 // except that a nested class or member class template can be declared
17594 // and then later defined.
17595 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
17596 S->isDeclScope(PrevDecl)) {
17597 Diag(NameLoc, diag::ext_member_redeclared);
17598 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17601 if (!Invalid) {
17602 // If this is a use, just return the declaration we found, unless
17603 // we have attributes.
17604 if (TUK == TUK_Reference || TUK == TUK_Friend) {
17605 if (!Attrs.empty()) {
17606 // FIXME: Diagnose these attributes. For now, we create a new
17607 // declaration to hold them.
17608 } else if (TUK == TUK_Reference &&
17609 (PrevTagDecl->getFriendObjectKind() ==
17610 Decl::FOK_Undeclared ||
17611 PrevDecl->getOwningModule() != getCurrentModule()) &&
17612 SS.isEmpty()) {
17613 // This declaration is a reference to an existing entity, but
17614 // has different visibility from that entity: it either makes
17615 // a friend visible or it makes a type visible in a new module.
17616 // In either case, create a new declaration. We only do this if
17617 // the declaration would have meant the same thing if no prior
17618 // declaration were found, that is, if it was found in the same
17619 // scope where we would have injected a declaration.
17620 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17621 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17622 return PrevTagDecl;
17623 // This is in the injected scope, create a new declaration in
17624 // that scope.
17625 S = getTagInjectionScope(S, getLangOpts());
17626 } else {
17627 return PrevTagDecl;
17631 // Diagnose attempts to redefine a tag.
17632 if (TUK == TUK_Definition) {
17633 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17634 // If we're defining a specialization and the previous definition
17635 // is from an implicit instantiation, don't emit an error
17636 // here; we'll catch this in the general case below.
17637 bool IsExplicitSpecializationAfterInstantiation = false;
17638 if (isMemberSpecialization) {
17639 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17640 IsExplicitSpecializationAfterInstantiation =
17641 RD->getTemplateSpecializationKind() !=
17642 TSK_ExplicitSpecialization;
17643 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17644 IsExplicitSpecializationAfterInstantiation =
17645 ED->getTemplateSpecializationKind() !=
17646 TSK_ExplicitSpecialization;
17649 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17650 // not keep more that one definition around (merge them). However,
17651 // ensure the decl passes the structural compatibility check in
17652 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17653 NamedDecl *Hidden = nullptr;
17654 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17655 // There is a definition of this tag, but it is not visible. We
17656 // explicitly make use of C++'s one definition rule here, and
17657 // assume that this definition is identical to the hidden one
17658 // we already have. Make the existing definition visible and
17659 // use it in place of this one.
17660 if (!getLangOpts().CPlusPlus) {
17661 // Postpone making the old definition visible until after we
17662 // complete parsing the new one and do the structural
17663 // comparison.
17664 SkipBody->CheckSameAsPrevious = true;
17665 SkipBody->New = createTagFromNewDecl();
17666 SkipBody->Previous = Def;
17667 return Def;
17668 } else {
17669 SkipBody->ShouldSkip = true;
17670 SkipBody->Previous = Def;
17671 makeMergedDefinitionVisible(Hidden);
17672 // Carry on and handle it like a normal definition. We'll
17673 // skip starting the definitiion later.
17675 } else if (!IsExplicitSpecializationAfterInstantiation) {
17676 // A redeclaration in function prototype scope in C isn't
17677 // visible elsewhere, so merely issue a warning.
17678 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17679 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17680 else
17681 Diag(NameLoc, diag::err_redefinition) << Name;
17682 notePreviousDefinition(Def,
17683 NameLoc.isValid() ? NameLoc : KWLoc);
17684 // If this is a redefinition, recover by making this
17685 // struct be anonymous, which will make any later
17686 // references get the previous definition.
17687 Name = nullptr;
17688 Previous.clear();
17689 Invalid = true;
17691 } else {
17692 // If the type is currently being defined, complain
17693 // about a nested redefinition.
17694 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17695 if (TD->isBeingDefined()) {
17696 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17697 Diag(PrevTagDecl->getLocation(),
17698 diag::note_previous_definition);
17699 Name = nullptr;
17700 Previous.clear();
17701 Invalid = true;
17705 // Okay, this is definition of a previously declared or referenced
17706 // tag. We're going to create a new Decl for it.
17709 // Okay, we're going to make a redeclaration. If this is some kind
17710 // of reference, make sure we build the redeclaration in the same DC
17711 // as the original, and ignore the current access specifier.
17712 if (TUK == TUK_Friend || TUK == TUK_Reference) {
17713 SearchDC = PrevTagDecl->getDeclContext();
17714 AS = AS_none;
17717 // If we get here we have (another) forward declaration or we
17718 // have a definition. Just create a new decl.
17720 } else {
17721 // If we get here, this is a definition of a new tag type in a nested
17722 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17723 // new decl/type. We set PrevDecl to NULL so that the entities
17724 // have distinct types.
17725 Previous.clear();
17727 // If we get here, we're going to create a new Decl. If PrevDecl
17728 // is non-NULL, it's a definition of the tag declared by
17729 // PrevDecl. If it's NULL, we have a new definition.
17731 // Otherwise, PrevDecl is not a tag, but was found with tag
17732 // lookup. This is only actually possible in C++, where a few
17733 // things like templates still live in the tag namespace.
17734 } else {
17735 // Use a better diagnostic if an elaborated-type-specifier
17736 // found the wrong kind of type on the first
17737 // (non-redeclaration) lookup.
17738 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
17739 !Previous.isForRedeclaration()) {
17740 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17741 Diag(NameLoc, diag::err_tag_reference_non_tag)
17742 << PrevDecl << NTK << llvm::to_underlying(Kind);
17743 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17744 Invalid = true;
17746 // Otherwise, only diagnose if the declaration is in scope.
17747 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17748 SS.isNotEmpty() || isMemberSpecialization)) {
17749 // do nothing
17751 // Diagnose implicit declarations introduced by elaborated types.
17752 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
17753 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17754 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17755 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17756 Invalid = true;
17758 // Otherwise it's a declaration. Call out a particularly common
17759 // case here.
17760 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17761 unsigned Kind = 0;
17762 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17763 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17764 << Name << Kind << TND->getUnderlyingType();
17765 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17766 Invalid = true;
17768 // Otherwise, diagnose.
17769 } else {
17770 // The tag name clashes with something else in the target scope,
17771 // issue an error and recover by making this tag be anonymous.
17772 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17773 notePreviousDefinition(PrevDecl, NameLoc);
17774 Name = nullptr;
17775 Invalid = true;
17778 // The existing declaration isn't relevant to us; we're in a
17779 // new scope, so clear out the previous declaration.
17780 Previous.clear();
17784 CreateNewDecl:
17786 TagDecl *PrevDecl = nullptr;
17787 if (Previous.isSingleResult())
17788 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17790 // If there is an identifier, use the location of the identifier as the
17791 // location of the decl, otherwise use the location of the struct/union
17792 // keyword.
17793 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17795 // Otherwise, create a new declaration. If there is a previous
17796 // declaration of the same entity, the two will be linked via
17797 // PrevDecl.
17798 TagDecl *New;
17800 if (Kind == TagTypeKind::Enum) {
17801 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17802 // enum X { A, B, C } D; D should chain to X.
17803 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17804 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17805 ScopedEnumUsesClassTag, IsFixed);
17807 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17808 StdAlignValT = cast<EnumDecl>(New);
17810 // If this is an undefined enum, warn.
17811 if (TUK != TUK_Definition && !Invalid) {
17812 TagDecl *Def;
17813 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17814 // C++0x: 7.2p2: opaque-enum-declaration.
17815 // Conflicts are diagnosed above. Do nothing.
17817 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17818 Diag(Loc, diag::ext_forward_ref_enum_def)
17819 << New;
17820 Diag(Def->getLocation(), diag::note_previous_definition);
17821 } else {
17822 unsigned DiagID = diag::ext_forward_ref_enum;
17823 if (getLangOpts().MSVCCompat)
17824 DiagID = diag::ext_ms_forward_ref_enum;
17825 else if (getLangOpts().CPlusPlus)
17826 DiagID = diag::err_forward_ref_enum;
17827 Diag(Loc, DiagID);
17831 if (EnumUnderlying) {
17832 EnumDecl *ED = cast<EnumDecl>(New);
17833 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17834 ED->setIntegerTypeSourceInfo(TI);
17835 else
17836 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17837 QualType EnumTy = ED->getIntegerType();
17838 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
17839 ? Context.getPromotedIntegerType(EnumTy)
17840 : EnumTy);
17841 assert(ED->isComplete() && "enum with type should be complete");
17843 } else {
17844 // struct/union/class
17846 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17847 // struct X { int A; } D; D should chain to X.
17848 if (getLangOpts().CPlusPlus) {
17849 // FIXME: Look for a way to use RecordDecl for simple structs.
17850 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17851 cast_or_null<CXXRecordDecl>(PrevDecl));
17853 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17854 StdBadAlloc = cast<CXXRecordDecl>(New);
17855 } else
17856 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17857 cast_or_null<RecordDecl>(PrevDecl));
17860 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
17861 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17862 << (OOK == OOK_Macro) << New->getSourceRange();
17864 // C++11 [dcl.type]p3:
17865 // A type-specifier-seq shall not define a class or enumeration [...].
17866 if (!Invalid && getLangOpts().CPlusPlus &&
17867 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
17868 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17869 << Context.getTagDeclType(New);
17870 Invalid = true;
17873 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
17874 DC->getDeclKind() == Decl::Enum) {
17875 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17876 << Context.getTagDeclType(New);
17877 Invalid = true;
17880 // Maybe add qualifier info.
17881 if (SS.isNotEmpty()) {
17882 if (SS.isSet()) {
17883 // If this is either a declaration or a definition, check the
17884 // nested-name-specifier against the current context.
17885 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
17886 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17887 isMemberSpecialization))
17888 Invalid = true;
17890 New->setQualifierInfo(SS.getWithLocInContext(Context));
17891 if (TemplateParameterLists.size() > 0) {
17892 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17895 else
17896 Invalid = true;
17899 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17900 // Add alignment attributes if necessary; these attributes are checked when
17901 // the ASTContext lays out the structure.
17903 // It is important for implementing the correct semantics that this
17904 // happen here (in ActOnTag). The #pragma pack stack is
17905 // maintained as a result of parser callbacks which can occur at
17906 // many points during the parsing of a struct declaration (because
17907 // the #pragma tokens are effectively skipped over during the
17908 // parsing of the struct).
17909 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17910 AddAlignmentAttributesForRecord(RD);
17911 AddMsStructLayoutForRecord(RD);
17915 if (ModulePrivateLoc.isValid()) {
17916 if (isMemberSpecialization)
17917 Diag(New->getLocation(), diag::err_module_private_specialization)
17918 << 2
17919 << FixItHint::CreateRemoval(ModulePrivateLoc);
17920 // __module_private__ does not apply to local classes. However, we only
17921 // diagnose this as an error when the declaration specifiers are
17922 // freestanding. Here, we just ignore the __module_private__.
17923 else if (!SearchDC->isFunctionOrMethod())
17924 New->setModulePrivate();
17927 // If this is a specialization of a member class (of a class template),
17928 // check the specialization.
17929 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17930 Invalid = true;
17932 // If we're declaring or defining a tag in function prototype scope in C,
17933 // note that this type can only be used within the function and add it to
17934 // the list of decls to inject into the function definition scope.
17935 if ((Name || Kind == TagTypeKind::Enum) &&
17936 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17937 if (getLangOpts().CPlusPlus) {
17938 // C++ [dcl.fct]p6:
17939 // Types shall not be defined in return or parameter types.
17940 if (TUK == TUK_Definition && !IsTypeSpecifier) {
17941 Diag(Loc, diag::err_type_defined_in_param_type)
17942 << Name;
17943 Invalid = true;
17945 } else if (!PrevDecl) {
17946 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17950 if (Invalid)
17951 New->setInvalidDecl();
17953 // Set the lexical context. If the tag has a C++ scope specifier, the
17954 // lexical context will be different from the semantic context.
17955 New->setLexicalDeclContext(CurContext);
17957 // Mark this as a friend decl if applicable.
17958 // In Microsoft mode, a friend declaration also acts as a forward
17959 // declaration so we always pass true to setObjectOfFriendDecl to make
17960 // the tag name visible.
17961 if (TUK == TUK_Friend)
17962 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17964 // Set the access specifier.
17965 if (!Invalid && SearchDC->isRecord())
17966 SetMemberAccessSpecifier(New, PrevDecl, AS);
17968 if (PrevDecl)
17969 CheckRedeclarationInModule(New, PrevDecl);
17971 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
17972 New->startDefinition();
17974 ProcessDeclAttributeList(S, New, Attrs);
17975 AddPragmaAttributes(S, New);
17977 // If this has an identifier, add it to the scope stack.
17978 if (TUK == TUK_Friend) {
17979 // We might be replacing an existing declaration in the lookup tables;
17980 // if so, borrow its access specifier.
17981 if (PrevDecl)
17982 New->setAccess(PrevDecl->getAccess());
17984 DeclContext *DC = New->getDeclContext()->getRedeclContext();
17985 DC->makeDeclVisibleInContext(New);
17986 if (Name) // can be null along some error paths
17987 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17988 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17989 } else if (Name) {
17990 S = getNonFieldDeclScope(S);
17991 PushOnScopeChains(New, S, true);
17992 } else {
17993 CurContext->addDecl(New);
17996 // If this is the C FILE type, notify the AST context.
17997 if (IdentifierInfo *II = New->getIdentifier())
17998 if (!New->isInvalidDecl() &&
17999 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18000 II->isStr("FILE"))
18001 Context.setFILEDecl(New);
18003 if (PrevDecl)
18004 mergeDeclAttributes(New, PrevDecl);
18006 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
18007 inferGslOwnerPointerAttribute(CXXRD);
18009 // If there's a #pragma GCC visibility in scope, set the visibility of this
18010 // record.
18011 AddPushedVisibilityAttribute(New);
18013 if (isMemberSpecialization && !New->isInvalidDecl())
18014 CompleteMemberSpecialization(New, Previous);
18016 OwnedDecl = true;
18017 // In C++, don't return an invalid declaration. We can't recover well from
18018 // the cases where we make the type anonymous.
18019 if (Invalid && getLangOpts().CPlusPlus) {
18020 if (New->isBeingDefined())
18021 if (auto RD = dyn_cast<RecordDecl>(New))
18022 RD->completeDefinition();
18023 return true;
18024 } else if (SkipBody && SkipBody->ShouldSkip) {
18025 return SkipBody->Previous;
18026 } else {
18027 return New;
18031 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
18032 AdjustDeclIfTemplate(TagD);
18033 TagDecl *Tag = cast<TagDecl>(TagD);
18035 // Enter the tag context.
18036 PushDeclContext(S, Tag);
18038 ActOnDocumentableDecl(TagD);
18040 // If there's a #pragma GCC visibility in scope, set the visibility of this
18041 // record.
18042 AddPushedVisibilityAttribute(Tag);
18045 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
18046 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18047 return false;
18049 // Make the previous decl visible.
18050 makeMergedDefinitionVisible(SkipBody.Previous);
18051 return true;
18054 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
18055 assert(IDecl->getLexicalParent() == CurContext &&
18056 "The next DeclContext should be lexically contained in the current one.");
18057 CurContext = IDecl;
18060 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
18061 SourceLocation FinalLoc,
18062 bool IsFinalSpelledSealed,
18063 bool IsAbstract,
18064 SourceLocation LBraceLoc) {
18065 AdjustDeclIfTemplate(TagD);
18066 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18068 FieldCollector->StartClass();
18070 if (!Record->getIdentifier())
18071 return;
18073 if (IsAbstract)
18074 Record->markAbstract();
18076 if (FinalLoc.isValid()) {
18077 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18078 IsFinalSpelledSealed
18079 ? FinalAttr::Keyword_sealed
18080 : FinalAttr::Keyword_final));
18082 // C++ [class]p2:
18083 // [...] The class-name is also inserted into the scope of the
18084 // class itself; this is known as the injected-class-name. For
18085 // purposes of access checking, the injected-class-name is treated
18086 // as if it were a public member name.
18087 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18088 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18089 Record->getLocation(), Record->getIdentifier(),
18090 /*PrevDecl=*/nullptr,
18091 /*DelayTypeCreation=*/true);
18092 Context.getTypeDeclType(InjectedClassName, Record);
18093 InjectedClassName->setImplicit();
18094 InjectedClassName->setAccess(AS_public);
18095 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18096 InjectedClassName->setDescribedClassTemplate(Template);
18097 PushOnScopeChains(InjectedClassName, S);
18098 assert(InjectedClassName->isInjectedClassName() &&
18099 "Broken injected-class-name");
18102 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
18103 SourceRange BraceRange) {
18104 AdjustDeclIfTemplate(TagD);
18105 TagDecl *Tag = cast<TagDecl>(TagD);
18106 Tag->setBraceRange(BraceRange);
18108 // Make sure we "complete" the definition even it is invalid.
18109 if (Tag->isBeingDefined()) {
18110 assert(Tag->isInvalidDecl() && "We should already have completed it");
18111 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18112 RD->completeDefinition();
18115 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18116 FieldCollector->FinishClass();
18117 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18118 auto *Def = RD->getDefinition();
18119 assert(Def && "The record is expected to have a completed definition");
18120 unsigned NumInitMethods = 0;
18121 for (auto *Method : Def->methods()) {
18122 if (!Method->getIdentifier())
18123 continue;
18124 if (Method->getName() == "__init")
18125 NumInitMethods++;
18127 if (NumInitMethods > 1 || !Def->hasInitMethod())
18128 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18132 // Exit this scope of this tag's definition.
18133 PopDeclContext();
18135 if (getCurLexicalContext()->isObjCContainer() &&
18136 Tag->getDeclContext()->isFileContext())
18137 Tag->setTopLevelDeclInObjCContainer();
18139 // Notify the consumer that we've defined a tag.
18140 if (!Tag->isInvalidDecl())
18141 Consumer.HandleTagDeclDefinition(Tag);
18143 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18144 // from XLs and instead matches the XL #pragma pack(1) behavior.
18145 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18146 AlignPackStack.hasValue()) {
18147 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18148 // Only diagnose #pragma align(packed).
18149 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18150 return;
18151 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18152 if (!RD)
18153 return;
18154 // Only warn if there is at least 1 bitfield member.
18155 if (llvm::any_of(RD->fields(),
18156 [](const FieldDecl *FD) { return FD->isBitField(); }))
18157 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18161 void Sema::ActOnObjCContainerFinishDefinition() {
18162 // Exit this scope of this interface definition.
18163 PopDeclContext();
18166 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
18167 assert(ObjCCtx == CurContext && "Mismatch of container contexts");
18168 OriginalLexicalContext = ObjCCtx;
18169 ActOnObjCContainerFinishDefinition();
18172 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
18173 ActOnObjCContainerStartDefinition(ObjCCtx);
18174 OriginalLexicalContext = nullptr;
18177 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
18178 AdjustDeclIfTemplate(TagD);
18179 TagDecl *Tag = cast<TagDecl>(TagD);
18180 Tag->setInvalidDecl();
18182 // Make sure we "complete" the definition even it is invalid.
18183 if (Tag->isBeingDefined()) {
18184 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18185 RD->completeDefinition();
18188 // We're undoing ActOnTagStartDefinition here, not
18189 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18190 // the FieldCollector.
18192 PopDeclContext();
18195 // Note that FieldName may be null for anonymous bitfields.
18196 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
18197 IdentifierInfo *FieldName, QualType FieldTy,
18198 bool IsMsStruct, Expr *BitWidth) {
18199 assert(BitWidth);
18200 if (BitWidth->containsErrors())
18201 return ExprError();
18203 // C99 6.7.2.1p4 - verify the field type.
18204 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18205 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18206 // Handle incomplete and sizeless types with a specific error.
18207 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18208 diag::err_field_incomplete_or_sizeless))
18209 return ExprError();
18210 if (FieldName)
18211 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18212 << FieldName << FieldTy << BitWidth->getSourceRange();
18213 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18214 << FieldTy << BitWidth->getSourceRange();
18215 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18216 UPPC_BitFieldWidth))
18217 return ExprError();
18219 // If the bit-width is type- or value-dependent, don't try to check
18220 // it now.
18221 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18222 return BitWidth;
18224 llvm::APSInt Value;
18225 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
18226 if (ICE.isInvalid())
18227 return ICE;
18228 BitWidth = ICE.get();
18230 // Zero-width bitfield is ok for anonymous field.
18231 if (Value == 0 && FieldName)
18232 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18233 << FieldName << BitWidth->getSourceRange();
18235 if (Value.isSigned() && Value.isNegative()) {
18236 if (FieldName)
18237 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18238 << FieldName << toString(Value, 10);
18239 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18240 << toString(Value, 10);
18243 // The size of the bit-field must not exceed our maximum permitted object
18244 // size.
18245 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18246 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18247 << !FieldName << FieldName << toString(Value, 10);
18250 if (!FieldTy->isDependentType()) {
18251 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18252 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18253 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18255 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18256 // ABI.
18257 bool CStdConstraintViolation =
18258 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18259 bool MSBitfieldViolation =
18260 Value.ugt(TypeStorageSize) &&
18261 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18262 if (CStdConstraintViolation || MSBitfieldViolation) {
18263 unsigned DiagWidth =
18264 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18265 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18266 << (bool)FieldName << FieldName << toString(Value, 10)
18267 << !CStdConstraintViolation << DiagWidth;
18270 // Warn on types where the user might conceivably expect to get all
18271 // specified bits as value bits: that's all integral types other than
18272 // 'bool'.
18273 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18274 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18275 << FieldName << toString(Value, 10)
18276 << (unsigned)TypeWidth;
18280 return BitWidth;
18283 /// ActOnField - Each field of a C struct/union is passed into this in order
18284 /// to create a FieldDecl object for it.
18285 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
18286 Declarator &D, Expr *BitfieldWidth) {
18287 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18288 D, BitfieldWidth,
18289 /*InitStyle=*/ICIS_NoInit, AS_public);
18290 return Res;
18293 /// HandleField - Analyze a field of a C struct or a C++ data member.
18295 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
18296 SourceLocation DeclStart,
18297 Declarator &D, Expr *BitWidth,
18298 InClassInitStyle InitStyle,
18299 AccessSpecifier AS) {
18300 if (D.isDecompositionDeclarator()) {
18301 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18302 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18303 << Decomp.getSourceRange();
18304 return nullptr;
18307 IdentifierInfo *II = D.getIdentifier();
18308 SourceLocation Loc = DeclStart;
18309 if (II) Loc = D.getIdentifierLoc();
18311 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18312 QualType T = TInfo->getType();
18313 if (getLangOpts().CPlusPlus) {
18314 CheckExtraCXXDefaultArguments(D);
18316 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18317 UPPC_DataMemberType)) {
18318 D.setInvalidType();
18319 T = Context.IntTy;
18320 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18324 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18326 if (D.getDeclSpec().isInlineSpecified())
18327 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18328 << getLangOpts().CPlusPlus17;
18329 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18330 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18331 diag::err_invalid_thread)
18332 << DeclSpec::getSpecifierName(TSCS);
18334 // Check to see if this name was declared as a member previously
18335 NamedDecl *PrevDecl = nullptr;
18336 LookupResult Previous(*this, II, Loc, LookupMemberName,
18337 ForVisibleRedeclaration);
18338 LookupName(Previous, S);
18339 switch (Previous.getResultKind()) {
18340 case LookupResult::Found:
18341 case LookupResult::FoundUnresolvedValue:
18342 PrevDecl = Previous.getAsSingle<NamedDecl>();
18343 break;
18345 case LookupResult::FoundOverloaded:
18346 PrevDecl = Previous.getRepresentativeDecl();
18347 break;
18349 case LookupResult::NotFound:
18350 case LookupResult::NotFoundInCurrentInstantiation:
18351 case LookupResult::Ambiguous:
18352 break;
18354 Previous.suppressDiagnostics();
18356 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18357 // Maybe we will complain about the shadowed template parameter.
18358 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18359 // Just pretend that we didn't see the previous declaration.
18360 PrevDecl = nullptr;
18363 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18364 PrevDecl = nullptr;
18366 bool Mutable
18367 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18368 SourceLocation TSSL = D.getBeginLoc();
18369 FieldDecl *NewFD
18370 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18371 TSSL, AS, PrevDecl, &D);
18373 if (NewFD->isInvalidDecl())
18374 Record->setInvalidDecl();
18376 if (D.getDeclSpec().isModulePrivateSpecified())
18377 NewFD->setModulePrivate();
18379 if (NewFD->isInvalidDecl() && PrevDecl) {
18380 // Don't introduce NewFD into scope; there's already something
18381 // with the same name in the same scope.
18382 } else if (II) {
18383 PushOnScopeChains(NewFD, S);
18384 } else
18385 Record->addDecl(NewFD);
18387 return NewFD;
18390 /// Build a new FieldDecl and check its well-formedness.
18392 /// This routine builds a new FieldDecl given the fields name, type,
18393 /// record, etc. \p PrevDecl should refer to any previous declaration
18394 /// with the same name and in the same scope as the field to be
18395 /// created.
18397 /// \returns a new FieldDecl.
18399 /// \todo The Declarator argument is a hack. It will be removed once
18400 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
18401 TypeSourceInfo *TInfo,
18402 RecordDecl *Record, SourceLocation Loc,
18403 bool Mutable, Expr *BitWidth,
18404 InClassInitStyle InitStyle,
18405 SourceLocation TSSL,
18406 AccessSpecifier AS, NamedDecl *PrevDecl,
18407 Declarator *D) {
18408 IdentifierInfo *II = Name.getAsIdentifierInfo();
18409 bool InvalidDecl = false;
18410 if (D) InvalidDecl = D->isInvalidType();
18412 // If we receive a broken type, recover by assuming 'int' and
18413 // marking this declaration as invalid.
18414 if (T.isNull() || T->containsErrors()) {
18415 InvalidDecl = true;
18416 T = Context.IntTy;
18419 QualType EltTy = Context.getBaseElementType(T);
18420 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18421 if (RequireCompleteSizedType(Loc, EltTy,
18422 diag::err_field_incomplete_or_sizeless)) {
18423 // Fields of incomplete type force their record to be invalid.
18424 Record->setInvalidDecl();
18425 InvalidDecl = true;
18426 } else {
18427 NamedDecl *Def;
18428 EltTy->isIncompleteType(&Def);
18429 if (Def && Def->isInvalidDecl()) {
18430 Record->setInvalidDecl();
18431 InvalidDecl = true;
18436 // TR 18037 does not allow fields to be declared with address space
18437 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18438 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
18439 Diag(Loc, diag::err_field_with_address_space);
18440 Record->setInvalidDecl();
18441 InvalidDecl = true;
18444 if (LangOpts.OpenCL) {
18445 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18446 // used as structure or union field: image, sampler, event or block types.
18447 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18448 T->isBlockPointerType()) {
18449 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18450 Record->setInvalidDecl();
18451 InvalidDecl = true;
18453 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18454 // is enabled.
18455 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18456 "__cl_clang_bitfields", LangOpts)) {
18457 Diag(Loc, diag::err_opencl_bitfields);
18458 InvalidDecl = true;
18462 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18463 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18464 T.hasQualifiers()) {
18465 InvalidDecl = true;
18466 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18469 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18470 // than a variably modified type.
18471 if (!InvalidDecl && T->isVariablyModifiedType()) {
18472 if (!tryToFixVariablyModifiedVarType(
18473 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18474 InvalidDecl = true;
18477 // Fields can not have abstract class types
18478 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18479 diag::err_abstract_type_in_decl,
18480 AbstractFieldType))
18481 InvalidDecl = true;
18483 if (InvalidDecl)
18484 BitWidth = nullptr;
18485 // If this is declared as a bit-field, check the bit-field.
18486 if (BitWidth) {
18487 BitWidth =
18488 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18489 if (!BitWidth) {
18490 InvalidDecl = true;
18491 BitWidth = nullptr;
18495 // Check that 'mutable' is consistent with the type of the declaration.
18496 if (!InvalidDecl && Mutable) {
18497 unsigned DiagID = 0;
18498 if (T->isReferenceType())
18499 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18500 : diag::err_mutable_reference;
18501 else if (T.isConstQualified())
18502 DiagID = diag::err_mutable_const;
18504 if (DiagID) {
18505 SourceLocation ErrLoc = Loc;
18506 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18507 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18508 Diag(ErrLoc, DiagID);
18509 if (DiagID != diag::ext_mutable_reference) {
18510 Mutable = false;
18511 InvalidDecl = true;
18516 // C++11 [class.union]p8 (DR1460):
18517 // At most one variant member of a union may have a
18518 // brace-or-equal-initializer.
18519 if (InitStyle != ICIS_NoInit)
18520 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18522 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18523 BitWidth, Mutable, InitStyle);
18524 if (InvalidDecl)
18525 NewFD->setInvalidDecl();
18527 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18528 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18529 Diag(Loc, diag::err_duplicate_member) << II;
18530 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18531 NewFD->setInvalidDecl();
18534 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18535 if (Record->isUnion()) {
18536 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18537 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18538 if (RDecl->getDefinition()) {
18539 // C++ [class.union]p1: An object of a class with a non-trivial
18540 // constructor, a non-trivial copy constructor, a non-trivial
18541 // destructor, or a non-trivial copy assignment operator
18542 // cannot be a member of a union, nor can an array of such
18543 // objects.
18544 if (CheckNontrivialField(NewFD))
18545 NewFD->setInvalidDecl();
18549 // C++ [class.union]p1: If a union contains a member of reference type,
18550 // the program is ill-formed, except when compiling with MSVC extensions
18551 // enabled.
18552 if (EltTy->isReferenceType()) {
18553 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18554 diag::ext_union_member_of_reference_type :
18555 diag::err_union_member_of_reference_type)
18556 << NewFD->getDeclName() << EltTy;
18557 if (!getLangOpts().MicrosoftExt)
18558 NewFD->setInvalidDecl();
18563 // FIXME: We need to pass in the attributes given an AST
18564 // representation, not a parser representation.
18565 if (D) {
18566 // FIXME: The current scope is almost... but not entirely... correct here.
18567 ProcessDeclAttributes(getCurScope(), NewFD, *D);
18569 if (NewFD->hasAttrs())
18570 CheckAlignasUnderalignment(NewFD);
18573 // In auto-retain/release, infer strong retension for fields of
18574 // retainable type.
18575 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
18576 NewFD->setInvalidDecl();
18578 if (T.isObjCGCWeak())
18579 Diag(Loc, diag::warn_attribute_weak_on_field);
18581 // PPC MMA non-pointer types are not allowed as field types.
18582 if (Context.getTargetInfo().getTriple().isPPC64() &&
18583 CheckPPCMMAType(T, NewFD->getLocation()))
18584 NewFD->setInvalidDecl();
18586 NewFD->setAccess(AS);
18587 return NewFD;
18590 bool Sema::CheckNontrivialField(FieldDecl *FD) {
18591 assert(FD);
18592 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18594 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18595 return false;
18597 QualType EltTy = Context.getBaseElementType(FD->getType());
18598 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18599 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18600 if (RDecl->getDefinition()) {
18601 // We check for copy constructors before constructors
18602 // because otherwise we'll never get complaints about
18603 // copy constructors.
18605 CXXSpecialMember member = CXXInvalid;
18606 // We're required to check for any non-trivial constructors. Since the
18607 // implicit default constructor is suppressed if there are any
18608 // user-declared constructors, we just need to check that there is a
18609 // trivial default constructor and a trivial copy constructor. (We don't
18610 // worry about move constructors here, since this is a C++98 check.)
18611 if (RDecl->hasNonTrivialCopyConstructor())
18612 member = CXXCopyConstructor;
18613 else if (!RDecl->hasTrivialDefaultConstructor())
18614 member = CXXDefaultConstructor;
18615 else if (RDecl->hasNonTrivialCopyAssignment())
18616 member = CXXCopyAssignment;
18617 else if (RDecl->hasNonTrivialDestructor())
18618 member = CXXDestructor;
18620 if (member != CXXInvalid) {
18621 if (!getLangOpts().CPlusPlus11 &&
18622 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18623 // Objective-C++ ARC: it is an error to have a non-trivial field of
18624 // a union. However, system headers in Objective-C programs
18625 // occasionally have Objective-C lifetime objects within unions,
18626 // and rather than cause the program to fail, we make those
18627 // members unavailable.
18628 SourceLocation Loc = FD->getLocation();
18629 if (getSourceManager().isInSystemHeader(Loc)) {
18630 if (!FD->hasAttr<UnavailableAttr>())
18631 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18632 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18633 return false;
18637 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
18638 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
18639 diag::err_illegal_union_or_anon_struct_member)
18640 << FD->getParent()->isUnion() << FD->getDeclName() << member;
18641 DiagnoseNontrivial(RDecl, member);
18642 return !getLangOpts().CPlusPlus11;
18647 return false;
18650 /// TranslateIvarVisibility - Translate visibility from a token ID to an
18651 /// AST enum value.
18652 static ObjCIvarDecl::AccessControl
18653 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
18654 switch (ivarVisibility) {
18655 default: llvm_unreachable("Unknown visitibility kind");
18656 case tok::objc_private: return ObjCIvarDecl::Private;
18657 case tok::objc_public: return ObjCIvarDecl::Public;
18658 case tok::objc_protected: return ObjCIvarDecl::Protected;
18659 case tok::objc_package: return ObjCIvarDecl::Package;
18663 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
18664 /// in order to create an IvarDecl object for it.
18665 Decl *Sema::ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D,
18666 Expr *BitWidth, tok::ObjCKeywordKind Visibility) {
18668 IdentifierInfo *II = D.getIdentifier();
18669 SourceLocation Loc = DeclStart;
18670 if (II) Loc = D.getIdentifierLoc();
18672 // FIXME: Unnamed fields can be handled in various different ways, for
18673 // example, unnamed unions inject all members into the struct namespace!
18675 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18676 QualType T = TInfo->getType();
18678 if (BitWidth) {
18679 // 6.7.2.1p3, 6.7.2.1p4
18680 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
18681 if (!BitWidth)
18682 D.setInvalidType();
18683 } else {
18684 // Not a bitfield.
18686 // validate II.
18689 if (T->isReferenceType()) {
18690 Diag(Loc, diag::err_ivar_reference_type);
18691 D.setInvalidType();
18693 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18694 // than a variably modified type.
18695 else if (T->isVariablyModifiedType()) {
18696 if (!tryToFixVariablyModifiedVarType(
18697 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
18698 D.setInvalidType();
18701 // Get the visibility (access control) for this ivar.
18702 ObjCIvarDecl::AccessControl ac =
18703 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
18704 : ObjCIvarDecl::None;
18705 // Must set ivar's DeclContext to its enclosing interface.
18706 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
18707 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
18708 return nullptr;
18709 ObjCContainerDecl *EnclosingContext;
18710 if (ObjCImplementationDecl *IMPDecl =
18711 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
18712 if (LangOpts.ObjCRuntime.isFragile()) {
18713 // Case of ivar declared in an implementation. Context is that of its class.
18714 EnclosingContext = IMPDecl->getClassInterface();
18715 assert(EnclosingContext && "Implementation has no class interface!");
18717 else
18718 EnclosingContext = EnclosingDecl;
18719 } else {
18720 if (ObjCCategoryDecl *CDecl =
18721 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
18722 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
18723 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
18724 return nullptr;
18727 EnclosingContext = EnclosingDecl;
18730 // Construct the decl.
18731 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(
18732 Context, EnclosingContext, DeclStart, Loc, II, T, TInfo, ac, BitWidth);
18734 if (T->containsErrors())
18735 NewID->setInvalidDecl();
18737 if (II) {
18738 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
18739 ForVisibleRedeclaration);
18740 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
18741 && !isa<TagDecl>(PrevDecl)) {
18742 Diag(Loc, diag::err_duplicate_member) << II;
18743 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18744 NewID->setInvalidDecl();
18748 // Process attributes attached to the ivar.
18749 ProcessDeclAttributes(S, NewID, D);
18751 if (D.isInvalidType())
18752 NewID->setInvalidDecl();
18754 // In ARC, infer 'retaining' for ivars of retainable type.
18755 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
18756 NewID->setInvalidDecl();
18758 if (D.getDeclSpec().isModulePrivateSpecified())
18759 NewID->setModulePrivate();
18761 if (II) {
18762 // FIXME: When interfaces are DeclContexts, we'll need to add
18763 // these to the interface.
18764 S->AddDecl(NewID);
18765 IdResolver.AddDecl(NewID);
18768 if (LangOpts.ObjCRuntime.isNonFragile() &&
18769 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
18770 Diag(Loc, diag::warn_ivars_in_interface);
18772 return NewID;
18775 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
18776 /// class and class extensions. For every class \@interface and class
18777 /// extension \@interface, if the last ivar is a bitfield of any type,
18778 /// then add an implicit `char :0` ivar to the end of that interface.
18779 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
18780 SmallVectorImpl<Decl *> &AllIvarDecls) {
18781 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18782 return;
18784 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18785 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18787 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18788 return;
18789 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18790 if (!ID) {
18791 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18792 if (!CD->IsClassExtension())
18793 return;
18795 // No need to add this to end of @implementation.
18796 else
18797 return;
18799 // All conditions are met. Add a new bitfield to the tail end of ivars.
18800 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18801 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18803 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18804 DeclLoc, DeclLoc, nullptr,
18805 Context.CharTy,
18806 Context.getTrivialTypeSourceInfo(Context.CharTy,
18807 DeclLoc),
18808 ObjCIvarDecl::Private, BW,
18809 true);
18810 AllIvarDecls.push_back(Ivar);
18813 /// [class.dtor]p4:
18814 /// At the end of the definition of a class, overload resolution is
18815 /// performed among the prospective destructors declared in that class with
18816 /// an empty argument list to select the destructor for the class, also
18817 /// known as the selected destructor.
18819 /// We do the overload resolution here, then mark the selected constructor in the AST.
18820 /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18821 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
18822 if (!Record->hasUserDeclaredDestructor()) {
18823 return;
18826 SourceLocation Loc = Record->getLocation();
18827 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
18829 for (auto *Decl : Record->decls()) {
18830 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18831 if (DD->isInvalidDecl())
18832 continue;
18833 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18834 OCS);
18835 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18839 if (OCS.empty()) {
18840 return;
18842 OverloadCandidateSet::iterator Best;
18843 unsigned Msg = 0;
18844 OverloadCandidateDisplayKind DisplayKind;
18846 switch (OCS.BestViableFunction(S, Loc, Best)) {
18847 case OR_Success:
18848 case OR_Deleted:
18849 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18850 break;
18852 case OR_Ambiguous:
18853 Msg = diag::err_ambiguous_destructor;
18854 DisplayKind = OCD_AmbiguousCandidates;
18855 break;
18857 case OR_No_Viable_Function:
18858 Msg = diag::err_no_viable_destructor;
18859 DisplayKind = OCD_AllCandidates;
18860 break;
18863 if (Msg) {
18864 // OpenCL have got their own thing going with destructors. It's slightly broken,
18865 // but we allow it.
18866 if (!S.LangOpts.OpenCL) {
18867 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18868 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18869 Record->setInvalidDecl();
18871 // It's a bit hacky: At this point we've raised an error but we want the
18872 // rest of the compiler to continue somehow working. However almost
18873 // everything we'll try to do with the class will depend on there being a
18874 // destructor. So let's pretend the first one is selected and hope for the
18875 // best.
18876 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18880 /// [class.mem.special]p5
18881 /// Two special member functions are of the same kind if:
18882 /// - they are both default constructors,
18883 /// - they are both copy or move constructors with the same first parameter
18884 /// type, or
18885 /// - they are both copy or move assignment operators with the same first
18886 /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18887 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
18888 CXXMethodDecl *M1,
18889 CXXMethodDecl *M2,
18890 Sema::CXXSpecialMember CSM) {
18891 // We don't want to compare templates to non-templates: See
18892 // https://github.com/llvm/llvm-project/issues/59206
18893 if (CSM == Sema::CXXDefaultConstructor)
18894 return bool(M1->getDescribedFunctionTemplate()) ==
18895 bool(M2->getDescribedFunctionTemplate());
18896 // FIXME: better resolve CWG
18897 // https://cplusplus.github.io/CWG/issues/2787.html
18898 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18899 M2->getNonObjectParameter(0)->getType()))
18900 return false;
18901 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
18902 M2->getFunctionObjectParameterReferenceType()))
18903 return false;
18905 return true;
18908 /// [class.mem.special]p6:
18909 /// An eligible special member function is a special member function for which:
18910 /// - the function is not deleted,
18911 /// - the associated constraints, if any, are satisfied, and
18912 /// - no special member function of the same kind whose associated constraints
18913 /// [CWG2595], if any, are satisfied is more constrained.
18914 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
18915 ArrayRef<CXXMethodDecl *> Methods,
18916 Sema::CXXSpecialMember CSM) {
18917 SmallVector<bool, 4> SatisfactionStatus;
18919 for (CXXMethodDecl *Method : Methods) {
18920 const Expr *Constraints = Method->getTrailingRequiresClause();
18921 if (!Constraints)
18922 SatisfactionStatus.push_back(true);
18923 else {
18924 ConstraintSatisfaction Satisfaction;
18925 if (S.CheckFunctionConstraints(Method, Satisfaction))
18926 SatisfactionStatus.push_back(false);
18927 else
18928 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18932 for (size_t i = 0; i < Methods.size(); i++) {
18933 if (!SatisfactionStatus[i])
18934 continue;
18935 CXXMethodDecl *Method = Methods[i];
18936 CXXMethodDecl *OrigMethod = Method;
18937 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18938 OrigMethod = cast<CXXMethodDecl>(MF);
18940 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18941 bool AnotherMethodIsMoreConstrained = false;
18942 for (size_t j = 0; j < Methods.size(); j++) {
18943 if (i == j || !SatisfactionStatus[j])
18944 continue;
18945 CXXMethodDecl *OtherMethod = Methods[j];
18946 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18947 OtherMethod = cast<CXXMethodDecl>(MF);
18949 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18950 CSM))
18951 continue;
18953 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18954 if (!OtherConstraints)
18955 continue;
18956 if (!Constraints) {
18957 AnotherMethodIsMoreConstrained = true;
18958 break;
18960 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18961 {Constraints},
18962 AnotherMethodIsMoreConstrained)) {
18963 // There was an error with the constraints comparison. Exit the loop
18964 // and don't consider this function eligible.
18965 AnotherMethodIsMoreConstrained = true;
18967 if (AnotherMethodIsMoreConstrained)
18968 break;
18970 // FIXME: Do not consider deleted methods as eligible after implementing
18971 // DR1734 and DR1496.
18972 if (!AnotherMethodIsMoreConstrained) {
18973 Method->setIneligibleOrNotSelected(false);
18974 Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
18979 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
18980 CXXRecordDecl *Record) {
18981 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18982 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18983 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18984 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18985 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18987 for (auto *Decl : Record->decls()) {
18988 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18989 if (!MD) {
18990 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18991 if (FTD)
18992 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18994 if (!MD)
18995 continue;
18996 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18997 if (CD->isInvalidDecl())
18998 continue;
18999 if (CD->isDefaultConstructor())
19000 DefaultConstructors.push_back(MD);
19001 else if (CD->isCopyConstructor())
19002 CopyConstructors.push_back(MD);
19003 else if (CD->isMoveConstructor())
19004 MoveConstructors.push_back(MD);
19005 } else if (MD->isCopyAssignmentOperator()) {
19006 CopyAssignmentOperators.push_back(MD);
19007 } else if (MD->isMoveAssignmentOperator()) {
19008 MoveAssignmentOperators.push_back(MD);
19012 SetEligibleMethods(S, Record, DefaultConstructors,
19013 Sema::CXXDefaultConstructor);
19014 SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
19015 SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
19016 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19017 Sema::CXXCopyAssignment);
19018 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19019 Sema::CXXMoveAssignment);
19022 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19023 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19024 SourceLocation RBrac,
19025 const ParsedAttributesView &Attrs) {
19026 assert(EnclosingDecl && "missing record or interface decl");
19028 // If this is an Objective-C @implementation or category and we have
19029 // new fields here we should reset the layout of the interface since
19030 // it will now change.
19031 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19032 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19033 switch (DC->getKind()) {
19034 default: break;
19035 case Decl::ObjCCategory:
19036 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19037 break;
19038 case Decl::ObjCImplementation:
19039 Context.
19040 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19041 break;
19045 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19046 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19048 // Start counting up the number of named members; make sure to include
19049 // members of anonymous structs and unions in the total.
19050 unsigned NumNamedMembers = 0;
19051 if (Record) {
19052 for (const auto *I : Record->decls()) {
19053 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19054 if (IFD->getDeclName())
19055 ++NumNamedMembers;
19059 // Verify that all the fields are okay.
19060 SmallVector<FieldDecl*, 32> RecFields;
19062 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19063 i != end; ++i) {
19064 FieldDecl *FD = cast<FieldDecl>(*i);
19066 // Get the type for the field.
19067 const Type *FDTy = FD->getType().getTypePtr();
19069 if (!FD->isAnonymousStructOrUnion()) {
19070 // Remember all fields written by the user.
19071 RecFields.push_back(FD);
19074 // If the field is already invalid for some reason, don't emit more
19075 // diagnostics about it.
19076 if (FD->isInvalidDecl()) {
19077 EnclosingDecl->setInvalidDecl();
19078 continue;
19081 // C99 6.7.2.1p2:
19082 // A structure or union shall not contain a member with
19083 // incomplete or function type (hence, a structure shall not
19084 // contain an instance of itself, but may contain a pointer to
19085 // an instance of itself), except that the last member of a
19086 // structure with more than one named member may have incomplete
19087 // array type; such a structure (and any union containing,
19088 // possibly recursively, a member that is such a structure)
19089 // shall not be a member of a structure or an element of an
19090 // array.
19091 bool IsLastField = (i + 1 == Fields.end());
19092 if (FDTy->isFunctionType()) {
19093 // Field declared as a function.
19094 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19095 << FD->getDeclName();
19096 FD->setInvalidDecl();
19097 EnclosingDecl->setInvalidDecl();
19098 continue;
19099 } else if (FDTy->isIncompleteArrayType() &&
19100 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19101 if (Record) {
19102 // Flexible array member.
19103 // Microsoft and g++ is more permissive regarding flexible array.
19104 // It will accept flexible array in union and also
19105 // as the sole element of a struct/class.
19106 unsigned DiagID = 0;
19107 if (!Record->isUnion() && !IsLastField) {
19108 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19109 << FD->getDeclName() << FD->getType()
19110 << llvm::to_underlying(Record->getTagKind());
19111 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19112 FD->setInvalidDecl();
19113 EnclosingDecl->setInvalidDecl();
19114 continue;
19115 } else if (Record->isUnion())
19116 DiagID = getLangOpts().MicrosoftExt
19117 ? diag::ext_flexible_array_union_ms
19118 : getLangOpts().CPlusPlus
19119 ? diag::ext_flexible_array_union_gnu
19120 : diag::err_flexible_array_union;
19121 else if (NumNamedMembers < 1)
19122 DiagID = getLangOpts().MicrosoftExt
19123 ? diag::ext_flexible_array_empty_aggregate_ms
19124 : getLangOpts().CPlusPlus
19125 ? diag::ext_flexible_array_empty_aggregate_gnu
19126 : diag::err_flexible_array_empty_aggregate;
19128 if (DiagID)
19129 Diag(FD->getLocation(), DiagID)
19130 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19131 // While the layout of types that contain virtual bases is not specified
19132 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19133 // virtual bases after the derived members. This would make a flexible
19134 // array member declared at the end of an object not adjacent to the end
19135 // of the type.
19136 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19137 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19138 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19139 if (!getLangOpts().C99)
19140 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19141 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19143 // If the element type has a non-trivial destructor, we would not
19144 // implicitly destroy the elements, so disallow it for now.
19146 // FIXME: GCC allows this. We should probably either implicitly delete
19147 // the destructor of the containing class, or just allow this.
19148 QualType BaseElem = Context.getBaseElementType(FD->getType());
19149 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19150 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19151 << FD->getDeclName() << FD->getType();
19152 FD->setInvalidDecl();
19153 EnclosingDecl->setInvalidDecl();
19154 continue;
19156 // Okay, we have a legal flexible array member at the end of the struct.
19157 Record->setHasFlexibleArrayMember(true);
19158 } else {
19159 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19160 // unless they are followed by another ivar. That check is done
19161 // elsewhere, after synthesized ivars are known.
19163 } else if (!FDTy->isDependentType() &&
19164 RequireCompleteSizedType(
19165 FD->getLocation(), FD->getType(),
19166 diag::err_field_incomplete_or_sizeless)) {
19167 // Incomplete type
19168 FD->setInvalidDecl();
19169 EnclosingDecl->setInvalidDecl();
19170 continue;
19171 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19172 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19173 // A type which contains a flexible array member is considered to be a
19174 // flexible array member.
19175 Record->setHasFlexibleArrayMember(true);
19176 if (!Record->isUnion()) {
19177 // If this is a struct/class and this is not the last element, reject
19178 // it. Note that GCC supports variable sized arrays in the middle of
19179 // structures.
19180 if (!IsLastField)
19181 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19182 << FD->getDeclName() << FD->getType();
19183 else {
19184 // We support flexible arrays at the end of structs in
19185 // other structs as an extension.
19186 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19187 << FD->getDeclName();
19191 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19192 RequireNonAbstractType(FD->getLocation(), FD->getType(),
19193 diag::err_abstract_type_in_decl,
19194 AbstractIvarType)) {
19195 // Ivars can not have abstract class types
19196 FD->setInvalidDecl();
19198 if (Record && FDTTy->getDecl()->hasObjectMember())
19199 Record->setHasObjectMember(true);
19200 if (Record && FDTTy->getDecl()->hasVolatileMember())
19201 Record->setHasVolatileMember(true);
19202 } else if (FDTy->isObjCObjectType()) {
19203 /// A field cannot be an Objective-c object
19204 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19205 << FixItHint::CreateInsertion(FD->getLocation(), "*");
19206 QualType T = Context.getObjCObjectPointerType(FD->getType());
19207 FD->setType(T);
19208 } else if (Record && Record->isUnion() &&
19209 FD->getType().hasNonTrivialObjCLifetime() &&
19210 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19211 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19212 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
19213 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19214 // For backward compatibility, fields of C unions declared in system
19215 // headers that have non-trivial ObjC ownership qualifications are marked
19216 // as unavailable unless the qualifier is explicit and __strong. This can
19217 // break ABI compatibility between programs compiled with ARC and MRR, but
19218 // is a better option than rejecting programs using those unions under
19219 // ARC.
19220 FD->addAttr(UnavailableAttr::CreateImplicit(
19221 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19222 FD->getLocation()));
19223 } else if (getLangOpts().ObjC &&
19224 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19225 !Record->hasObjectMember()) {
19226 if (FD->getType()->isObjCObjectPointerType() ||
19227 FD->getType().isObjCGCStrong())
19228 Record->setHasObjectMember(true);
19229 else if (Context.getAsArrayType(FD->getType())) {
19230 QualType BaseType = Context.getBaseElementType(FD->getType());
19231 if (BaseType->isRecordType() &&
19232 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19233 Record->setHasObjectMember(true);
19234 else if (BaseType->isObjCObjectPointerType() ||
19235 BaseType.isObjCGCStrong())
19236 Record->setHasObjectMember(true);
19240 if (Record && !getLangOpts().CPlusPlus &&
19241 !shouldIgnoreForRecordTriviality(FD)) {
19242 QualType FT = FD->getType();
19243 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
19244 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19245 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
19246 Record->isUnion())
19247 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19249 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
19250 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
19251 Record->setNonTrivialToPrimitiveCopy(true);
19252 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19253 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19255 if (FT.isDestructedType()) {
19256 Record->setNonTrivialToPrimitiveDestroy(true);
19257 Record->setParamDestroyedInCallee(true);
19258 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19259 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19262 if (const auto *RT = FT->getAs<RecordType>()) {
19263 if (RT->getDecl()->getArgPassingRestrictions() ==
19264 RecordArgPassingKind::CanNeverPassInRegs)
19265 Record->setArgPassingRestrictions(
19266 RecordArgPassingKind::CanNeverPassInRegs);
19267 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
19268 Record->setArgPassingRestrictions(
19269 RecordArgPassingKind::CanNeverPassInRegs);
19272 if (Record && FD->getType().isVolatileQualified())
19273 Record->setHasVolatileMember(true);
19274 // Keep track of the number of named members.
19275 if (FD->getIdentifier())
19276 ++NumNamedMembers;
19279 // Okay, we successfully defined 'Record'.
19280 if (Record) {
19281 bool Completed = false;
19282 if (CXXRecord) {
19283 if (!CXXRecord->isInvalidDecl()) {
19284 // Set access bits correctly on the directly-declared conversions.
19285 for (CXXRecordDecl::conversion_iterator
19286 I = CXXRecord->conversion_begin(),
19287 E = CXXRecord->conversion_end(); I != E; ++I)
19288 I.setAccess((*I)->getAccess());
19291 // Add any implicitly-declared members to this class.
19292 AddImplicitlyDeclaredMembersToClass(CXXRecord);
19294 if (!CXXRecord->isDependentType()) {
19295 if (!CXXRecord->isInvalidDecl()) {
19296 // If we have virtual base classes, we may end up finding multiple
19297 // final overriders for a given virtual function. Check for this
19298 // problem now.
19299 if (CXXRecord->getNumVBases()) {
19300 CXXFinalOverriderMap FinalOverriders;
19301 CXXRecord->getFinalOverriders(FinalOverriders);
19303 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19304 MEnd = FinalOverriders.end();
19305 M != MEnd; ++M) {
19306 for (OverridingMethods::iterator SO = M->second.begin(),
19307 SOEnd = M->second.end();
19308 SO != SOEnd; ++SO) {
19309 assert(SO->second.size() > 0 &&
19310 "Virtual function without overriding functions?");
19311 if (SO->second.size() == 1)
19312 continue;
19314 // C++ [class.virtual]p2:
19315 // In a derived class, if a virtual member function of a base
19316 // class subobject has more than one final overrider the
19317 // program is ill-formed.
19318 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19319 << (const NamedDecl *)M->first << Record;
19320 Diag(M->first->getLocation(),
19321 diag::note_overridden_virtual_function);
19322 for (OverridingMethods::overriding_iterator
19323 OM = SO->second.begin(),
19324 OMEnd = SO->second.end();
19325 OM != OMEnd; ++OM)
19326 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19327 << (const NamedDecl *)M->first << OM->Method->getParent();
19329 Record->setInvalidDecl();
19332 CXXRecord->completeDefinition(&FinalOverriders);
19333 Completed = true;
19336 ComputeSelectedDestructor(*this, CXXRecord);
19337 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
19341 if (!Completed)
19342 Record->completeDefinition();
19344 // Handle attributes before checking the layout.
19345 ProcessDeclAttributeList(S, Record, Attrs);
19347 // Check to see if a FieldDecl is a pointer to a function.
19348 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19349 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19350 if (!FD) {
19351 // Check whether this is a forward declaration that was inserted by
19352 // Clang. This happens when a non-forward declared / defined type is
19353 // used, e.g.:
19355 // struct foo {
19356 // struct bar *(*f)();
19357 // struct bar *(*g)();
19358 // };
19360 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19361 // incomplete definition.
19362 if (const auto *TD = dyn_cast<TagDecl>(D))
19363 return !TD->isCompleteDefinition();
19364 return false;
19366 QualType FieldType = FD->getType().getDesugaredType(Context);
19367 if (isa<PointerType>(FieldType)) {
19368 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19369 return PointeeType.getDesugaredType(Context)->isFunctionType();
19371 return false;
19374 // Maybe randomize the record's decls. We automatically randomize a record
19375 // of function pointers, unless it has the "no_randomize_layout" attribute.
19376 if (!getLangOpts().CPlusPlus &&
19377 (Record->hasAttr<RandomizeLayoutAttr>() ||
19378 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19379 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19380 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19381 !Record->isRandomized()) {
19382 SmallVector<Decl *, 32> NewDeclOrdering;
19383 if (randstruct::randomizeStructureLayout(Context, Record,
19384 NewDeclOrdering))
19385 Record->reorderDecls(NewDeclOrdering);
19388 // We may have deferred checking for a deleted destructor. Check now.
19389 if (CXXRecord) {
19390 auto *Dtor = CXXRecord->getDestructor();
19391 if (Dtor && Dtor->isImplicit() &&
19392 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
19393 CXXRecord->setImplicitDestructorIsDeleted();
19394 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19398 if (Record->hasAttrs()) {
19399 CheckAlignasUnderalignment(Record);
19401 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19402 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19403 IA->getRange(), IA->getBestCase(),
19404 IA->getInheritanceModel());
19407 // Check if the structure/union declaration is a type that can have zero
19408 // size in C. For C this is a language extension, for C++ it may cause
19409 // compatibility problems.
19410 bool CheckForZeroSize;
19411 if (!getLangOpts().CPlusPlus) {
19412 CheckForZeroSize = true;
19413 } else {
19414 // For C++ filter out types that cannot be referenced in C code.
19415 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19416 CheckForZeroSize =
19417 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19418 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19419 CXXRecord->isCLike();
19421 if (CheckForZeroSize) {
19422 bool ZeroSize = true;
19423 bool IsEmpty = true;
19424 unsigned NonBitFields = 0;
19425 for (RecordDecl::field_iterator I = Record->field_begin(),
19426 E = Record->field_end();
19427 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19428 IsEmpty = false;
19429 if (I->isUnnamedBitfield()) {
19430 if (!I->isZeroLengthBitField(Context))
19431 ZeroSize = false;
19432 } else {
19433 ++NonBitFields;
19434 QualType FieldType = I->getType();
19435 if (FieldType->isIncompleteType() ||
19436 !Context.getTypeSizeInChars(FieldType).isZero())
19437 ZeroSize = false;
19441 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19442 // allowed in C++, but warn if its declaration is inside
19443 // extern "C" block.
19444 if (ZeroSize) {
19445 Diag(RecLoc, getLangOpts().CPlusPlus ?
19446 diag::warn_zero_size_struct_union_in_extern_c :
19447 diag::warn_zero_size_struct_union_compat)
19448 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19451 // Structs without named members are extension in C (C99 6.7.2.1p7),
19452 // but are accepted by GCC.
19453 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19454 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19455 diag::ext_no_named_members_in_struct_union)
19456 << Record->isUnion();
19459 } else {
19460 ObjCIvarDecl **ClsFields =
19461 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19462 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19463 ID->setEndOfDefinitionLoc(RBrac);
19464 // Add ivar's to class's DeclContext.
19465 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19466 ClsFields[i]->setLexicalDeclContext(ID);
19467 ID->addDecl(ClsFields[i]);
19469 // Must enforce the rule that ivars in the base classes may not be
19470 // duplicates.
19471 if (ID->getSuperClass())
19472 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19473 } else if (ObjCImplementationDecl *IMPDecl =
19474 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19475 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19476 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19477 // Ivar declared in @implementation never belongs to the implementation.
19478 // Only it is in implementation's lexical context.
19479 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19480 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
19481 IMPDecl->setIvarLBraceLoc(LBrac);
19482 IMPDecl->setIvarRBraceLoc(RBrac);
19483 } else if (ObjCCategoryDecl *CDecl =
19484 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19485 // case of ivars in class extension; all other cases have been
19486 // reported as errors elsewhere.
19487 // FIXME. Class extension does not have a LocEnd field.
19488 // CDecl->setLocEnd(RBrac);
19489 // Add ivar's to class extension's DeclContext.
19490 // Diagnose redeclaration of private ivars.
19491 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19492 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19493 if (IDecl) {
19494 if (const ObjCIvarDecl *ClsIvar =
19495 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19496 Diag(ClsFields[i]->getLocation(),
19497 diag::err_duplicate_ivar_declaration);
19498 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19499 continue;
19501 for (const auto *Ext : IDecl->known_extensions()) {
19502 if (const ObjCIvarDecl *ClsExtIvar
19503 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19504 Diag(ClsFields[i]->getLocation(),
19505 diag::err_duplicate_ivar_declaration);
19506 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19507 continue;
19511 ClsFields[i]->setLexicalDeclContext(CDecl);
19512 CDecl->addDecl(ClsFields[i]);
19514 CDecl->setIvarLBraceLoc(LBrac);
19515 CDecl->setIvarRBraceLoc(RBrac);
19520 /// Determine whether the given integral value is representable within
19521 /// the given type T.
19522 static bool isRepresentableIntegerValue(ASTContext &Context,
19523 llvm::APSInt &Value,
19524 QualType T) {
19525 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19526 "Integral type required!");
19527 unsigned BitWidth = Context.getIntWidth(T);
19529 if (Value.isUnsigned() || Value.isNonNegative()) {
19530 if (T->isSignedIntegerOrEnumerationType())
19531 --BitWidth;
19532 return Value.getActiveBits() <= BitWidth;
19534 return Value.getSignificantBits() <= BitWidth;
19537 // Given an integral type, return the next larger integral type
19538 // (or a NULL type of no such type exists).
19539 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
19540 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19541 // enum checking below.
19542 assert((T->isIntegralType(Context) ||
19543 T->isEnumeralType()) && "Integral type required!");
19544 const unsigned NumTypes = 4;
19545 QualType SignedIntegralTypes[NumTypes] = {
19546 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19548 QualType UnsignedIntegralTypes[NumTypes] = {
19549 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19550 Context.UnsignedLongLongTy
19553 unsigned BitWidth = Context.getTypeSize(T);
19554 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19555 : UnsignedIntegralTypes;
19556 for (unsigned I = 0; I != NumTypes; ++I)
19557 if (Context.getTypeSize(Types[I]) > BitWidth)
19558 return Types[I];
19560 return QualType();
19563 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
19564 EnumConstantDecl *LastEnumConst,
19565 SourceLocation IdLoc,
19566 IdentifierInfo *Id,
19567 Expr *Val) {
19568 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19569 llvm::APSInt EnumVal(IntWidth);
19570 QualType EltTy;
19572 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
19573 Val = nullptr;
19575 if (Val)
19576 Val = DefaultLvalueConversion(Val).get();
19578 if (Val) {
19579 if (Enum->isDependentType() || Val->isTypeDependent() ||
19580 Val->containsErrors())
19581 EltTy = Context.DependentTy;
19582 else {
19583 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19584 // underlying type, but do allow it in all other contexts.
19585 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19586 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19587 // constant-expression in the enumerator-definition shall be a converted
19588 // constant expression of the underlying type.
19589 EltTy = Enum->getIntegerType();
19590 ExprResult Converted =
19591 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19592 CCEK_Enumerator);
19593 if (Converted.isInvalid())
19594 Val = nullptr;
19595 else
19596 Val = Converted.get();
19597 } else if (!Val->isValueDependent() &&
19598 !(Val =
19599 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
19600 .get())) {
19601 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19602 } else {
19603 if (Enum->isComplete()) {
19604 EltTy = Enum->getIntegerType();
19606 // In Obj-C and Microsoft mode, require the enumeration value to be
19607 // representable in the underlying type of the enumeration. In C++11,
19608 // we perform a non-narrowing conversion as part of converted constant
19609 // expression checking.
19610 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19611 if (Context.getTargetInfo()
19612 .getTriple()
19613 .isWindowsMSVCEnvironment()) {
19614 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19615 } else {
19616 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19620 // Cast to the underlying type.
19621 Val = ImpCastExprToType(Val, EltTy,
19622 EltTy->isBooleanType() ? CK_IntegralToBoolean
19623 : CK_IntegralCast)
19624 .get();
19625 } else if (getLangOpts().CPlusPlus) {
19626 // C++11 [dcl.enum]p5:
19627 // If the underlying type is not fixed, the type of each enumerator
19628 // is the type of its initializing value:
19629 // - If an initializer is specified for an enumerator, the
19630 // initializing value has the same type as the expression.
19631 EltTy = Val->getType();
19632 } else {
19633 // C99 6.7.2.2p2:
19634 // The expression that defines the value of an enumeration constant
19635 // shall be an integer constant expression that has a value
19636 // representable as an int.
19638 // Complain if the value is not representable in an int.
19639 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
19640 Diag(IdLoc, diag::ext_enum_value_not_int)
19641 << toString(EnumVal, 10) << Val->getSourceRange()
19642 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19643 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19644 // Force the type of the expression to 'int'.
19645 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19647 EltTy = Val->getType();
19653 if (!Val) {
19654 if (Enum->isDependentType())
19655 EltTy = Context.DependentTy;
19656 else if (!LastEnumConst) {
19657 // C++0x [dcl.enum]p5:
19658 // If the underlying type is not fixed, the type of each enumerator
19659 // is the type of its initializing value:
19660 // - If no initializer is specified for the first enumerator, the
19661 // initializing value has an unspecified integral type.
19663 // GCC uses 'int' for its unspecified integral type, as does
19664 // C99 6.7.2.2p3.
19665 if (Enum->isFixed()) {
19666 EltTy = Enum->getIntegerType();
19668 else {
19669 EltTy = Context.IntTy;
19671 } else {
19672 // Assign the last value + 1.
19673 EnumVal = LastEnumConst->getInitVal();
19674 ++EnumVal;
19675 EltTy = LastEnumConst->getType();
19677 // Check for overflow on increment.
19678 if (EnumVal < LastEnumConst->getInitVal()) {
19679 // C++0x [dcl.enum]p5:
19680 // If the underlying type is not fixed, the type of each enumerator
19681 // is the type of its initializing value:
19683 // - Otherwise the type of the initializing value is the same as
19684 // the type of the initializing value of the preceding enumerator
19685 // unless the incremented value is not representable in that type,
19686 // in which case the type is an unspecified integral type
19687 // sufficient to contain the incremented value. If no such type
19688 // exists, the program is ill-formed.
19689 QualType T = getNextLargerIntegralType(Context, EltTy);
19690 if (T.isNull() || Enum->isFixed()) {
19691 // There is no integral type larger enough to represent this
19692 // value. Complain, then allow the value to wrap around.
19693 EnumVal = LastEnumConst->getInitVal();
19694 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19695 ++EnumVal;
19696 if (Enum->isFixed())
19697 // When the underlying type is fixed, this is ill-formed.
19698 Diag(IdLoc, diag::err_enumerator_wrapped)
19699 << toString(EnumVal, 10)
19700 << EltTy;
19701 else
19702 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19703 << toString(EnumVal, 10);
19704 } else {
19705 EltTy = T;
19708 // Retrieve the last enumerator's value, extent that type to the
19709 // type that is supposed to be large enough to represent the incremented
19710 // value, then increment.
19711 EnumVal = LastEnumConst->getInitVal();
19712 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19713 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19714 ++EnumVal;
19716 // If we're not in C++, diagnose the overflow of enumerator values,
19717 // which in C99 means that the enumerator value is not representable in
19718 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19719 // permits enumerator values that are representable in some larger
19720 // integral type.
19721 if (!getLangOpts().CPlusPlus && !T.isNull())
19722 Diag(IdLoc, diag::warn_enum_value_overflow);
19723 } else if (!getLangOpts().CPlusPlus &&
19724 !EltTy->isDependentType() &&
19725 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19726 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19727 Diag(IdLoc, diag::ext_enum_value_not_int)
19728 << toString(EnumVal, 10) << 1;
19733 if (!EltTy->isDependentType()) {
19734 // Make the enumerator value match the signedness and size of the
19735 // enumerator's type.
19736 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19737 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19740 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19741 Val, EnumVal);
19744 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
19745 SourceLocation IILoc) {
19746 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19747 !getLangOpts().CPlusPlus)
19748 return SkipBodyInfo();
19750 // We have an anonymous enum definition. Look up the first enumerator to
19751 // determine if we should merge the definition with an existing one and
19752 // skip the body.
19753 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19754 forRedeclarationInCurContext());
19755 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19756 if (!PrevECD)
19757 return SkipBodyInfo();
19759 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19760 NamedDecl *Hidden;
19761 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19762 SkipBodyInfo Skip;
19763 Skip.Previous = Hidden;
19764 return Skip;
19767 return SkipBodyInfo();
19770 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19771 SourceLocation IdLoc, IdentifierInfo *Id,
19772 const ParsedAttributesView &Attrs,
19773 SourceLocation EqualLoc, Expr *Val) {
19774 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19775 EnumConstantDecl *LastEnumConst =
19776 cast_or_null<EnumConstantDecl>(lastEnumConst);
19778 // The scope passed in may not be a decl scope. Zip up the scope tree until
19779 // we find one that is.
19780 S = getNonFieldDeclScope(S);
19782 // Verify that there isn't already something declared with this name in this
19783 // scope.
19784 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
19785 LookupName(R, S);
19786 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19788 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19789 // Maybe we will complain about the shadowed template parameter.
19790 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19791 // Just pretend that we didn't see the previous declaration.
19792 PrevDecl = nullptr;
19795 // C++ [class.mem]p15:
19796 // If T is the name of a class, then each of the following shall have a name
19797 // different from T:
19798 // - every enumerator of every member of class T that is an unscoped
19799 // enumerated type
19800 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19801 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
19802 DeclarationNameInfo(Id, IdLoc));
19804 EnumConstantDecl *New =
19805 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19806 if (!New)
19807 return nullptr;
19809 if (PrevDecl) {
19810 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19811 // Check for other kinds of shadowing not already handled.
19812 CheckShadow(New, PrevDecl, R);
19815 // When in C++, we may get a TagDecl with the same name; in this case the
19816 // enum constant will 'hide' the tag.
19817 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19818 "Received TagDecl when not in C++!");
19819 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19820 if (isa<EnumConstantDecl>(PrevDecl))
19821 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19822 else
19823 Diag(IdLoc, diag::err_redefinition) << Id;
19824 notePreviousDefinition(PrevDecl, IdLoc);
19825 return nullptr;
19829 // Process attributes.
19830 ProcessDeclAttributeList(S, New, Attrs);
19831 AddPragmaAttributes(S, New);
19833 // Register this decl in the current scope stack.
19834 New->setAccess(TheEnumDecl->getAccess());
19835 PushOnScopeChains(New, S);
19837 ActOnDocumentableDecl(New);
19839 return New;
19842 // Returns true when the enum initial expression does not trigger the
19843 // duplicate enum warning. A few common cases are exempted as follows:
19844 // Element2 = Element1
19845 // Element2 = Element1 + 1
19846 // Element2 = Element1 - 1
19847 // Where Element2 and Element1 are from the same enum.
19848 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
19849 Expr *InitExpr = ECD->getInitExpr();
19850 if (!InitExpr)
19851 return true;
19852 InitExpr = InitExpr->IgnoreImpCasts();
19854 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19855 if (!BO->isAdditiveOp())
19856 return true;
19857 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19858 if (!IL)
19859 return true;
19860 if (IL->getValue() != 1)
19861 return true;
19863 InitExpr = BO->getLHS();
19866 // This checks if the elements are from the same enum.
19867 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19868 if (!DRE)
19869 return true;
19871 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19872 if (!EnumConstant)
19873 return true;
19875 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19876 Enum)
19877 return true;
19879 return false;
19882 // Emits a warning when an element is implicitly set a value that
19883 // a previous element has already been set to.
19884 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
19885 EnumDecl *Enum, QualType EnumType) {
19886 // Avoid anonymous enums
19887 if (!Enum->getIdentifier())
19888 return;
19890 // Only check for small enums.
19891 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19892 return;
19894 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19895 return;
19897 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19898 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19900 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19902 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19903 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19905 // Use int64_t as a key to avoid needing special handling for map keys.
19906 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19907 llvm::APSInt Val = D->getInitVal();
19908 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19911 DuplicatesVector DupVector;
19912 ValueToVectorMap EnumMap;
19914 // Populate the EnumMap with all values represented by enum constants without
19915 // an initializer.
19916 for (auto *Element : Elements) {
19917 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19919 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19920 // this constant. Skip this enum since it may be ill-formed.
19921 if (!ECD) {
19922 return;
19925 // Constants with initializers are handled in the next loop.
19926 if (ECD->getInitExpr())
19927 continue;
19929 // Duplicate values are handled in the next loop.
19930 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19933 if (EnumMap.size() == 0)
19934 return;
19936 // Create vectors for any values that has duplicates.
19937 for (auto *Element : Elements) {
19938 // The last loop returned if any constant was null.
19939 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19940 if (!ValidDuplicateEnum(ECD, Enum))
19941 continue;
19943 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19944 if (Iter == EnumMap.end())
19945 continue;
19947 DeclOrVector& Entry = Iter->second;
19948 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19949 // Ensure constants are different.
19950 if (D == ECD)
19951 continue;
19953 // Create new vector and push values onto it.
19954 auto Vec = std::make_unique<ECDVector>();
19955 Vec->push_back(D);
19956 Vec->push_back(ECD);
19958 // Update entry to point to the duplicates vector.
19959 Entry = Vec.get();
19961 // Store the vector somewhere we can consult later for quick emission of
19962 // diagnostics.
19963 DupVector.emplace_back(std::move(Vec));
19964 continue;
19967 ECDVector *Vec = Entry.get<ECDVector*>();
19968 // Make sure constants are not added more than once.
19969 if (*Vec->begin() == ECD)
19970 continue;
19972 Vec->push_back(ECD);
19975 // Emit diagnostics.
19976 for (const auto &Vec : DupVector) {
19977 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19979 // Emit warning for one enum constant.
19980 auto *FirstECD = Vec->front();
19981 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19982 << FirstECD << toString(FirstECD->getInitVal(), 10)
19983 << FirstECD->getSourceRange();
19985 // Emit one note for each of the remaining enum constants with
19986 // the same value.
19987 for (auto *ECD : llvm::drop_begin(*Vec))
19988 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19989 << ECD << toString(ECD->getInitVal(), 10)
19990 << ECD->getSourceRange();
19994 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19995 bool AllowMask) const {
19996 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19997 assert(ED->isCompleteDefinition() && "expected enum definition");
19999 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
20000 llvm::APInt &FlagBits = R.first->second;
20002 if (R.second) {
20003 for (auto *E : ED->enumerators()) {
20004 const auto &EVal = E->getInitVal();
20005 // Only single-bit enumerators introduce new flag values.
20006 if (EVal.isPowerOf2())
20007 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20011 // A value is in a flag enum if either its bits are a subset of the enum's
20012 // flag bits (the first condition) or we are allowing masks and the same is
20013 // true of its complement (the second condition). When masks are allowed, we
20014 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20016 // While it's true that any value could be used as a mask, the assumption is
20017 // that a mask will have all of the insignificant bits set. Anything else is
20018 // likely a logic error.
20019 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20020 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20023 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
20024 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20025 const ParsedAttributesView &Attrs) {
20026 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20027 QualType EnumType = Context.getTypeDeclType(Enum);
20029 ProcessDeclAttributeList(S, Enum, Attrs);
20031 if (Enum->isDependentType()) {
20032 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20033 EnumConstantDecl *ECD =
20034 cast_or_null<EnumConstantDecl>(Elements[i]);
20035 if (!ECD) continue;
20037 ECD->setType(EnumType);
20040 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20041 return;
20044 // TODO: If the result value doesn't fit in an int, it must be a long or long
20045 // long value. ISO C does not support this, but GCC does as an extension,
20046 // emit a warning.
20047 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20048 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20049 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20051 // Verify that all the values are okay, compute the size of the values, and
20052 // reverse the list.
20053 unsigned NumNegativeBits = 0;
20054 unsigned NumPositiveBits = 0;
20056 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20057 EnumConstantDecl *ECD =
20058 cast_or_null<EnumConstantDecl>(Elements[i]);
20059 if (!ECD) continue; // Already issued a diagnostic.
20061 const llvm::APSInt &InitVal = ECD->getInitVal();
20063 // Keep track of the size of positive and negative values.
20064 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20065 // If the enumerator is zero that should still be counted as a positive
20066 // bit since we need a bit to store the value zero.
20067 unsigned ActiveBits = InitVal.getActiveBits();
20068 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20069 } else {
20070 NumNegativeBits =
20071 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20075 // If we have an empty set of enumerators we still need one bit.
20076 // From [dcl.enum]p8
20077 // If the enumerator-list is empty, the values of the enumeration are as if
20078 // the enumeration had a single enumerator with value 0
20079 if (!NumPositiveBits && !NumNegativeBits)
20080 NumPositiveBits = 1;
20082 // Figure out the type that should be used for this enum.
20083 QualType BestType;
20084 unsigned BestWidth;
20086 // C++0x N3000 [conv.prom]p3:
20087 // An rvalue of an unscoped enumeration type whose underlying
20088 // type is not fixed can be converted to an rvalue of the first
20089 // of the following types that can represent all the values of
20090 // the enumeration: int, unsigned int, long int, unsigned long
20091 // int, long long int, or unsigned long long int.
20092 // C99 6.4.4.3p2:
20093 // An identifier declared as an enumeration constant has type int.
20094 // The C99 rule is modified by a gcc extension
20095 QualType BestPromotionType;
20097 bool Packed = Enum->hasAttr<PackedAttr>();
20098 // -fshort-enums is the equivalent to specifying the packed attribute on all
20099 // enum definitions.
20100 if (LangOpts.ShortEnums)
20101 Packed = true;
20103 // If the enum already has a type because it is fixed or dictated by the
20104 // target, promote that type instead of analyzing the enumerators.
20105 if (Enum->isComplete()) {
20106 BestType = Enum->getIntegerType();
20107 if (Context.isPromotableIntegerType(BestType))
20108 BestPromotionType = Context.getPromotedIntegerType(BestType);
20109 else
20110 BestPromotionType = BestType;
20112 BestWidth = Context.getIntWidth(BestType);
20114 else if (NumNegativeBits) {
20115 // If there is a negative value, figure out the smallest integer type (of
20116 // int/long/longlong) that fits.
20117 // If it's packed, check also if it fits a char or a short.
20118 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20119 BestType = Context.SignedCharTy;
20120 BestWidth = CharWidth;
20121 } else if (Packed && NumNegativeBits <= ShortWidth &&
20122 NumPositiveBits < ShortWidth) {
20123 BestType = Context.ShortTy;
20124 BestWidth = ShortWidth;
20125 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20126 BestType = Context.IntTy;
20127 BestWidth = IntWidth;
20128 } else {
20129 BestWidth = Context.getTargetInfo().getLongWidth();
20131 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20132 BestType = Context.LongTy;
20133 } else {
20134 BestWidth = Context.getTargetInfo().getLongLongWidth();
20136 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20137 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20138 BestType = Context.LongLongTy;
20141 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20142 } else {
20143 // If there is no negative value, figure out the smallest type that fits
20144 // all of the enumerator values.
20145 // If it's packed, check also if it fits a char or a short.
20146 if (Packed && NumPositiveBits <= CharWidth) {
20147 BestType = Context.UnsignedCharTy;
20148 BestPromotionType = Context.IntTy;
20149 BestWidth = CharWidth;
20150 } else if (Packed && NumPositiveBits <= ShortWidth) {
20151 BestType = Context.UnsignedShortTy;
20152 BestPromotionType = Context.IntTy;
20153 BestWidth = ShortWidth;
20154 } else if (NumPositiveBits <= IntWidth) {
20155 BestType = Context.UnsignedIntTy;
20156 BestWidth = IntWidth;
20157 BestPromotionType
20158 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20159 ? Context.UnsignedIntTy : Context.IntTy;
20160 } else if (NumPositiveBits <=
20161 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20162 BestType = Context.UnsignedLongTy;
20163 BestPromotionType
20164 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20165 ? Context.UnsignedLongTy : Context.LongTy;
20166 } else {
20167 BestWidth = Context.getTargetInfo().getLongLongWidth();
20168 assert(NumPositiveBits <= BestWidth &&
20169 "How could an initializer get larger than ULL?");
20170 BestType = Context.UnsignedLongLongTy;
20171 BestPromotionType
20172 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20173 ? Context.UnsignedLongLongTy : Context.LongLongTy;
20177 // Loop over all of the enumerator constants, changing their types to match
20178 // the type of the enum if needed.
20179 for (auto *D : Elements) {
20180 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20181 if (!ECD) continue; // Already issued a diagnostic.
20183 // Standard C says the enumerators have int type, but we allow, as an
20184 // extension, the enumerators to be larger than int size. If each
20185 // enumerator value fits in an int, type it as an int, otherwise type it the
20186 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20187 // that X has type 'int', not 'unsigned'.
20189 // Determine whether the value fits into an int.
20190 llvm::APSInt InitVal = ECD->getInitVal();
20192 // If it fits into an integer type, force it. Otherwise force it to match
20193 // the enum decl type.
20194 QualType NewTy;
20195 unsigned NewWidth;
20196 bool NewSign;
20197 if (!getLangOpts().CPlusPlus &&
20198 !Enum->isFixed() &&
20199 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
20200 NewTy = Context.IntTy;
20201 NewWidth = IntWidth;
20202 NewSign = true;
20203 } else if (ECD->getType() == BestType) {
20204 // Already the right type!
20205 if (getLangOpts().CPlusPlus)
20206 // C++ [dcl.enum]p4: Following the closing brace of an
20207 // enum-specifier, each enumerator has the type of its
20208 // enumeration.
20209 ECD->setType(EnumType);
20210 continue;
20211 } else {
20212 NewTy = BestType;
20213 NewWidth = BestWidth;
20214 NewSign = BestType->isSignedIntegerOrEnumerationType();
20217 // Adjust the APSInt value.
20218 InitVal = InitVal.extOrTrunc(NewWidth);
20219 InitVal.setIsSigned(NewSign);
20220 ECD->setInitVal(InitVal);
20222 // Adjust the Expr initializer and type.
20223 if (ECD->getInitExpr() &&
20224 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20225 ECD->setInitExpr(ImplicitCastExpr::Create(
20226 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20227 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20228 if (getLangOpts().CPlusPlus)
20229 // C++ [dcl.enum]p4: Following the closing brace of an
20230 // enum-specifier, each enumerator has the type of its
20231 // enumeration.
20232 ECD->setType(EnumType);
20233 else
20234 ECD->setType(NewTy);
20237 Enum->completeDefinition(BestType, BestPromotionType,
20238 NumPositiveBits, NumNegativeBits);
20240 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20242 if (Enum->isClosedFlag()) {
20243 for (Decl *D : Elements) {
20244 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20245 if (!ECD) continue; // Already issued a diagnostic.
20247 llvm::APSInt InitVal = ECD->getInitVal();
20248 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20249 !IsValueInFlagEnum(Enum, InitVal, true))
20250 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20251 << ECD << Enum;
20255 // Now that the enum type is defined, ensure it's not been underaligned.
20256 if (Enum->hasAttrs())
20257 CheckAlignasUnderalignment(Enum);
20260 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
20261 SourceLocation StartLoc,
20262 SourceLocation EndLoc) {
20263 StringLiteral *AsmString = cast<StringLiteral>(expr);
20265 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
20266 AsmString, StartLoc,
20267 EndLoc);
20268 CurContext->addDecl(New);
20269 return New;
20272 Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) {
20273 auto *New = TopLevelStmtDecl::Create(Context, Statement);
20274 Context.getTranslationUnitDecl()->addDecl(New);
20275 return New;
20278 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
20279 IdentifierInfo* AliasName,
20280 SourceLocation PragmaLoc,
20281 SourceLocation NameLoc,
20282 SourceLocation AliasNameLoc) {
20283 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20284 LookupOrdinaryName);
20285 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20286 AttributeCommonInfo::Form::Pragma());
20287 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20288 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20290 // If a declaration that:
20291 // 1) declares a function or a variable
20292 // 2) has external linkage
20293 // already exists, add a label attribute to it.
20294 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20295 if (isDeclExternC(PrevDecl))
20296 PrevDecl->addAttr(Attr);
20297 else
20298 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20299 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20300 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20301 } else
20302 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20305 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
20306 SourceLocation PragmaLoc,
20307 SourceLocation NameLoc) {
20308 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20310 if (PrevDecl) {
20311 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20312 } else {
20313 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20317 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
20318 IdentifierInfo* AliasName,
20319 SourceLocation PragmaLoc,
20320 SourceLocation NameLoc,
20321 SourceLocation AliasNameLoc) {
20322 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20323 LookupOrdinaryName);
20324 WeakInfo W = WeakInfo(Name, NameLoc);
20326 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20327 if (!PrevDecl->hasAttr<AliasAttr>())
20328 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20329 DeclApplyPragmaWeak(TUScope, ND, W);
20330 } else {
20331 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20335 ObjCContainerDecl *Sema::getObjCDeclContext() const {
20336 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
20339 Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD,
20340 bool Final) {
20341 assert(FD && "Expected non-null FunctionDecl");
20343 // SYCL functions can be template, so we check if they have appropriate
20344 // attribute prior to checking if it is a template.
20345 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20346 return FunctionEmissionStatus::Emitted;
20348 // Templates are emitted when they're instantiated.
20349 if (FD->isDependentContext())
20350 return FunctionEmissionStatus::TemplateDiscarded;
20352 // Check whether this function is an externally visible definition.
20353 auto IsEmittedForExternalSymbol = [this, FD]() {
20354 // We have to check the GVA linkage of the function's *definition* -- if we
20355 // only have a declaration, we don't know whether or not the function will
20356 // be emitted, because (say) the definition could include "inline".
20357 const FunctionDecl *Def = FD->getDefinition();
20359 return Def && !isDiscardableGVALinkage(
20360 getASTContext().GetGVALinkageForFunction(Def));
20363 if (LangOpts.OpenMPIsTargetDevice) {
20364 // In OpenMP device mode we will not emit host only functions, or functions
20365 // we don't need due to their linkage.
20366 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20367 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20368 // DevTy may be changed later by
20369 // #pragma omp declare target to(*) device_type(*).
20370 // Therefore DevTy having no value does not imply host. The emission status
20371 // will be checked again at the end of compilation unit with Final = true.
20372 if (DevTy)
20373 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20374 return FunctionEmissionStatus::OMPDiscarded;
20375 // If we have an explicit value for the device type, or we are in a target
20376 // declare context, we need to emit all extern and used symbols.
20377 if (isInOpenMPDeclareTargetContext() || DevTy)
20378 if (IsEmittedForExternalSymbol())
20379 return FunctionEmissionStatus::Emitted;
20380 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20381 // we'll omit it.
20382 if (Final)
20383 return FunctionEmissionStatus::OMPDiscarded;
20384 } else if (LangOpts.OpenMP > 45) {
20385 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20386 // function. In 5.0, no_host was introduced which might cause a function to
20387 // be ommitted.
20388 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20389 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20390 if (DevTy)
20391 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20392 return FunctionEmissionStatus::OMPDiscarded;
20395 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20396 return FunctionEmissionStatus::Emitted;
20398 if (LangOpts.CUDA) {
20399 // When compiling for device, host functions are never emitted. Similarly,
20400 // when compiling for host, device and global functions are never emitted.
20401 // (Technically, we do emit a host-side stub for global functions, but this
20402 // doesn't count for our purposes here.)
20403 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
20404 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
20405 return FunctionEmissionStatus::CUDADiscarded;
20406 if (!LangOpts.CUDAIsDevice &&
20407 (T == Sema::CFT_Device || T == Sema::CFT_Global))
20408 return FunctionEmissionStatus::CUDADiscarded;
20410 if (IsEmittedForExternalSymbol())
20411 return FunctionEmissionStatus::Emitted;
20414 // Otherwise, the function is known-emitted if it's in our set of
20415 // known-emitted functions.
20416 return FunctionEmissionStatus::Unknown;
20419 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
20420 // Host-side references to a __global__ function refer to the stub, so the
20421 // function itself is never emitted and therefore should not be marked.
20422 // If we have host fn calls kernel fn calls host+device, the HD function
20423 // does not get instantiated on the host. We model this by omitting at the
20424 // call to the kernel from the callgraph. This ensures that, when compiling
20425 // for host, only HD functions actually called from the host get marked as
20426 // known-emitted.
20427 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20428 IdentifyCUDATarget(Callee) == CFT_Global;