1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for declarations.
12 //===----------------------------------------------------------------------===//
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.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/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
51 using namespace clang;
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
56 Decl *Group[2] = { OwnedType, Ptr };
57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68 bool AllowTemplates = false,
69 bool AllowNonTemplates = true)
70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72 WantExpressionKeywords = false;
73 WantCXXNamedCasts = false;
74 WantRemainingKeywords = false;
77 bool ValidateCandidate(const TypoCorrection &candidate) override {
78 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79 if (!AllowInvalidDecl && ND->isInvalidDecl())
82 if (getAsTypeTemplateDecl(ND))
83 return AllowTemplates;
85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
89 if (AllowNonTemplates)
92 // An injected-class-name of a class template (specialization) is valid
93 // as a template or as a non-template.
95 auto *RD = dyn_cast<CXXRecordDecl>(ND);
96 if (!RD || !RD->isInjectedClassName())
98 RD = cast<CXXRecordDecl>(RD->getDeclContext());
99 return RD->getDescribedClassTemplate() ||
100 isa<ClassTemplateSpecializationDecl>(RD);
106 return !WantClassName && candidate.isKeyword();
110 bool AllowInvalidDecl;
113 bool AllowNonTemplates;
116 } // end anonymous namespace
118 /// Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
121 // FIXME: Take into account the current language when deciding whether a
122 // token kind is a valid type specifier
125 case tok::kw___int64:
126 case tok::kw___int128:
128 case tok::kw_unsigned:
135 case tok::kw__Float16:
136 case tok::kw___float128:
137 case tok::kw_wchar_t:
139 case tok::kw___underlying_type:
140 case tok::kw___auto_type:
143 case tok::annot_typename:
144 case tok::kw_char16_t:
145 case tok::kw_char32_t:
147 case tok::annot_decltype:
148 case tok::kw_decltype:
149 return getLangOpts().CPlusPlus;
151 case tok::kw_char8_t:
152 return getLangOpts().Char8;
162 enum class UnqualifiedTypeNameLookupResult {
167 } // end anonymous namespace
169 /// Tries to perform unqualified lookup of the type decls in bases for
171 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
172 /// type decl, \a FoundType if only type decls are found.
173 static UnqualifiedTypeNameLookupResult
174 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
175 SourceLocation NameLoc,
176 const CXXRecordDecl *RD) {
177 if (!RD->hasDefinition())
178 return UnqualifiedTypeNameLookupResult::NotFound;
179 // Look for type decls in base classes.
180 UnqualifiedTypeNameLookupResult FoundTypeDecl =
181 UnqualifiedTypeNameLookupResult::NotFound;
182 for (const auto &Base : RD->bases()) {
183 const CXXRecordDecl *BaseRD = nullptr;
184 if (auto *BaseTT = Base.getType()->getAs<TagType>())
185 BaseRD = BaseTT->getAsCXXRecordDecl();
186 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
187 // Look for type decls in dependent base classes that have known primary
189 if (!TST || !TST->isDependentType())
191 auto *TD = TST->getTemplateName().getAsTemplateDecl();
194 if (auto *BasePrimaryTemplate =
195 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
196 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
197 BaseRD = BasePrimaryTemplate;
198 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
199 if (const ClassTemplatePartialSpecializationDecl *PS =
200 CTD->findPartialSpecialization(Base.getType()))
201 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
207 for (NamedDecl *ND : BaseRD->lookup(&II)) {
208 if (!isa<TypeDecl>(ND))
209 return UnqualifiedTypeNameLookupResult::FoundNonType;
210 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
212 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
213 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
214 case UnqualifiedTypeNameLookupResult::FoundNonType:
215 return UnqualifiedTypeNameLookupResult::FoundNonType;
216 case UnqualifiedTypeNameLookupResult::FoundType:
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219 case UnqualifiedTypeNameLookupResult::NotFound:
226 return FoundTypeDecl;
229 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
230 const IdentifierInfo &II,
231 SourceLocation NameLoc) {
232 // Lookup in the parent class template context, if any.
233 const CXXRecordDecl *RD = nullptr;
234 UnqualifiedTypeNameLookupResult FoundTypeDecl =
235 UnqualifiedTypeNameLookupResult::NotFound;
236 for (DeclContext *DC = S.CurContext;
237 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
238 DC = DC->getParent()) {
239 // Look for type decls in dependent base classes that have known primary
241 RD = dyn_cast<CXXRecordDecl>(DC);
242 if (RD && RD->getDescribedClassTemplate())
243 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
245 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
248 // We found some types in dependent base classes. Recover as if the user
249 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
250 // lookup during template instantiation.
251 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
253 ASTContext &Context = S.Context;
254 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
255 cast<Type>(Context.getRecordType(RD)));
256 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
259 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
261 TypeLocBuilder Builder;
262 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
263 DepTL.setNameLoc(NameLoc);
264 DepTL.setElaboratedKeywordLoc(SourceLocation());
265 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
266 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
269 /// If the identifier refers to a type name within this scope,
270 /// return the declaration of that type.
272 /// This routine performs ordinary name lookup of the identifier II
273 /// within the given scope, with optional C++ scope specifier SS, to
274 /// determine whether the name refers to a type. If so, returns an
275 /// opaque pointer (actually a QualType) corresponding to that
276 /// type. Otherwise, returns NULL.
277 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
278 Scope *S, CXXScopeSpec *SS,
279 bool isClassName, bool HasTrailingDot,
280 ParsedType ObjectTypePtr,
281 bool IsCtorOrDtorName,
282 bool WantNontrivialTypeSourceInfo,
283 bool IsClassTemplateDeductionContext,
284 IdentifierInfo **CorrectedII) {
285 // FIXME: Consider allowing this outside C++1z mode as an extension.
286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
288 !isClassName && !HasTrailingDot;
290 // Determine where we will perform name lookup.
291 DeclContext *LookupCtx = nullptr;
293 QualType ObjectType = ObjectTypePtr.get();
294 if (ObjectType->isRecordType())
295 LookupCtx = computeDeclContext(ObjectType);
296 } else if (SS && SS->isNotEmpty()) {
297 LookupCtx = computeDeclContext(*SS, false);
300 if (isDependentScopeSpecifier(*SS)) {
302 // A qualified-id that refers to a type and in which the
303 // nested-name-specifier depends on a template-parameter (14.6.2)
304 // shall be prefixed by the keyword typename to indicate that the
305 // qualified-id denotes a type, forming an
306 // elaborated-type-specifier (7.1.5.3).
308 // We therefore do not perform any name lookup if the result would
309 // refer to a member of an unknown specialization.
310 if (!isClassName && !IsCtorOrDtorName)
313 // We know from the grammar that this name refers to a type,
314 // so build a dependent node to describe the type.
315 if (WantNontrivialTypeSourceInfo)
316 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
318 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
319 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
321 return ParsedType::make(T);
327 if (!LookupCtx->isDependentContext() &&
328 RequireCompleteDeclContext(*SS, LookupCtx))
332 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
333 // lookup for class-names.
334 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
336 LookupResult Result(*this, &II, NameLoc, Kind);
338 // Perform "qualified" name lookup into the declaration context we
339 // computed, which is either the type of the base of a member access
340 // expression or the declaration context associated with a prior
341 // nested-name-specifier.
342 LookupQualifiedName(Result, LookupCtx);
344 if (ObjectTypePtr && Result.empty()) {
345 // C++ [basic.lookup.classref]p3:
346 // If the unqualified-id is ~type-name, the type-name is looked up
347 // in the context of the entire postfix-expression. If the type T of
348 // the object expression is of a class type C, the type-name is also
349 // looked up in the scope of class C. At least one of the lookups shall
350 // find a name that refers to (possibly cv-qualified) T.
351 LookupName(Result, S);
354 // Perform unqualified name lookup.
355 LookupName(Result, S);
357 // For unqualified lookup in a class template in MSVC mode, look into
358 // dependent base classes where the primary class template is known.
359 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
360 if (ParsedType TypeInBase =
361 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
366 NamedDecl *IIDecl = nullptr;
367 switch (Result.getResultKind()) {
368 case LookupResult::NotFound:
369 case LookupResult::NotFoundInCurrentInstantiation:
371 TypoCorrection Correction =
372 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
373 llvm::make_unique<TypeNameValidatorCCC>(
374 true, isClassName, AllowDeducedTemplate),
376 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
378 bool MemberOfUnknownSpecialization;
379 UnqualifiedId TemplateName;
380 TemplateName.setIdentifier(NewII, NameLoc);
381 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
382 CXXScopeSpec NewSS, *NewSSPtr = SS;
384 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
387 if (Correction && (NNS || NewII != &II) &&
388 // Ignore a correction to a template type as the to-be-corrected
389 // identifier is not a template (typo correction for template names
390 // is handled elsewhere).
391 !(getLangOpts().CPlusPlus && NewSSPtr &&
392 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
393 Template, MemberOfUnknownSpecialization))) {
394 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
395 isClassName, HasTrailingDot, ObjectTypePtr,
397 WantNontrivialTypeSourceInfo,
398 IsClassTemplateDeductionContext);
400 diagnoseTypo(Correction,
401 PDiag(diag::err_unknown_type_or_class_name_suggest)
402 << Result.getLookupName() << isClassName);
404 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
405 *CorrectedII = NewII;
410 // If typo correction failed or was not performed, fall through
412 case LookupResult::FoundOverloaded:
413 case LookupResult::FoundUnresolvedValue:
414 Result.suppressDiagnostics();
417 case LookupResult::Ambiguous:
418 // Recover from type-hiding ambiguities by hiding the type. We'll
419 // do the lookup again when looking for an object, and we can
420 // diagnose the error then. If we don't do this, then the error
421 // about hiding the type will be immediately followed by an error
422 // that only makes sense if the identifier was treated like a type.
423 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
424 Result.suppressDiagnostics();
428 // Look to see if we have a type anywhere in the list of results.
429 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
430 Res != ResEnd; ++Res) {
431 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
432 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
434 (*Res)->getLocation().getRawEncoding() <
435 IIDecl->getLocation().getRawEncoding())
441 // None of the entities we found is a type, so there is no way
442 // to even assume that the result is a type. In this case, don't
443 // complain about the ambiguity. The parser will either try to
444 // perform this lookup again (e.g., as an object name), which
445 // will produce the ambiguity, or will complain that it expected
447 Result.suppressDiagnostics();
451 // We found a type within the ambiguous lookup; diagnose the
452 // ambiguity and then return that type. This might be the right
453 // answer, or it might not be, but it suppresses any attempt to
454 // perform the name lookup again.
457 case LookupResult::Found:
458 IIDecl = Result.getFoundDecl();
462 assert(IIDecl && "Didn't find decl");
465 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
466 // C++ [class.qual]p2: A lookup that would find the injected-class-name
467 // instead names the constructors of the class, except when naming a class.
468 // This is ill-formed when we're not actually forming a ctor or dtor name.
469 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
470 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
471 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
472 FoundRD->isInjectedClassName() &&
473 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
474 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
477 DiagnoseUseOfDecl(IIDecl, NameLoc);
479 T = Context.getTypeDeclType(TD);
480 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
481 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
482 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
484 T = Context.getObjCInterfaceType(IDecl);
485 } else if (AllowDeducedTemplate) {
486 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
487 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
492 // If it's not plausibly a type, suppress diagnostics.
493 Result.suppressDiagnostics();
497 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
498 // constructor or destructor name (in such a case, the scope specifier
499 // will be attached to the enclosing Expr or Decl node).
500 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
501 !isa<ObjCInterfaceDecl>(IIDecl)) {
502 if (WantNontrivialTypeSourceInfo) {
503 // Construct a type with type-source information.
504 TypeLocBuilder Builder;
505 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
507 T = getElaboratedType(ETK_None, *SS, T);
508 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
509 ElabTL.setElaboratedKeywordLoc(SourceLocation());
510 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
511 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
513 T = getElaboratedType(ETK_None, *SS, T);
517 return ParsedType::make(T);
520 // Builds a fake NNS for the given decl context.
521 static NestedNameSpecifier *
522 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
523 for (;; DC = DC->getLookupParent()) {
524 DC = DC->getPrimaryContext();
525 auto *ND = dyn_cast<NamespaceDecl>(DC);
526 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
527 return NestedNameSpecifier::Create(Context, nullptr, ND);
528 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
529 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
530 RD->getTypeForDecl());
531 else if (isa<TranslationUnitDecl>(DC))
532 return NestedNameSpecifier::GlobalSpecifier(Context);
534 llvm_unreachable("something isn't in TU scope?");
537 /// Find the parent class with dependent bases of the innermost enclosing method
538 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
539 /// up allowing unqualified dependent type names at class-level, which MSVC
540 /// correctly rejects.
541 static const CXXRecordDecl *
542 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
543 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
544 DC = DC->getPrimaryContext();
545 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
546 if (MD->getParent()->hasAnyDependentBases())
547 return MD->getParent();
552 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
553 SourceLocation NameLoc,
554 bool IsTemplateTypeArg) {
555 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
557 NestedNameSpecifier *NNS = nullptr;
558 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
559 // If we weren't able to parse a default template argument, delay lookup
560 // until instantiation time by making a non-dependent DependentTypeName. We
561 // pretend we saw a NestedNameSpecifier referring to the current scope, and
562 // lookup is retried.
563 // FIXME: This hurts our diagnostic quality, since we get errors like "no
564 // type named 'Foo' in 'current_namespace'" when the user didn't write any
566 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
567 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
568 } else if (const CXXRecordDecl *RD =
569 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
570 // Build a DependentNameType that will perform lookup into RD at
571 // instantiation time.
572 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
573 RD->getTypeForDecl());
575 // Diagnose that this identifier was undeclared, and retry the lookup during
576 // template instantiation.
577 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
580 // This is not a situation that we should recover from.
584 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
586 // Build type location information. We synthesized the qualifier, so we have
587 // to build a fake NestedNameSpecifierLoc.
588 NestedNameSpecifierLocBuilder NNSLocBuilder;
589 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
590 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
592 TypeLocBuilder Builder;
593 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
594 DepTL.setNameLoc(NameLoc);
595 DepTL.setElaboratedKeywordLoc(SourceLocation());
596 DepTL.setQualifierLoc(QualifierLoc);
597 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
600 /// isTagName() - This method is called *for error recovery purposes only*
601 /// to determine if the specified name is a valid tag name ("struct foo"). If
602 /// so, this returns the TST for the tag corresponding to it (TST_enum,
603 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
604 /// cases in C where the user forgot to specify the tag.
605 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
606 // Do a tag name lookup in this scope.
607 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
608 LookupName(R, S, false);
609 R.suppressDiagnostics();
610 if (R.getResultKind() == LookupResult::Found)
611 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
612 switch (TD->getTagKind()) {
613 case TTK_Struct: return DeclSpec::TST_struct;
614 case TTK_Interface: return DeclSpec::TST_interface;
615 case TTK_Union: return DeclSpec::TST_union;
616 case TTK_Class: return DeclSpec::TST_class;
617 case TTK_Enum: return DeclSpec::TST_enum;
621 return DeclSpec::TST_unspecified;
624 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
625 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
626 /// then downgrade the missing typename error to a warning.
627 /// This is needed for MSVC compatibility; Example:
629 /// template<class T> class A {
631 /// typedef int TYPE;
633 /// template<class T> class B : public A<T> {
635 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
638 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
639 if (CurContext->isRecord()) {
640 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
643 const Type *Ty = SS->getScopeRep()->getAsType();
645 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
646 for (const auto &Base : RD->bases())
647 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
649 return S->isFunctionPrototypeScope();
651 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
654 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
655 SourceLocation IILoc,
658 ParsedType &SuggestedType,
659 bool IsTemplateName) {
660 // Don't report typename errors for editor placeholders.
661 if (II->isEditorPlaceholder())
663 // We don't have anything to suggest (yet).
664 SuggestedType = nullptr;
666 // There may have been a typo in the name of the type. Look up typo
667 // results, in case we have something that we can suggest.
668 if (TypoCorrection Corrected =
669 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
670 llvm::make_unique<TypeNameValidatorCCC>(
671 false, false, IsTemplateName, !IsTemplateName),
672 CTK_ErrorRecovery)) {
673 // FIXME: Support error recovery for the template-name case.
674 bool CanRecover = !IsTemplateName;
675 if (Corrected.isKeyword()) {
676 // We corrected to a keyword.
677 diagnoseTypo(Corrected,
678 PDiag(IsTemplateName ? diag::err_no_template_suggest
679 : diag::err_unknown_typename_suggest)
681 II = Corrected.getCorrectionAsIdentifierInfo();
683 // We found a similarly-named type or interface; suggest that.
684 if (!SS || !SS->isSet()) {
685 diagnoseTypo(Corrected,
686 PDiag(IsTemplateName ? diag::err_no_template_suggest
687 : diag::err_unknown_typename_suggest)
689 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
690 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
691 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
692 II->getName().equals(CorrectedStr);
693 diagnoseTypo(Corrected,
695 ? diag::err_no_member_template_suggest
696 : diag::err_unknown_nested_typename_suggest)
697 << II << DC << DroppedSpecifier << SS->getRange(),
700 llvm_unreachable("could not have corrected a typo here");
707 if (Corrected.getCorrectionSpecifier())
708 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
710 // FIXME: Support class template argument deduction here.
712 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
713 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
714 /*IsCtorOrDtorName=*/false,
715 /*NonTrivialTypeSourceInfo=*/true);
720 if (getLangOpts().CPlusPlus && !IsTemplateName) {
721 // See if II is a class template that the user forgot to pass arguments to.
723 Name.setIdentifier(II, IILoc);
724 CXXScopeSpec EmptySS;
725 TemplateTy TemplateResult;
726 bool MemberOfUnknownSpecialization;
727 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
728 Name, nullptr, true, TemplateResult,
729 MemberOfUnknownSpecialization) == TNK_Type_template) {
730 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
735 // FIXME: Should we move the logic that tries to recover from a missing tag
736 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
738 if (!SS || (!SS->isSet() && !SS->isInvalid()))
739 Diag(IILoc, IsTemplateName ? diag::err_no_template
740 : diag::err_unknown_typename)
742 else if (DeclContext *DC = computeDeclContext(*SS, false))
743 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
744 : diag::err_typename_nested_not_found)
745 << II << DC << SS->getRange();
746 else if (isDependentScopeSpecifier(*SS)) {
747 unsigned DiagID = diag::err_typename_missing;
748 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
749 DiagID = diag::ext_typename_missing;
751 Diag(SS->getRange().getBegin(), DiagID)
752 << SS->getScopeRep() << II->getName()
753 << SourceRange(SS->getRange().getBegin(), IILoc)
754 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
755 SuggestedType = ActOnTypenameType(S, SourceLocation(),
756 *SS, *II, IILoc).get();
758 assert(SS && SS->isInvalid() &&
759 "Invalid scope specifier has already been diagnosed");
763 /// Determine whether the given result set contains either a type name
765 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
766 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
767 NextToken.is(tok::less);
769 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
770 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
773 if (CheckTemplate && isa<TemplateDecl>(*I))
780 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
781 Scope *S, CXXScopeSpec &SS,
782 IdentifierInfo *&Name,
783 SourceLocation NameLoc) {
784 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
785 SemaRef.LookupParsedName(R, S, &SS);
786 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
787 StringRef FixItTagName;
788 switch (Tag->getTagKind()) {
790 FixItTagName = "class ";
794 FixItTagName = "enum ";
798 FixItTagName = "struct ";
802 FixItTagName = "__interface ";
806 FixItTagName = "union ";
810 StringRef TagName = FixItTagName.drop_back();
811 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
812 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
813 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
815 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
817 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
820 // Replace lookup results with just the tag decl.
821 Result.clear(Sema::LookupTagName);
822 SemaRef.LookupParsedName(Result, S, &SS);
829 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
830 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
831 QualType T, SourceLocation NameLoc) {
832 ASTContext &Context = S.Context;
834 TypeLocBuilder Builder;
835 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
837 T = S.getElaboratedType(ETK_None, SS, T);
838 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
839 ElabTL.setElaboratedKeywordLoc(SourceLocation());
840 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
841 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
844 Sema::NameClassification
845 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
846 SourceLocation NameLoc, const Token &NextToken,
847 bool IsAddressOfOperand,
848 std::unique_ptr<CorrectionCandidateCallback> CCC) {
849 DeclarationNameInfo NameInfo(Name, NameLoc);
850 ObjCMethodDecl *CurMethod = getCurMethodDecl();
852 if (NextToken.is(tok::coloncolon)) {
853 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
854 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
855 } else if (getLangOpts().CPlusPlus && SS.isSet() &&
856 isCurrentClassName(*Name, S, &SS)) {
857 // Per [class.qual]p2, this names the constructors of SS, not the
858 // injected-class-name. We don't have a classification for that.
859 // There's not much point caching this result, since the parser
860 // will reject it later.
861 return NameClassification::Unknown();
864 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
865 LookupParsedName(Result, S, &SS, !CurMethod);
867 // For unqualified lookup in a class template in MSVC mode, look into
868 // dependent base classes where the primary class template is known.
869 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
870 if (ParsedType TypeInBase =
871 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875 // Perform lookup for Objective-C instance variables (including automatically
876 // synthesized instance variables), if we're in an Objective-C method.
877 // FIXME: This lookup really, really needs to be folded in to the normal
878 // unqualified lookup mechanism.
879 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
880 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
881 if (E.get() || E.isInvalid())
885 bool SecondTry = false;
886 bool IsFilteredTemplateName = false;
889 switch (Result.getResultKind()) {
890 case LookupResult::NotFound:
891 // If an unqualified-id is followed by a '(', then we have a function
893 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
894 // In C++, this is an ADL-only call.
896 if (getLangOpts().CPlusPlus)
897 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
900 // If the expression that precedes the parenthesized argument list in a
901 // function call consists solely of an identifier, and if no
902 // declaration is visible for this identifier, the identifier is
903 // implicitly declared exactly as if, in the innermost block containing
904 // the function call, the declaration
906 // extern int identifier ();
910 // We also allow this in C99 as an extension.
911 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
913 Result.resolveKind();
914 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918 // In C, we first see whether there is a tag type by the same name, in
919 // which case it's likely that the user just forgot to write "enum",
920 // "struct", or "union".
921 if (!getLangOpts().CPlusPlus && !SecondTry &&
922 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
926 // Perform typo correction to determine if there is another name that is
927 // close to this name.
928 if (!SecondTry && CCC) {
930 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
931 Result.getLookupKind(), S,
933 CTK_ErrorRecovery)) {
934 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
935 unsigned QualifiedDiag = diag::err_no_member_suggest;
937 NamedDecl *FirstDecl = Corrected.getFoundDecl();
938 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
939 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
940 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
941 UnqualifiedDiag = diag::err_no_template_suggest;
942 QualifiedDiag = diag::err_no_member_template_suggest;
943 } else if (UnderlyingFirstDecl &&
944 (isa<TypeDecl>(UnderlyingFirstDecl) ||
945 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
946 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
947 UnqualifiedDiag = diag::err_unknown_typename_suggest;
948 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
952 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
953 } else {// FIXME: is this even reachable? Test it.
954 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
955 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
956 Name->getName().equals(CorrectedStr);
957 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
958 << Name << computeDeclContext(SS, false)
959 << DroppedSpecifier << SS.getRange());
962 // Update the name, so that the caller has the new name.
963 Name = Corrected.getCorrectionAsIdentifierInfo();
965 // Typo correction corrected to a keyword.
966 if (Corrected.isKeyword())
969 // Also update the LookupResult...
970 // FIXME: This should probably go away at some point
972 Result.setLookupName(Corrected.getCorrection());
974 Result.addDecl(FirstDecl);
976 // If we found an Objective-C instance variable, let
977 // LookupInObjCMethod build the appropriate expression to
978 // reference the ivar.
979 // FIXME: This is a gross hack.
980 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
982 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
990 // We failed to correct; just fall through and let the parser deal with it.
991 Result.suppressDiagnostics();
992 return NameClassification::Unknown();
994 case LookupResult::NotFoundInCurrentInstantiation: {
995 // We performed name lookup into the current instantiation, and there were
996 // dependent bases, so we treat this result the same way as any other
997 // dependent nested-name-specifier.
1000 // A name used in a template declaration or definition and that is
1001 // dependent on a template-parameter is assumed not to name a type
1002 // unless the applicable name lookup finds a type name or the name is
1003 // qualified by the keyword typename.
1005 // FIXME: If the next token is '<', we might want to ask the parser to
1006 // perform some heroics to see if we actually have a
1007 // template-argument-list, which would indicate a missing 'template'
1009 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1010 NameInfo, IsAddressOfOperand,
1011 /*TemplateArgs=*/nullptr);
1014 case LookupResult::Found:
1015 case LookupResult::FoundOverloaded:
1016 case LookupResult::FoundUnresolvedValue:
1019 case LookupResult::Ambiguous:
1020 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1021 hasAnyAcceptableTemplateNames(Result)) {
1022 // C++ [temp.local]p3:
1023 // A lookup that finds an injected-class-name (10.2) can result in an
1024 // ambiguity in certain cases (for example, if it is found in more than
1025 // one base class). If all of the injected-class-names that are found
1026 // refer to specializations of the same class template, and if the name
1027 // is followed by a template-argument-list, the reference refers to the
1028 // class template itself and not a specialization thereof, and is not
1031 // This filtering can make an ambiguous result into an unambiguous one,
1032 // so try again after filtering out template names.
1033 FilterAcceptableTemplateNames(Result);
1034 if (!Result.isAmbiguous()) {
1035 IsFilteredTemplateName = true;
1040 // Diagnose the ambiguity and return an error.
1041 return NameClassification::Error();
1044 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1045 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1046 // C++ [temp.names]p3:
1047 // After name lookup (3.4) finds that a name is a template-name or that
1048 // an operator-function-id or a literal- operator-id refers to a set of
1049 // overloaded functions any member of which is a function template if
1050 // this is followed by a <, the < is always taken as the delimiter of a
1051 // template-argument-list and never as the less-than operator.
1052 if (!IsFilteredTemplateName)
1053 FilterAcceptableTemplateNames(Result);
1055 if (!Result.empty()) {
1056 bool IsFunctionTemplate;
1058 TemplateName Template;
1059 if (Result.end() - Result.begin() > 1) {
1060 IsFunctionTemplate = true;
1061 Template = Context.getOverloadedTemplateName(Result.begin(),
1065 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1066 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1067 IsVarTemplate = isa<VarTemplateDecl>(TD);
1069 if (SS.isSet() && !SS.isInvalid())
1070 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1071 /*TemplateKeyword=*/false,
1074 Template = TemplateName(TD);
1077 if (IsFunctionTemplate) {
1078 // Function templates always go through overload resolution, at which
1079 // point we'll perform the various checks (e.g., accessibility) we need
1080 // to based on which function we selected.
1081 Result.suppressDiagnostics();
1083 return NameClassification::FunctionTemplate(Template);
1086 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1087 : NameClassification::TypeTemplate(Template);
1091 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1092 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1093 DiagnoseUseOfDecl(Type, NameLoc);
1094 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1095 QualType T = Context.getTypeDeclType(Type);
1096 if (SS.isNotEmpty())
1097 return buildNestedType(*this, SS, T, NameLoc);
1098 return ParsedType::make(T);
1101 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1103 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1104 if (ObjCCompatibleAliasDecl *Alias =
1105 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1106 Class = Alias->getClassInterface();
1110 DiagnoseUseOfDecl(Class, NameLoc);
1112 if (NextToken.is(tok::period)) {
1113 // Interface. <something> is parsed as a property reference expression.
1114 // Just return "unknown" as a fall-through for now.
1115 Result.suppressDiagnostics();
1116 return NameClassification::Unknown();
1119 QualType T = Context.getObjCInterfaceType(Class);
1120 return ParsedType::make(T);
1123 // We can have a type template here if we're classifying a template argument.
1124 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1125 !isa<VarTemplateDecl>(FirstDecl))
1126 return NameClassification::TypeTemplate(
1127 TemplateName(cast<TemplateDecl>(FirstDecl)));
1129 // Check for a tag type hidden by a non-type decl in a few cases where it
1130 // seems likely a type is wanted instead of the non-type that was found.
1131 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1132 if ((NextToken.is(tok::identifier) ||
1134 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1135 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1136 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1137 DiagnoseUseOfDecl(Type, NameLoc);
1138 QualType T = Context.getTypeDeclType(Type);
1139 if (SS.isNotEmpty())
1140 return buildNestedType(*this, SS, T, NameLoc);
1141 return ParsedType::make(T);
1144 if (FirstDecl->isCXXClassMember())
1145 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1148 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1149 return BuildDeclarationNameExpr(SS, Result, ADL);
1152 Sema::TemplateNameKindForDiagnostics
1153 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1154 auto *TD = Name.getAsTemplateDecl();
1156 return TemplateNameKindForDiagnostics::DependentTemplate;
1157 if (isa<ClassTemplateDecl>(TD))
1158 return TemplateNameKindForDiagnostics::ClassTemplate;
1159 if (isa<FunctionTemplateDecl>(TD))
1160 return TemplateNameKindForDiagnostics::FunctionTemplate;
1161 if (isa<VarTemplateDecl>(TD))
1162 return TemplateNameKindForDiagnostics::VarTemplate;
1163 if (isa<TypeAliasTemplateDecl>(TD))
1164 return TemplateNameKindForDiagnostics::AliasTemplate;
1165 if (isa<TemplateTemplateParmDecl>(TD))
1166 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1167 return TemplateNameKindForDiagnostics::DependentTemplate;
1170 // Determines the context to return to after temporarily entering a
1171 // context. This depends in an unnecessarily complicated way on the
1172 // exact ordering of callbacks from the parser.
1173 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1175 // Functions defined inline within classes aren't parsed until we've
1176 // finished parsing the top-level class, so the top-level class is
1177 // the context we'll need to return to.
1178 // A Lambda call operator whose parent is a class must not be treated
1179 // as an inline member function. A Lambda can be used legally
1180 // either as an in-class member initializer or a default argument. These
1181 // are parsed once the class has been marked complete and so the containing
1182 // context would be the nested class (when the lambda is defined in one);
1183 // If the class is not complete, then the lambda is being used in an
1184 // ill-formed fashion (such as to specify the width of a bit-field, or
1185 // in an array-bound) - in which case we still want to return the
1186 // lexically containing DC (which could be a nested class).
1187 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1188 DC = DC->getLexicalParent();
1190 // A function not defined within a class will always return to its
1192 if (!isa<CXXRecordDecl>(DC))
1195 // A C++ inline method/friend is parsed *after* the topmost class
1196 // it was declared in is fully parsed ("complete"); the topmost
1197 // class is the context we need to return to.
1198 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1201 // Return the declaration context of the topmost class the inline method is
1206 return DC->getLexicalParent();
1209 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1210 assert(getContainingDC(DC) == CurContext &&
1211 "The next DeclContext should be lexically contained in the current one.");
1216 void Sema::PopDeclContext() {
1217 assert(CurContext && "DeclContext imbalance!");
1219 CurContext = getContainingDC(CurContext);
1220 assert(CurContext && "Popped translation unit!");
1223 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1225 // Unlike PushDeclContext, the context to which we return is not necessarily
1226 // the containing DC of TD, because the new context will be some pre-existing
1227 // TagDecl definition instead of a fresh one.
1228 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1229 CurContext = cast<TagDecl>(D)->getDefinition();
1230 assert(CurContext && "skipping definition of undefined tag");
1231 // Start lookups from the parent of the current context; we don't want to look
1232 // into the pre-existing complete definition.
1233 S->setEntity(CurContext->getLookupParent());
1237 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1238 CurContext = static_cast<decltype(CurContext)>(Context);
1241 /// EnterDeclaratorContext - Used when we must lookup names in the context
1242 /// of a declarator's nested name specifier.
1244 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1245 // C++0x [basic.lookup.unqual]p13:
1246 // A name used in the definition of a static data member of class
1247 // X (after the qualified-id of the static member) is looked up as
1248 // if the name was used in a member function of X.
1249 // C++0x [basic.lookup.unqual]p14:
1250 // If a variable member of a namespace is defined outside of the
1251 // scope of its namespace then any name used in the definition of
1252 // the variable member (after the declarator-id) is looked up as
1253 // if the definition of the variable member occurred in its
1255 // Both of these imply that we should push a scope whose context
1256 // is the semantic context of the declaration. We can't use
1257 // PushDeclContext here because that context is not necessarily
1258 // lexically contained in the current context. Fortunately,
1259 // the containing scope should have the appropriate information.
1261 assert(!S->getEntity() && "scope already has entity");
1264 Scope *Ancestor = S->getParent();
1265 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1266 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1273 void Sema::ExitDeclaratorContext(Scope *S) {
1274 assert(S->getEntity() == CurContext && "Context imbalance!");
1276 // Switch back to the lexical context. The safety of this is
1277 // enforced by an assert in EnterDeclaratorContext.
1278 Scope *Ancestor = S->getParent();
1279 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1280 CurContext = Ancestor->getEntity();
1282 // We don't need to do anything with the scope, which is going to
1286 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1287 // We assume that the caller has already called
1288 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1289 FunctionDecl *FD = D->getAsFunction();
1293 // Same implementation as PushDeclContext, but enters the context
1294 // from the lexical parent, rather than the top-level class.
1295 assert(CurContext == FD->getLexicalParent() &&
1296 "The next DeclContext should be lexically contained in the current one.");
1298 S->setEntity(CurContext);
1300 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1301 ParmVarDecl *Param = FD->getParamDecl(P);
1302 // If the parameter has an identifier, then add it to the scope
1303 if (Param->getIdentifier()) {
1305 IdResolver.AddDecl(Param);
1310 void Sema::ActOnExitFunctionContext() {
1311 // Same implementation as PopDeclContext, but returns to the lexical parent,
1312 // rather than the top-level class.
1313 assert(CurContext && "DeclContext imbalance!");
1314 CurContext = CurContext->getLexicalParent();
1315 assert(CurContext && "Popped translation unit!");
1318 /// Determine whether we allow overloading of the function
1319 /// PrevDecl with another declaration.
1321 /// This routine determines whether overloading is possible, not
1322 /// whether some new function is actually an overload. It will return
1323 /// true in C++ (where we can always provide overloads) or, as an
1324 /// extension, in C when the previous function is already an
1325 /// overloaded function declaration or has the "overloadable"
1327 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1328 ASTContext &Context,
1329 const FunctionDecl *New) {
1330 if (Context.getLangOpts().CPlusPlus)
1333 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1336 return Previous.getResultKind() == LookupResult::Found &&
1337 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1338 New->hasAttr<OverloadableAttr>());
1341 /// Add this decl to the scope shadowed decl chains.
1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1343 // Move up the scope chain until we find the nearest enclosing
1344 // non-transparent context. The declaration will be introduced into this
1346 while (S->getEntity() && S->getEntity()->isTransparentContext())
1349 // Add scoped declarations into their context, so that they can be
1350 // found later. Declarations without a context won't be inserted
1351 // into any context.
1353 CurContext->addDecl(D);
1355 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1356 // are function-local declarations.
1357 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1358 !D->getDeclContext()->getRedeclContext()->Equals(
1359 D->getLexicalDeclContext()->getRedeclContext()) &&
1360 !D->getLexicalDeclContext()->isFunctionOrMethod())
1363 // Template instantiations should also not be pushed into scope.
1364 if (isa<FunctionDecl>(D) &&
1365 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1368 // If this replaces anything in the current scope,
1369 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1370 IEnd = IdResolver.end();
1371 for (; I != IEnd; ++I) {
1372 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1374 IdResolver.RemoveDecl(*I);
1376 // Should only need to replace one decl.
1383 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1384 // Implicitly-generated labels may end up getting generated in an order that
1385 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1386 // the label at the appropriate place in the identifier chain.
1387 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1388 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1389 if (IDC == CurContext) {
1390 if (!S->isDeclScope(*I))
1392 } else if (IDC->Encloses(CurContext))
1396 IdResolver.InsertDeclAfter(I, D);
1398 IdResolver.AddDecl(D);
1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1403 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1404 TUScope->AddDecl(D);
1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1408 bool AllowInlineNamespace) {
1409 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1413 DeclContext *TargetDC = DC->getPrimaryContext();
1415 if (DeclContext *ScopeDC = S->getEntity())
1416 if (ScopeDC->getPrimaryContext() == TargetDC)
1418 } while ((S = S->getParent()));
1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1427 /// Filters out lookup results that don't fall within the given scope
1428 /// as determined by isDeclInScope.
1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1430 bool ConsiderLinkage,
1431 bool AllowInlineNamespace) {
1432 LookupResult::Filter F = R.makeFilter();
1433 while (F.hasNext()) {
1434 NamedDecl *D = F.next();
1436 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1439 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1449 /// have compatible owning modules.
1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1451 // FIXME: The Modules TS is not clear about how friend declarations are
1452 // to be treated. It's not meaningful to have different owning modules for
1453 // linkage in redeclarations of the same entity, so for now allow the
1454 // redeclaration and change the owning modules to match.
1455 if (New->getFriendObjectKind() &&
1456 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1457 New->setLocalOwningModule(Old->getOwningModule());
1458 makeMergedDefinitionVisible(New);
1462 Module *NewM = New->getOwningModule();
1463 Module *OldM = Old->getOwningModule();
1467 // FIXME: Check proclaimed-ownership-declarations here too.
1468 bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1469 bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1470 if (NewIsModuleInterface || OldIsModuleInterface) {
1471 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1472 // if a declaration of D [...] appears in the purview of a module, all
1473 // other such declarations shall appear in the purview of the same module
1474 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1476 << NewIsModuleInterface
1477 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1478 << OldIsModuleInterface
1479 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1480 Diag(Old->getLocation(), diag::note_previous_declaration);
1481 New->setInvalidDecl();
1488 static bool isUsingDecl(NamedDecl *D) {
1489 return isa<UsingShadowDecl>(D) ||
1490 isa<UnresolvedUsingTypenameDecl>(D) ||
1491 isa<UnresolvedUsingValueDecl>(D);
1494 /// Removes using shadow declarations from the lookup results.
1495 static void RemoveUsingDecls(LookupResult &R) {
1496 LookupResult::Filter F = R.makeFilter();
1498 if (isUsingDecl(F.next()))
1504 /// Check for this common pattern:
1507 /// S(const S&); // DO NOT IMPLEMENT
1508 /// void operator=(const S&); // DO NOT IMPLEMENT
1511 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1512 // FIXME: Should check for private access too but access is set after we get
1514 if (D->doesThisDeclarationHaveABody())
1517 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1518 return CD->isCopyConstructor();
1519 return D->isCopyAssignmentOperator();
1522 // We need this to handle
1525 // void *foo() { return 0; }
1528 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1529 // for example. If 'A', foo will have external linkage. If we have '*A',
1530 // foo will have no linkage. Since we can't know until we get to the end
1531 // of the typedef, this function finds out if D might have non-external linkage.
1532 // Callers should verify at the end of the TU if it D has external linkage or
1534 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1535 const DeclContext *DC = D->getDeclContext();
1536 while (!DC->isTranslationUnit()) {
1537 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1538 if (!RD->hasNameForLinkage())
1541 DC = DC->getParent();
1544 return !D->isExternallyVisible();
1547 // FIXME: This needs to be refactored; some other isInMainFile users want
1549 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1550 if (S.TUKind != TU_Complete)
1552 return S.SourceMgr.isInMainFile(Loc);
1555 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1558 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1561 // Ignore all entities declared within templates, and out-of-line definitions
1562 // of members of class templates.
1563 if (D->getDeclContext()->isDependentContext() ||
1564 D->getLexicalDeclContext()->isDependentContext())
1567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1568 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1570 // A non-out-of-line declaration of a member specialization was implicitly
1571 // instantiated; it's the out-of-line declaration that we're interested in.
1572 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1573 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1576 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1577 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1580 // 'static inline' functions are defined in headers; don't warn.
1581 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1585 if (FD->doesThisDeclarationHaveABody() &&
1586 Context.DeclMustBeEmitted(FD))
1588 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1589 // Constants and utility variables are defined in headers with internal
1590 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1592 if (!isMainFileLoc(*this, VD->getLocation()))
1595 if (Context.DeclMustBeEmitted(VD))
1598 if (VD->isStaticDataMember() &&
1599 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1601 if (VD->isStaticDataMember() &&
1602 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1603 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1606 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1612 // Only warn for unused decls internal to the translation unit.
1613 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1614 // for inline functions defined in the main source file, for instance.
1615 return mightHaveNonExternalLinkage(D);
1618 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1622 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1623 const FunctionDecl *First = FD->getFirstDecl();
1624 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1625 return; // First should already be in the vector.
1628 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1629 const VarDecl *First = VD->getFirstDecl();
1630 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1631 return; // First should already be in the vector.
1634 if (ShouldWarnIfUnusedFileScopedDecl(D))
1635 UnusedFileScopedDecls.push_back(D);
1638 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1639 if (D->isInvalidDecl())
1642 bool Referenced = false;
1643 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1644 // For a decomposition declaration, warn if none of the bindings are
1645 // referenced, instead of if the variable itself is referenced (which
1646 // it is, by the bindings' expressions).
1647 for (auto *BD : DD->bindings()) {
1648 if (BD->isReferenced()) {
1653 } else if (!D->getDeclName()) {
1655 } else if (D->isReferenced() || D->isUsed()) {
1659 if (Referenced || D->hasAttr<UnusedAttr>() ||
1660 D->hasAttr<ObjCPreciseLifetimeAttr>())
1663 if (isa<LabelDecl>(D))
1666 // Except for labels, we only care about unused decls that are local to
1668 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1669 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1670 // For dependent types, the diagnostic is deferred.
1672 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1673 if (!WithinFunction)
1676 if (isa<TypedefNameDecl>(D))
1679 // White-list anything that isn't a local variable.
1680 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1683 // Types of valid local variables should be complete, so this should succeed.
1684 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1686 // White-list anything with an __attribute__((unused)) type.
1687 const auto *Ty = VD->getType().getTypePtr();
1689 // Only look at the outermost level of typedef.
1690 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1691 if (TT->getDecl()->hasAttr<UnusedAttr>())
1695 // If we failed to complete the type for some reason, or if the type is
1696 // dependent, don't diagnose the variable.
1697 if (Ty->isIncompleteType() || Ty->isDependentType())
1700 // Look at the element type to ensure that the warning behaviour is
1701 // consistent for both scalars and arrays.
1702 Ty = Ty->getBaseElementTypeUnsafe();
1704 if (const TagType *TT = Ty->getAs<TagType>()) {
1705 const TagDecl *Tag = TT->getDecl();
1706 if (Tag->hasAttr<UnusedAttr>())
1709 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1710 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1713 if (const Expr *Init = VD->getInit()) {
1714 if (const ExprWithCleanups *Cleanups =
1715 dyn_cast<ExprWithCleanups>(Init))
1716 Init = Cleanups->getSubExpr();
1717 const CXXConstructExpr *Construct =
1718 dyn_cast<CXXConstructExpr>(Init);
1719 if (Construct && !Construct->isElidable()) {
1720 CXXConstructorDecl *CD = Construct->getConstructor();
1721 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1722 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1729 // TODO: __attribute__((unused)) templates?
1735 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1737 if (isa<LabelDecl>(D)) {
1738 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1739 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1740 if (AfterColon.isInvalid())
1742 Hint = FixItHint::CreateRemoval(CharSourceRange::
1743 getCharRange(D->getLocStart(), AfterColon));
1747 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1748 if (D->getTypeForDecl()->isDependentType())
1751 for (auto *TmpD : D->decls()) {
1752 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1753 DiagnoseUnusedDecl(T);
1754 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1755 DiagnoseUnusedNestedTypedefs(R);
1759 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1760 /// unless they are marked attr(unused).
1761 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1762 if (!ShouldDiagnoseUnusedDecl(D))
1765 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1766 // typedefs can be referenced later on, so the diagnostics are emitted
1767 // at end-of-translation-unit.
1768 UnusedLocalTypedefNameCandidates.insert(TD);
1773 GenerateFixForUnusedDecl(D, Context, Hint);
1776 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1777 DiagID = diag::warn_unused_exception_param;
1778 else if (isa<LabelDecl>(D))
1779 DiagID = diag::warn_unused_label;
1781 DiagID = diag::warn_unused_variable;
1783 Diag(D->getLocation(), DiagID) << D << Hint;
1786 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1787 // Verify that we have no forward references left. If so, there was a goto
1788 // or address of a label taken, but no definition of it. Label fwd
1789 // definitions are indicated with a null substmt which is also not a resolved
1790 // MS inline assembly label name.
1791 bool Diagnose = false;
1792 if (L->isMSAsmLabel())
1793 Diagnose = !L->isResolvedMSAsmLabel();
1795 Diagnose = L->getStmt() == nullptr;
1797 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1800 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1801 S->mergeNRVOIntoParent();
1803 if (S->decl_empty()) return;
1804 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1805 "Scope shouldn't contain decls!");
1807 for (auto *TmpD : S->decls()) {
1808 assert(TmpD && "This decl didn't get pushed??");
1810 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1811 NamedDecl *D = cast<NamedDecl>(TmpD);
1813 // Diagnose unused variables in this scope.
1814 if (!S->hasUnrecoverableErrorOccurred()) {
1815 DiagnoseUnusedDecl(D);
1816 if (const auto *RD = dyn_cast<RecordDecl>(D))
1817 DiagnoseUnusedNestedTypedefs(RD);
1820 if (!D->getDeclName()) continue;
1822 // If this was a forward reference to a label, verify it was defined.
1823 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1824 CheckPoppedLabel(LD, *this);
1826 // Remove this name from our lexical scope, and warn on it if we haven't
1828 IdResolver.RemoveDecl(D);
1829 auto ShadowI = ShadowingDecls.find(D);
1830 if (ShadowI != ShadowingDecls.end()) {
1831 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1832 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1833 << D << FD << FD->getParent();
1834 Diag(FD->getLocation(), diag::note_previous_declaration);
1836 ShadowingDecls.erase(ShadowI);
1841 /// Look for an Objective-C class in the translation unit.
1843 /// \param Id The name of the Objective-C class we're looking for. If
1844 /// typo-correction fixes this name, the Id will be updated
1845 /// to the fixed name.
1847 /// \param IdLoc The location of the name in the translation unit.
1849 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1850 /// if there is no class with the given name.
1852 /// \returns The declaration of the named Objective-C class, or NULL if the
1853 /// class could not be found.
1854 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1855 SourceLocation IdLoc,
1856 bool DoTypoCorrection) {
1857 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1858 // creation from this context.
1859 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1861 if (!IDecl && DoTypoCorrection) {
1862 // Perform typo correction at the given location, but only if we
1863 // find an Objective-C class name.
1864 if (TypoCorrection C = CorrectTypo(
1865 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1866 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1867 CTK_ErrorRecovery)) {
1868 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1869 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1870 Id = IDecl->getIdentifier();
1873 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1874 // This routine must always return a class definition, if any.
1875 if (Def && Def->getDefinition())
1876 Def = Def->getDefinition();
1880 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1881 /// from S, where a non-field would be declared. This routine copes
1882 /// with the difference between C and C++ scoping rules in structs and
1883 /// unions. For example, the following code is well-formed in C but
1884 /// ill-formed in C++:
1890 /// void test_S6() {
1895 /// For the declaration of BAR, this routine will return a different
1896 /// scope. The scope S will be the scope of the unnamed enumeration
1897 /// within S6. In C++, this routine will return the scope associated
1898 /// with S6, because the enumeration's scope is a transparent
1899 /// context but structures can contain non-field names. In C, this
1900 /// routine will return the translation unit scope, since the
1901 /// enumeration's scope is a transparent context and structures cannot
1902 /// contain non-field names.
1903 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1904 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1905 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1906 (S->isClassScope() && !getLangOpts().CPlusPlus))
1911 /// Looks up the declaration of "struct objc_super" and
1912 /// saves it for later use in building builtin declaration of
1913 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1914 /// pre-existing declaration exists no action takes place.
1915 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1916 IdentifierInfo *II) {
1917 if (!II->isStr("objc_msgSendSuper"))
1919 ASTContext &Context = ThisSema.Context;
1921 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1922 SourceLocation(), Sema::LookupTagName);
1923 ThisSema.LookupName(Result, S);
1924 if (Result.getResultKind() == LookupResult::Found)
1925 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1926 Context.setObjCSuperType(Context.getTagDeclType(TD));
1929 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1931 case ASTContext::GE_None:
1933 case ASTContext::GE_Missing_stdio:
1935 case ASTContext::GE_Missing_setjmp:
1937 case ASTContext::GE_Missing_ucontext:
1938 return "ucontext.h";
1940 llvm_unreachable("unhandled error kind");
1943 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1944 /// file scope. lazily create a decl for it. ForRedeclaration is true
1945 /// if we're creating this built-in in anticipation of redeclaring the
1947 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1948 Scope *S, bool ForRedeclaration,
1949 SourceLocation Loc) {
1950 LookupPredefedObjCSuperType(*this, S, II);
1952 ASTContext::GetBuiltinTypeError Error;
1953 QualType R = Context.GetBuiltinType(ID, Error);
1955 if (ForRedeclaration)
1956 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1957 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1961 if (!ForRedeclaration &&
1962 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1963 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1964 Diag(Loc, diag::ext_implicit_lib_function_decl)
1965 << Context.BuiltinInfo.getName(ID) << R;
1966 if (Context.BuiltinInfo.getHeaderName(ID) &&
1967 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1968 Diag(Loc, diag::note_include_header_or_declare)
1969 << Context.BuiltinInfo.getHeaderName(ID)
1970 << Context.BuiltinInfo.getName(ID);
1976 DeclContext *Parent = Context.getTranslationUnitDecl();
1977 if (getLangOpts().CPlusPlus) {
1978 LinkageSpecDecl *CLinkageDecl =
1979 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1980 LinkageSpecDecl::lang_c, false);
1981 CLinkageDecl->setImplicit();
1982 Parent->addDecl(CLinkageDecl);
1983 Parent = CLinkageDecl;
1986 FunctionDecl *New = FunctionDecl::Create(Context,
1988 Loc, Loc, II, R, /*TInfo=*/nullptr,
1991 R->isFunctionProtoType());
1994 // Create Decl objects for each parameter, adding them to the
1996 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1997 SmallVector<ParmVarDecl*, 16> Params;
1998 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2000 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2001 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2003 parm->setScopeInfo(0, i);
2004 Params.push_back(parm);
2006 New->setParams(Params);
2009 AddKnownFunctionAttributes(New);
2010 RegisterLocallyScopedExternCDecl(New, S);
2012 // TUScope is the translation-unit scope to insert this function into.
2013 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2014 // relate Scopes to DeclContexts, and probably eliminate CurContext
2015 // entirely, but we're not there yet.
2016 DeclContext *SavedContext = CurContext;
2017 CurContext = Parent;
2018 PushOnScopeChains(New, TUScope);
2019 CurContext = SavedContext;
2023 /// Typedef declarations don't have linkage, but they still denote the same
2024 /// entity if their types are the same.
2025 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2027 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2028 TypedefNameDecl *Decl,
2029 LookupResult &Previous) {
2030 // This is only interesting when modules are enabled.
2031 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2034 // Empty sets are uninteresting.
2035 if (Previous.empty())
2038 LookupResult::Filter Filter = Previous.makeFilter();
2039 while (Filter.hasNext()) {
2040 NamedDecl *Old = Filter.next();
2042 // Non-hidden declarations are never ignored.
2043 if (S.isVisible(Old))
2046 // Declarations of the same entity are not ignored, even if they have
2047 // different linkages.
2048 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2049 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2050 Decl->getUnderlyingType()))
2053 // If both declarations give a tag declaration a typedef name for linkage
2054 // purposes, then they declare the same entity.
2055 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2056 Decl->getAnonDeclWithTypedefName())
2066 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2068 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2069 OldType = OldTypedef->getUnderlyingType();
2071 OldType = Context.getTypeDeclType(Old);
2072 QualType NewType = New->getUnderlyingType();
2074 if (NewType->isVariablyModifiedType()) {
2075 // Must not redefine a typedef with a variably-modified type.
2076 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2077 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2079 if (Old->getLocation().isValid())
2080 notePreviousDefinition(Old, New->getLocation());
2081 New->setInvalidDecl();
2085 if (OldType != NewType &&
2086 !OldType->isDependentType() &&
2087 !NewType->isDependentType() &&
2088 !Context.hasSameType(OldType, NewType)) {
2089 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2090 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2091 << Kind << NewType << OldType;
2092 if (Old->getLocation().isValid())
2093 notePreviousDefinition(Old, New->getLocation());
2094 New->setInvalidDecl();
2100 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2101 /// same name and scope as a previous declaration 'Old'. Figure out
2102 /// how to resolve this situation, merging decls or emitting
2103 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2105 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2106 LookupResult &OldDecls) {
2107 // If the new decl is known invalid already, don't bother doing any
2109 if (New->isInvalidDecl()) return;
2111 // Allow multiple definitions for ObjC built-in typedefs.
2112 // FIXME: Verify the underlying types are equivalent!
2113 if (getLangOpts().ObjC1) {
2114 const IdentifierInfo *TypeID = New->getIdentifier();
2115 switch (TypeID->getLength()) {
2119 if (!TypeID->isStr("id"))
2121 QualType T = New->getUnderlyingType();
2122 if (!T->isPointerType())
2124 if (!T->isVoidPointerType()) {
2125 QualType PT = T->getAs<PointerType>()->getPointeeType();
2126 if (!PT->isStructureType())
2129 Context.setObjCIdRedefinitionType(T);
2130 // Install the built-in type for 'id', ignoring the current definition.
2131 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2135 if (!TypeID->isStr("Class"))
2137 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2138 // Install the built-in type for 'Class', ignoring the current definition.
2139 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2142 if (!TypeID->isStr("SEL"))
2144 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2145 // Install the built-in type for 'SEL', ignoring the current definition.
2146 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2149 // Fall through - the typedef name was not a builtin type.
2152 // Verify the old decl was also a type.
2153 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2155 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2156 << New->getDeclName();
2158 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2159 if (OldD->getLocation().isValid())
2160 notePreviousDefinition(OldD, New->getLocation());
2162 return New->setInvalidDecl();
2165 // If the old declaration is invalid, just give up here.
2166 if (Old->isInvalidDecl())
2167 return New->setInvalidDecl();
2169 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2170 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2171 auto *NewTag = New->getAnonDeclWithTypedefName();
2172 NamedDecl *Hidden = nullptr;
2173 if (OldTag && NewTag &&
2174 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2175 !hasVisibleDefinition(OldTag, &Hidden)) {
2176 // There is a definition of this tag, but it is not visible. Use it
2177 // instead of our tag.
2178 New->setTypeForDecl(OldTD->getTypeForDecl());
2179 if (OldTD->isModed())
2180 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2181 OldTD->getUnderlyingType());
2183 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2185 // Make the old tag definition visible.
2186 makeMergedDefinitionVisible(Hidden);
2188 // If this was an unscoped enumeration, yank all of its enumerators
2189 // out of the scope.
2190 if (isa<EnumDecl>(NewTag)) {
2191 Scope *EnumScope = getNonFieldDeclScope(S);
2192 for (auto *D : NewTag->decls()) {
2193 auto *ED = cast<EnumConstantDecl>(D);
2194 assert(EnumScope->isDeclScope(ED));
2195 EnumScope->RemoveDecl(ED);
2196 IdResolver.RemoveDecl(ED);
2197 ED->getLexicalDeclContext()->removeDecl(ED);
2203 // If the typedef types are not identical, reject them in all languages and
2204 // with any extensions enabled.
2205 if (isIncompatibleTypedef(Old, New))
2208 // The types match. Link up the redeclaration chain and merge attributes if
2209 // the old declaration was a typedef.
2210 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2211 New->setPreviousDecl(Typedef);
2212 mergeDeclAttributes(New, Old);
2215 if (getLangOpts().MicrosoftExt)
2218 if (getLangOpts().CPlusPlus) {
2219 // C++ [dcl.typedef]p2:
2220 // In a given non-class scope, a typedef specifier can be used to
2221 // redefine the name of any type declared in that scope to refer
2222 // to the type to which it already refers.
2223 if (!isa<CXXRecordDecl>(CurContext))
2226 // C++0x [dcl.typedef]p4:
2227 // In a given class scope, a typedef specifier can be used to redefine
2228 // any class-name declared in that scope that is not also a typedef-name
2229 // to refer to the type to which it already refers.
2231 // This wording came in via DR424, which was a correction to the
2232 // wording in DR56, which accidentally banned code like:
2235 // typedef struct A { } A;
2238 // in the C++03 standard. We implement the C++0x semantics, which
2239 // allow the above but disallow
2246 // since that was the intent of DR56.
2247 if (!isa<TypedefNameDecl>(Old))
2250 Diag(New->getLocation(), diag::err_redefinition)
2251 << New->getDeclName();
2252 notePreviousDefinition(Old, New->getLocation());
2253 return New->setInvalidDecl();
2256 // Modules always permit redefinition of typedefs, as does C11.
2257 if (getLangOpts().Modules || getLangOpts().C11)
2260 // If we have a redefinition of a typedef in C, emit a warning. This warning
2261 // is normally mapped to an error, but can be controlled with
2262 // -Wtypedef-redefinition. If either the original or the redefinition is
2263 // in a system header, don't emit this for compatibility with GCC.
2264 if (getDiagnostics().getSuppressSystemWarnings() &&
2265 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2266 (Old->isImplicit() ||
2267 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2268 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2271 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2272 << New->getDeclName();
2273 notePreviousDefinition(Old, New->getLocation());
2276 /// DeclhasAttr - returns true if decl Declaration already has the target
2278 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2279 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2280 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2281 for (const auto *i : D->attrs())
2282 if (i->getKind() == A->getKind()) {
2284 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2288 // FIXME: Don't hardcode this check
2289 if (OA && isa<OwnershipAttr>(i))
2290 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2297 static bool isAttributeTargetADefinition(Decl *D) {
2298 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2299 return VD->isThisDeclarationADefinition();
2300 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2301 return TD->isCompleteDefinition() || TD->isBeingDefined();
2305 /// Merge alignment attributes from \p Old to \p New, taking into account the
2306 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2308 /// \return \c true if any attributes were added to \p New.
2309 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2310 // Look for alignas attributes on Old, and pick out whichever attribute
2311 // specifies the strictest alignment requirement.
2312 AlignedAttr *OldAlignasAttr = nullptr;
2313 AlignedAttr *OldStrictestAlignAttr = nullptr;
2314 unsigned OldAlign = 0;
2315 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2316 // FIXME: We have no way of representing inherited dependent alignments
2318 // template<int A, int B> struct alignas(A) X;
2319 // template<int A, int B> struct alignas(B) X {};
2320 // For now, we just ignore any alignas attributes which are not on the
2321 // definition in such a case.
2322 if (I->isAlignmentDependent())
2328 unsigned Align = I->getAlignment(S.Context);
2329 if (Align > OldAlign) {
2331 OldStrictestAlignAttr = I;
2335 // Look for alignas attributes on New.
2336 AlignedAttr *NewAlignasAttr = nullptr;
2337 unsigned NewAlign = 0;
2338 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2339 if (I->isAlignmentDependent())
2345 unsigned Align = I->getAlignment(S.Context);
2346 if (Align > NewAlign)
2350 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2351 // Both declarations have 'alignas' attributes. We require them to match.
2352 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2353 // fall short. (If two declarations both have alignas, they must both match
2354 // every definition, and so must match each other if there is a definition.)
2356 // If either declaration only contains 'alignas(0)' specifiers, then it
2357 // specifies the natural alignment for the type.
2358 if (OldAlign == 0 || NewAlign == 0) {
2360 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2363 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2366 OldAlign = S.Context.getTypeAlign(Ty);
2368 NewAlign = S.Context.getTypeAlign(Ty);
2371 if (OldAlign != NewAlign) {
2372 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2373 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2374 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2375 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2379 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2380 // C++11 [dcl.align]p6:
2381 // if any declaration of an entity has an alignment-specifier,
2382 // every defining declaration of that entity shall specify an
2383 // equivalent alignment.
2385 // If the definition of an object does not have an alignment
2386 // specifier, any other declaration of that object shall also
2387 // have no alignment specifier.
2388 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2390 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2394 bool AnyAdded = false;
2396 // Ensure we have an attribute representing the strictest alignment.
2397 if (OldAlign > NewAlign) {
2398 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2399 Clone->setInherited(true);
2400 New->addAttr(Clone);
2404 // Ensure we have an alignas attribute if the old declaration had one.
2405 if (OldAlignasAttr && !NewAlignasAttr &&
2406 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2407 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2408 Clone->setInherited(true);
2409 New->addAttr(Clone);
2416 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2417 const InheritableAttr *Attr,
2418 Sema::AvailabilityMergeKind AMK) {
2419 // This function copies an attribute Attr from a previous declaration to the
2420 // new declaration D if the new declaration doesn't itself have that attribute
2421 // yet or if that attribute allows duplicates.
2422 // If you're adding a new attribute that requires logic different from
2423 // "use explicit attribute on decl if present, else use attribute from
2424 // previous decl", for example if the attribute needs to be consistent
2425 // between redeclarations, you need to call a custom merge function here.
2426 InheritableAttr *NewAttr = nullptr;
2427 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2428 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2429 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2430 AA->isImplicit(), AA->getIntroduced(),
2431 AA->getDeprecated(),
2432 AA->getObsoleted(), AA->getUnavailable(),
2433 AA->getMessage(), AA->getStrict(),
2434 AA->getReplacement(), AMK,
2435 AttrSpellingListIndex);
2436 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2437 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2438 AttrSpellingListIndex);
2439 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2440 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2441 AttrSpellingListIndex);
2442 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2443 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2444 AttrSpellingListIndex);
2445 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2446 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2447 AttrSpellingListIndex);
2448 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2449 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2450 FA->getFormatIdx(), FA->getFirstArg(),
2451 AttrSpellingListIndex);
2452 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2453 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2454 AttrSpellingListIndex);
2455 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2456 NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2457 AttrSpellingListIndex);
2458 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2459 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2460 AttrSpellingListIndex,
2461 IA->getSemanticSpelling());
2462 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2463 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2464 &S.Context.Idents.get(AA->getSpelling()),
2465 AttrSpellingListIndex);
2466 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2467 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2468 isa<CUDAGlobalAttr>(Attr))) {
2469 // CUDA target attributes are part of function signature for
2470 // overloading purposes and must not be merged.
2472 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2473 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2474 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2475 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2476 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2477 NewAttr = S.mergeInternalLinkageAttr(
2478 D, InternalLinkageA->getRange(),
2479 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2480 AttrSpellingListIndex);
2481 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2482 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2483 &S.Context.Idents.get(CommonA->getSpelling()),
2484 AttrSpellingListIndex);
2485 else if (isa<AlignedAttr>(Attr))
2486 // AlignedAttrs are handled separately, because we need to handle all
2487 // such attributes on a declaration at the same time.
2489 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2490 (AMK == Sema::AMK_Override ||
2491 AMK == Sema::AMK_ProtocolImplementation))
2493 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2494 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2496 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2497 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2500 NewAttr->setInherited(true);
2501 D->addAttr(NewAttr);
2502 if (isa<MSInheritanceAttr>(NewAttr))
2503 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2510 static const NamedDecl *getDefinition(const Decl *D) {
2511 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2512 return TD->getDefinition();
2513 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2514 const VarDecl *Def = VD->getDefinition();
2517 return VD->getActingDefinition();
2519 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2520 return FD->getDefinition();
2524 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2525 for (const auto *Attribute : D->attrs())
2526 if (Attribute->getKind() == Kind)
2531 /// checkNewAttributesAfterDef - If we already have a definition, check that
2532 /// there are no new attributes in this declaration.
2533 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2534 if (!New->hasAttrs())
2537 const NamedDecl *Def = getDefinition(Old);
2538 if (!Def || Def == New)
2541 AttrVec &NewAttributes = New->getAttrs();
2542 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2543 const Attr *NewAttribute = NewAttributes[I];
2545 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2546 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2547 Sema::SkipBodyInfo SkipBody;
2548 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2550 // If we're skipping this definition, drop the "alias" attribute.
2551 if (SkipBody.ShouldSkip) {
2552 NewAttributes.erase(NewAttributes.begin() + I);
2557 VarDecl *VD = cast<VarDecl>(New);
2558 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2559 VarDecl::TentativeDefinition
2560 ? diag::err_alias_after_tentative
2561 : diag::err_redefinition;
2562 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2563 if (Diag == diag::err_redefinition)
2564 S.notePreviousDefinition(Def, VD->getLocation());
2566 S.Diag(Def->getLocation(), diag::note_previous_definition);
2567 VD->setInvalidDecl();
2573 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2574 // Tentative definitions are only interesting for the alias check above.
2575 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2581 if (hasAttribute(Def, NewAttribute->getKind())) {
2583 continue; // regular attr merging will take care of validating this.
2586 if (isa<C11NoReturnAttr>(NewAttribute)) {
2587 // C's _Noreturn is allowed to be added to a function after it is defined.
2590 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2591 if (AA->isAlignas()) {
2592 // C++11 [dcl.align]p6:
2593 // if any declaration of an entity has an alignment-specifier,
2594 // every defining declaration of that entity shall specify an
2595 // equivalent alignment.
2597 // If the definition of an object does not have an alignment
2598 // specifier, any other declaration of that object shall also
2599 // have no alignment specifier.
2600 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2602 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2604 NewAttributes.erase(NewAttributes.begin() + I);
2610 S.Diag(NewAttribute->getLocation(),
2611 diag::warn_attribute_precede_definition);
2612 S.Diag(Def->getLocation(), diag::note_previous_definition);
2613 NewAttributes.erase(NewAttributes.begin() + I);
2618 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2619 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2620 AvailabilityMergeKind AMK) {
2621 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2622 UsedAttr *NewAttr = OldAttr->clone(Context);
2623 NewAttr->setInherited(true);
2624 New->addAttr(NewAttr);
2627 if (!Old->hasAttrs() && !New->hasAttrs())
2630 // Attributes declared post-definition are currently ignored.
2631 checkNewAttributesAfterDef(*this, New, Old);
2633 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2634 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2635 if (OldA->getLabel() != NewA->getLabel()) {
2636 // This redeclaration changes __asm__ label.
2637 Diag(New->getLocation(), diag::err_different_asm_label);
2638 Diag(OldA->getLocation(), diag::note_previous_declaration);
2640 } else if (Old->isUsed()) {
2641 // This redeclaration adds an __asm__ label to a declaration that has
2642 // already been ODR-used.
2643 Diag(New->getLocation(), diag::err_late_asm_label_name)
2644 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2648 // Re-declaration cannot add abi_tag's.
2649 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2650 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2651 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2652 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2653 NewTag) == OldAbiTagAttr->tags_end()) {
2654 Diag(NewAbiTagAttr->getLocation(),
2655 diag::err_new_abi_tag_on_redeclaration)
2657 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2661 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2662 Diag(Old->getLocation(), diag::note_previous_declaration);
2666 // This redeclaration adds a section attribute.
2667 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2668 if (auto *VD = dyn_cast<VarDecl>(New)) {
2669 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2670 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2671 Diag(Old->getLocation(), diag::note_previous_declaration);
2676 // Redeclaration adds code-seg attribute.
2677 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2678 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2679 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2680 Diag(New->getLocation(), diag::warn_mismatched_section)
2682 Diag(Old->getLocation(), diag::note_previous_declaration);
2685 if (!Old->hasAttrs())
2688 bool foundAny = New->hasAttrs();
2690 // Ensure that any moving of objects within the allocated map is done before
2692 if (!foundAny) New->setAttrs(AttrVec());
2694 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2695 // Ignore deprecated/unavailable/availability attributes if requested.
2696 AvailabilityMergeKind LocalAMK = AMK_None;
2697 if (isa<DeprecatedAttr>(I) ||
2698 isa<UnavailableAttr>(I) ||
2699 isa<AvailabilityAttr>(I)) {
2704 case AMK_Redeclaration:
2706 case AMK_ProtocolImplementation:
2713 if (isa<UsedAttr>(I))
2716 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2720 if (mergeAlignedAttrs(*this, New, Old))
2723 if (!foundAny) New->dropAttrs();
2726 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2728 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2729 const ParmVarDecl *oldDecl,
2731 // C++11 [dcl.attr.depend]p2:
2732 // The first declaration of a function shall specify the
2733 // carries_dependency attribute for its declarator-id if any declaration
2734 // of the function specifies the carries_dependency attribute.
2735 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2736 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2737 S.Diag(CDA->getLocation(),
2738 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2739 // Find the first declaration of the parameter.
2740 // FIXME: Should we build redeclaration chains for function parameters?
2741 const FunctionDecl *FirstFD =
2742 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2743 const ParmVarDecl *FirstVD =
2744 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2745 S.Diag(FirstVD->getLocation(),
2746 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2749 if (!oldDecl->hasAttrs())
2752 bool foundAny = newDecl->hasAttrs();
2754 // Ensure that any moving of objects within the allocated map is
2755 // done before we process them.
2756 if (!foundAny) newDecl->setAttrs(AttrVec());
2758 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2759 if (!DeclHasAttr(newDecl, I)) {
2760 InheritableAttr *newAttr =
2761 cast<InheritableParamAttr>(I->clone(S.Context));
2762 newAttr->setInherited(true);
2763 newDecl->addAttr(newAttr);
2768 if (!foundAny) newDecl->dropAttrs();
2771 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2772 const ParmVarDecl *OldParam,
2774 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2775 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2776 if (*Oldnullability != *Newnullability) {
2777 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2778 << DiagNullabilityKind(
2780 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2782 << DiagNullabilityKind(
2784 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2786 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2789 QualType NewT = NewParam->getType();
2790 NewT = S.Context.getAttributedType(
2791 AttributedType::getNullabilityAttrKind(*Oldnullability),
2793 NewParam->setType(NewT);
2800 /// Used in MergeFunctionDecl to keep track of function parameters in
2802 struct GNUCompatibleParamWarning {
2803 ParmVarDecl *OldParm;
2804 ParmVarDecl *NewParm;
2805 QualType PromotedType;
2808 } // end anonymous namespace
2810 /// getSpecialMember - get the special member enum for a method.
2811 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2812 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2813 if (Ctor->isDefaultConstructor())
2814 return Sema::CXXDefaultConstructor;
2816 if (Ctor->isCopyConstructor())
2817 return Sema::CXXCopyConstructor;
2819 if (Ctor->isMoveConstructor())
2820 return Sema::CXXMoveConstructor;
2821 } else if (isa<CXXDestructorDecl>(MD)) {
2822 return Sema::CXXDestructor;
2823 } else if (MD->isCopyAssignmentOperator()) {
2824 return Sema::CXXCopyAssignment;
2825 } else if (MD->isMoveAssignmentOperator()) {
2826 return Sema::CXXMoveAssignment;
2829 return Sema::CXXInvalid;
2832 // Determine whether the previous declaration was a definition, implicit
2833 // declaration, or a declaration.
2834 template <typename T>
2835 static std::pair<diag::kind, SourceLocation>
2836 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2837 diag::kind PrevDiag;
2838 SourceLocation OldLocation = Old->getLocation();
2839 if (Old->isThisDeclarationADefinition())
2840 PrevDiag = diag::note_previous_definition;
2841 else if (Old->isImplicit()) {
2842 PrevDiag = diag::note_previous_implicit_declaration;
2843 if (OldLocation.isInvalid())
2844 OldLocation = New->getLocation();
2846 PrevDiag = diag::note_previous_declaration;
2847 return std::make_pair(PrevDiag, OldLocation);
2850 /// canRedefineFunction - checks if a function can be redefined. Currently,
2851 /// only extern inline functions can be redefined, and even then only in
2853 static bool canRedefineFunction(const FunctionDecl *FD,
2854 const LangOptions& LangOpts) {
2855 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2856 !LangOpts.CPlusPlus &&
2857 FD->isInlineSpecified() &&
2858 FD->getStorageClass() == SC_Extern);
2861 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2862 const AttributedType *AT = T->getAs<AttributedType>();
2863 while (AT && !AT->isCallingConv())
2864 AT = AT->getModifiedType()->getAs<AttributedType>();
2868 template <typename T>
2869 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2870 const DeclContext *DC = Old->getDeclContext();
2874 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2875 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2877 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2882 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2883 static bool isExternC(VarTemplateDecl *) { return false; }
2885 /// Check whether a redeclaration of an entity introduced by a
2886 /// using-declaration is valid, given that we know it's not an overload
2887 /// (nor a hidden tag declaration).
2888 template<typename ExpectedDecl>
2889 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2890 ExpectedDecl *New) {
2891 // C++11 [basic.scope.declarative]p4:
2892 // Given a set of declarations in a single declarative region, each of
2893 // which specifies the same unqualified name,
2894 // -- they shall all refer to the same entity, or all refer to functions
2895 // and function templates; or
2896 // -- exactly one declaration shall declare a class name or enumeration
2897 // name that is not a typedef name and the other declarations shall all
2898 // refer to the same variable or enumerator, or all refer to functions
2899 // and function templates; in this case the class name or enumeration
2900 // name is hidden (3.3.10).
2902 // C++11 [namespace.udecl]p14:
2903 // If a function declaration in namespace scope or block scope has the
2904 // same name and the same parameter-type-list as a function introduced
2905 // by a using-declaration, and the declarations do not declare the same
2906 // function, the program is ill-formed.
2908 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2910 !Old->getDeclContext()->getRedeclContext()->Equals(
2911 New->getDeclContext()->getRedeclContext()) &&
2912 !(isExternC(Old) && isExternC(New)))
2916 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2917 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2918 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2924 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2925 const FunctionDecl *B) {
2926 assert(A->getNumParams() == B->getNumParams());
2928 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2929 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2930 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2933 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2936 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2939 /// If necessary, adjust the semantic declaration context for a qualified
2940 /// declaration to name the correct inline namespace within the qualifier.
2941 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2942 DeclaratorDecl *OldD) {
2943 // The only case where we need to update the DeclContext is when
2944 // redeclaration lookup for a qualified name finds a declaration
2945 // in an inline namespace within the context named by the qualifier:
2947 // inline namespace N { int f(); }
2948 // int ::f(); // Sema DC needs adjusting from :: to N::.
2950 // For unqualified declarations, the semantic context *can* change
2951 // along the redeclaration chain (for local extern declarations,
2952 // extern "C" declarations, and friend declarations in particular).
2953 if (!NewD->getQualifier())
2956 // NewD is probably already in the right context.
2957 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2958 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2959 if (NamedDC->Equals(SemaDC))
2962 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2963 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2964 "unexpected context for redeclaration");
2966 auto *LexDC = NewD->getLexicalDeclContext();
2967 auto FixSemaDC = [=](NamedDecl *D) {
2970 D->setDeclContext(SemaDC);
2971 D->setLexicalDeclContext(LexDC);
2975 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2976 FixSemaDC(FD->getDescribedFunctionTemplate());
2977 else if (auto *VD = dyn_cast<VarDecl>(NewD))
2978 FixSemaDC(VD->getDescribedVarTemplate());
2981 /// MergeFunctionDecl - We just parsed a function 'New' from
2982 /// declarator D which has the same name and scope as a previous
2983 /// declaration 'Old'. Figure out how to resolve this situation,
2984 /// merging decls or emitting diagnostics as appropriate.
2986 /// In C++, New and Old must be declarations that are not
2987 /// overloaded. Use IsOverload to determine whether New and Old are
2988 /// overloaded, and to select the Old declaration that New should be
2991 /// Returns true if there was an error, false otherwise.
2992 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2993 Scope *S, bool MergeTypeWithOld) {
2994 // Verify the old decl was also a function.
2995 FunctionDecl *Old = OldD->getAsFunction();
2997 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2998 if (New->getFriendObjectKind()) {
2999 Diag(New->getLocation(), diag::err_using_decl_friend);
3000 Diag(Shadow->getTargetDecl()->getLocation(),
3001 diag::note_using_decl_target);
3002 Diag(Shadow->getUsingDecl()->getLocation(),
3003 diag::note_using_decl) << 0;
3007 // Check whether the two declarations might declare the same function.
3008 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3010 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3012 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3013 << New->getDeclName();
3014 notePreviousDefinition(OldD, New->getLocation());
3019 // If the old declaration is invalid, just give up here.
3020 if (Old->isInvalidDecl())
3023 // Disallow redeclaration of some builtins.
3024 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3025 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3026 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3027 << Old << Old->getType();
3031 diag::kind PrevDiag;
3032 SourceLocation OldLocation;
3033 std::tie(PrevDiag, OldLocation) =
3034 getNoteDiagForInvalidRedeclaration(Old, New);
3036 // Don't complain about this if we're in GNU89 mode and the old function
3037 // is an extern inline function.
3038 // Don't complain about specializations. They are not supposed to have
3040 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3041 New->getStorageClass() == SC_Static &&
3042 Old->hasExternalFormalLinkage() &&
3043 !New->getTemplateSpecializationInfo() &&
3044 !canRedefineFunction(Old, getLangOpts())) {
3045 if (getLangOpts().MicrosoftExt) {
3046 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3047 Diag(OldLocation, PrevDiag);
3049 Diag(New->getLocation(), diag::err_static_non_static) << New;
3050 Diag(OldLocation, PrevDiag);
3055 if (New->hasAttr<InternalLinkageAttr>() &&
3056 !Old->hasAttr<InternalLinkageAttr>()) {
3057 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3058 << New->getDeclName();
3059 notePreviousDefinition(Old, New->getLocation());
3060 New->dropAttr<InternalLinkageAttr>();
3063 if (CheckRedeclarationModuleOwnership(New, Old))
3066 if (!getLangOpts().CPlusPlus) {
3067 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3068 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3069 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3072 // Try our best to find a decl that actually has the overloadable
3073 // attribute for the note. In most cases (e.g. programs with only one
3074 // broken declaration/definition), this won't matter.
3076 // FIXME: We could do this if we juggled some extra state in
3077 // OverloadableAttr, rather than just removing it.
3078 const Decl *DiagOld = Old;
3080 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3081 const auto *A = D->getAttr<OverloadableAttr>();
3082 return A && !A->isImplicit();
3084 // If we've implicitly added *all* of the overloadable attrs to this
3085 // chain, emitting a "previous redecl" note is pointless.
3086 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3090 Diag(DiagOld->getLocation(),
3091 diag::note_attribute_overloadable_prev_overload)
3095 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3097 New->dropAttr<OverloadableAttr>();
3101 // If a function is first declared with a calling convention, but is later
3102 // declared or defined without one, all following decls assume the calling
3103 // convention of the first.
3105 // It's OK if a function is first declared without a calling convention,
3106 // but is later declared or defined with the default calling convention.
3108 // To test if either decl has an explicit calling convention, we look for
3109 // AttributedType sugar nodes on the type as written. If they are missing or
3110 // were canonicalized away, we assume the calling convention was implicit.
3112 // Note also that we DO NOT return at this point, because we still have
3113 // other tests to run.
3114 QualType OldQType = Context.getCanonicalType(Old->getType());
3115 QualType NewQType = Context.getCanonicalType(New->getType());
3116 const FunctionType *OldType = cast<FunctionType>(OldQType);
3117 const FunctionType *NewType = cast<FunctionType>(NewQType);
3118 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3119 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3120 bool RequiresAdjustment = false;
3122 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3123 FunctionDecl *First = Old->getFirstDecl();
3124 const FunctionType *FT =
3125 First->getType().getCanonicalType()->castAs<FunctionType>();
3126 FunctionType::ExtInfo FI = FT->getExtInfo();
3127 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3128 if (!NewCCExplicit) {
3129 // Inherit the CC from the previous declaration if it was specified
3130 // there but not here.
3131 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3132 RequiresAdjustment = true;
3134 // Calling conventions aren't compatible, so complain.
3135 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3136 Diag(New->getLocation(), diag::err_cconv_change)
3137 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3139 << (!FirstCCExplicit ? "" :
3140 FunctionType::getNameForCallConv(FI.getCC()));
3142 // Put the note on the first decl, since it is the one that matters.
3143 Diag(First->getLocation(), diag::note_previous_declaration);
3148 // FIXME: diagnose the other way around?
3149 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3150 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3151 RequiresAdjustment = true;
3154 // Merge regparm attribute.
3155 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3156 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3157 if (NewTypeInfo.getHasRegParm()) {
3158 Diag(New->getLocation(), diag::err_regparm_mismatch)
3159 << NewType->getRegParmType()
3160 << OldType->getRegParmType();
3161 Diag(OldLocation, diag::note_previous_declaration);
3165 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3166 RequiresAdjustment = true;
3169 // Merge ns_returns_retained attribute.
3170 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3171 if (NewTypeInfo.getProducesResult()) {
3172 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3173 << "'ns_returns_retained'";
3174 Diag(OldLocation, diag::note_previous_declaration);
3178 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3179 RequiresAdjustment = true;
3182 if (OldTypeInfo.getNoCallerSavedRegs() !=
3183 NewTypeInfo.getNoCallerSavedRegs()) {
3184 if (NewTypeInfo.getNoCallerSavedRegs()) {
3185 AnyX86NoCallerSavedRegistersAttr *Attr =
3186 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3187 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3188 Diag(OldLocation, diag::note_previous_declaration);
3192 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3193 RequiresAdjustment = true;
3196 if (RequiresAdjustment) {
3197 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3198 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3199 New->setType(QualType(AdjustedType, 0));
3200 NewQType = Context.getCanonicalType(New->getType());
3201 NewType = cast<FunctionType>(NewQType);
3204 // If this redeclaration makes the function inline, we may need to add it to
3205 // UndefinedButUsed.
3206 if (!Old->isInlined() && New->isInlined() &&
3207 !New->hasAttr<GNUInlineAttr>() &&
3208 !getLangOpts().GNUInline &&
3209 Old->isUsed(false) &&
3210 !Old->isDefined() && !New->isThisDeclarationADefinition())
3211 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3214 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3216 if (New->hasAttr<GNUInlineAttr>() &&
3217 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3218 UndefinedButUsed.erase(Old->getCanonicalDecl());
3221 // If pass_object_size params don't match up perfectly, this isn't a valid
3223 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3224 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3225 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3226 << New->getDeclName();
3227 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3231 if (getLangOpts().CPlusPlus) {
3232 // C++1z [over.load]p2
3233 // Certain function declarations cannot be overloaded:
3234 // -- Function declarations that differ only in the return type,
3235 // the exception specification, or both cannot be overloaded.
3237 // Check the exception specifications match. This may recompute the type of
3238 // both Old and New if it resolved exception specifications, so grab the
3239 // types again after this. Because this updates the type, we do this before
3240 // any of the other checks below, which may update the "de facto" NewQType
3241 // but do not necessarily update the type of New.
3242 if (CheckEquivalentExceptionSpec(Old, New))
3244 OldQType = Context.getCanonicalType(Old->getType());
3245 NewQType = Context.getCanonicalType(New->getType());
3247 // Go back to the type source info to compare the declared return types,
3248 // per C++1y [dcl.type.auto]p13:
3249 // Redeclarations or specializations of a function or function template
3250 // with a declared return type that uses a placeholder type shall also
3251 // use that placeholder, not a deduced type.
3252 QualType OldDeclaredReturnType =
3253 (Old->getTypeSourceInfo()
3254 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3255 : OldType)->getReturnType();
3256 QualType NewDeclaredReturnType =
3257 (New->getTypeSourceInfo()
3258 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3259 : NewType)->getReturnType();
3260 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3261 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3262 New->isLocalExternDecl())) {
3264 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3265 OldDeclaredReturnType->isObjCObjectPointerType())
3266 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3267 if (ResQT.isNull()) {
3268 if (New->isCXXClassMember() && New->isOutOfLine())
3269 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3270 << New << New->getReturnTypeSourceRange();
3272 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3273 << New->getReturnTypeSourceRange();
3274 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3275 << Old->getReturnTypeSourceRange();
3282 QualType OldReturnType = OldType->getReturnType();
3283 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3284 if (OldReturnType != NewReturnType) {
3285 // If this function has a deduced return type and has already been
3286 // defined, copy the deduced value from the old declaration.
3287 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3288 if (OldAT && OldAT->isDeduced()) {
3290 SubstAutoType(New->getType(),
3291 OldAT->isDependentType() ? Context.DependentTy
3292 : OldAT->getDeducedType()));
3293 NewQType = Context.getCanonicalType(
3294 SubstAutoType(NewQType,
3295 OldAT->isDependentType() ? Context.DependentTy
3296 : OldAT->getDeducedType()));
3300 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3301 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3302 if (OldMethod && NewMethod) {
3303 // Preserve triviality.
3304 NewMethod->setTrivial(OldMethod->isTrivial());
3306 // MSVC allows explicit template specialization at class scope:
3307 // 2 CXXMethodDecls referring to the same function will be injected.
3308 // We don't want a redeclaration error.
3309 bool IsClassScopeExplicitSpecialization =
3310 OldMethod->isFunctionTemplateSpecialization() &&
3311 NewMethod->isFunctionTemplateSpecialization();
3312 bool isFriend = NewMethod->getFriendObjectKind();
3314 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3315 !IsClassScopeExplicitSpecialization) {
3316 // -- Member function declarations with the same name and the
3317 // same parameter types cannot be overloaded if any of them
3318 // is a static member function declaration.
3319 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3320 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3321 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3325 // C++ [class.mem]p1:
3326 // [...] A member shall not be declared twice in the
3327 // member-specification, except that a nested class or member
3328 // class template can be declared and then later defined.
3329 if (!inTemplateInstantiation()) {
3331 if (isa<CXXConstructorDecl>(OldMethod))
3332 NewDiag = diag::err_constructor_redeclared;
3333 else if (isa<CXXDestructorDecl>(NewMethod))
3334 NewDiag = diag::err_destructor_redeclared;
3335 else if (isa<CXXConversionDecl>(NewMethod))
3336 NewDiag = diag::err_conv_function_redeclared;
3338 NewDiag = diag::err_member_redeclared;
3340 Diag(New->getLocation(), NewDiag);
3342 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3343 << New << New->getType();
3345 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3348 // Complain if this is an explicit declaration of a special
3349 // member that was initially declared implicitly.
3351 // As an exception, it's okay to befriend such methods in order
3352 // to permit the implicit constructor/destructor/operator calls.
3353 } else if (OldMethod->isImplicit()) {
3355 NewMethod->setImplicit();
3357 Diag(NewMethod->getLocation(),
3358 diag::err_definition_of_implicitly_declared_member)
3359 << New << getSpecialMember(OldMethod);
3362 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3363 Diag(NewMethod->getLocation(),
3364 diag::err_definition_of_explicitly_defaulted_member)
3365 << getSpecialMember(OldMethod);
3370 // C++11 [dcl.attr.noreturn]p1:
3371 // The first declaration of a function shall specify the noreturn
3372 // attribute if any declaration of that function specifies the noreturn
3374 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3375 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3376 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3377 Diag(Old->getFirstDecl()->getLocation(),
3378 diag::note_noreturn_missing_first_decl);
3381 // C++11 [dcl.attr.depend]p2:
3382 // The first declaration of a function shall specify the
3383 // carries_dependency attribute for its declarator-id if any declaration
3384 // of the function specifies the carries_dependency attribute.
3385 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3386 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3387 Diag(CDA->getLocation(),
3388 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3389 Diag(Old->getFirstDecl()->getLocation(),
3390 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3394 // All declarations for a function shall agree exactly in both the
3395 // return type and the parameter-type-list.
3396 // We also want to respect all the extended bits except noreturn.
3398 // noreturn should now match unless the old type info didn't have it.
3399 QualType OldQTypeForComparison = OldQType;
3400 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3401 auto *OldType = OldQType->castAs<FunctionProtoType>();
3402 const FunctionType *OldTypeForComparison
3403 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3404 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3405 assert(OldQTypeForComparison.isCanonical());
3408 if (haveIncompatibleLanguageLinkages(Old, New)) {
3409 // As a special case, retain the language linkage from previous
3410 // declarations of a friend function as an extension.
3412 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3413 // and is useful because there's otherwise no way to specify language
3414 // linkage within class scope.
3416 // Check cautiously as the friend object kind isn't yet complete.
3417 if (New->getFriendObjectKind() != Decl::FOK_None) {
3418 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3419 Diag(OldLocation, PrevDiag);
3421 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3422 Diag(OldLocation, PrevDiag);
3427 if (OldQTypeForComparison == NewQType)
3428 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3430 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3431 New->isLocalExternDecl()) {
3432 // It's OK if we couldn't merge types for a local function declaraton
3433 // if either the old or new type is dependent. We'll merge the types
3434 // when we instantiate the function.
3438 // Fall through for conflicting redeclarations and redefinitions.
3441 // C: Function types need to be compatible, not identical. This handles
3442 // duplicate function decls like "void f(int); void f(enum X);" properly.
3443 if (!getLangOpts().CPlusPlus &&
3444 Context.typesAreCompatible(OldQType, NewQType)) {
3445 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3446 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3447 const FunctionProtoType *OldProto = nullptr;
3448 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3449 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3450 // The old declaration provided a function prototype, but the
3451 // new declaration does not. Merge in the prototype.
3452 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3453 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3455 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3456 OldProto->getExtProtoInfo());
3457 New->setType(NewQType);
3458 New->setHasInheritedPrototype();
3460 // Synthesize parameters with the same types.
3461 SmallVector<ParmVarDecl*, 16> Params;
3462 for (const auto &ParamType : OldProto->param_types()) {
3463 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3464 SourceLocation(), nullptr,
3465 ParamType, /*TInfo=*/nullptr,
3467 Param->setScopeInfo(0, Params.size());
3468 Param->setImplicit();
3469 Params.push_back(Param);
3472 New->setParams(Params);
3475 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3478 // GNU C permits a K&R definition to follow a prototype declaration
3479 // if the declared types of the parameters in the K&R definition
3480 // match the types in the prototype declaration, even when the
3481 // promoted types of the parameters from the K&R definition differ
3482 // from the types in the prototype. GCC then keeps the types from
3485 // If a variadic prototype is followed by a non-variadic K&R definition,
3486 // the K&R definition becomes variadic. This is sort of an edge case, but
3487 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3489 if (!getLangOpts().CPlusPlus &&
3490 Old->hasPrototype() && !New->hasPrototype() &&
3491 New->getType()->getAs<FunctionProtoType>() &&
3492 Old->getNumParams() == New->getNumParams()) {
3493 SmallVector<QualType, 16> ArgTypes;
3494 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3495 const FunctionProtoType *OldProto
3496 = Old->getType()->getAs<FunctionProtoType>();
3497 const FunctionProtoType *NewProto
3498 = New->getType()->getAs<FunctionProtoType>();
3500 // Determine whether this is the GNU C extension.
3501 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3502 NewProto->getReturnType());
3503 bool LooseCompatible = !MergedReturn.isNull();
3504 for (unsigned Idx = 0, End = Old->getNumParams();
3505 LooseCompatible && Idx != End; ++Idx) {
3506 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3507 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3508 if (Context.typesAreCompatible(OldParm->getType(),
3509 NewProto->getParamType(Idx))) {
3510 ArgTypes.push_back(NewParm->getType());
3511 } else if (Context.typesAreCompatible(OldParm->getType(),
3513 /*CompareUnqualified=*/true)) {
3514 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3515 NewProto->getParamType(Idx) };
3516 Warnings.push_back(Warn);
3517 ArgTypes.push_back(NewParm->getType());
3519 LooseCompatible = false;
3522 if (LooseCompatible) {
3523 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3524 Diag(Warnings[Warn].NewParm->getLocation(),
3525 diag::ext_param_promoted_not_compatible_with_prototype)
3526 << Warnings[Warn].PromotedType
3527 << Warnings[Warn].OldParm->getType();
3528 if (Warnings[Warn].OldParm->getLocation().isValid())
3529 Diag(Warnings[Warn].OldParm->getLocation(),
3530 diag::note_previous_declaration);
3533 if (MergeTypeWithOld)
3534 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3535 OldProto->getExtProtoInfo()));
3536 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3539 // Fall through to diagnose conflicting types.
3542 // A function that has already been declared has been redeclared or
3543 // defined with a different type; show an appropriate diagnostic.
3545 // If the previous declaration was an implicitly-generated builtin
3546 // declaration, then at the very least we should use a specialized note.
3548 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3549 // If it's actually a library-defined builtin function like 'malloc'
3550 // or 'printf', just warn about the incompatible redeclaration.
3551 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3552 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3553 Diag(OldLocation, diag::note_previous_builtin_declaration)
3554 << Old << Old->getType();
3556 // If this is a global redeclaration, just forget hereafter
3557 // about the "builtin-ness" of the function.
3559 // Doing this for local extern declarations is problematic. If
3560 // the builtin declaration remains visible, a second invalid
3561 // local declaration will produce a hard error; if it doesn't
3562 // remain visible, a single bogus local redeclaration (which is
3563 // actually only a warning) could break all the downstream code.
3564 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3565 New->getIdentifier()->revertBuiltin();
3570 PrevDiag = diag::note_previous_builtin_declaration;
3573 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3574 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3578 /// Completes the merge of two function declarations that are
3579 /// known to be compatible.
3581 /// This routine handles the merging of attributes and other
3582 /// properties of function declarations from the old declaration to
3583 /// the new declaration, once we know that New is in fact a
3584 /// redeclaration of Old.
3587 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3588 Scope *S, bool MergeTypeWithOld) {
3589 // Merge the attributes
3590 mergeDeclAttributes(New, Old);
3592 // Merge "pure" flag.
3596 // Merge "used" flag.
3597 if (Old->getMostRecentDecl()->isUsed(false))
3600 // Merge attributes from the parameters. These can mismatch with K&R
3602 if (New->getNumParams() == Old->getNumParams())
3603 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3604 ParmVarDecl *NewParam = New->getParamDecl(i);
3605 ParmVarDecl *OldParam = Old->getParamDecl(i);
3606 mergeParamDeclAttributes(NewParam, OldParam, *this);
3607 mergeParamDeclTypes(NewParam, OldParam, *this);
3610 if (getLangOpts().CPlusPlus)
3611 return MergeCXXFunctionDecl(New, Old, S);
3613 // Merge the function types so the we get the composite types for the return
3614 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3616 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3617 if (!Merged.isNull() && MergeTypeWithOld)
3618 New->setType(Merged);
3623 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3624 ObjCMethodDecl *oldMethod) {
3625 // Merge the attributes, including deprecated/unavailable
3626 AvailabilityMergeKind MergeKind =
3627 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3628 ? AMK_ProtocolImplementation
3629 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3632 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3634 // Merge attributes from the parameters.
3635 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3636 oe = oldMethod->param_end();
3637 for (ObjCMethodDecl::param_iterator
3638 ni = newMethod->param_begin(), ne = newMethod->param_end();
3639 ni != ne && oi != oe; ++ni, ++oi)
3640 mergeParamDeclAttributes(*ni, *oi, *this);
3642 CheckObjCMethodOverride(newMethod, oldMethod);
3645 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3646 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3648 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3649 ? diag::err_redefinition_different_type
3650 : diag::err_redeclaration_different_type)
3651 << New->getDeclName() << New->getType() << Old->getType();
3653 diag::kind PrevDiag;
3654 SourceLocation OldLocation;
3655 std::tie(PrevDiag, OldLocation)
3656 = getNoteDiagForInvalidRedeclaration(Old, New);
3657 S.Diag(OldLocation, PrevDiag);
3658 New->setInvalidDecl();
3661 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3662 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3663 /// emitting diagnostics as appropriate.
3665 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3666 /// to here in AddInitializerToDecl. We can't check them before the initializer
3668 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3669 bool MergeTypeWithOld) {
3670 if (New->isInvalidDecl() || Old->isInvalidDecl())
3674 if (getLangOpts().CPlusPlus) {
3675 if (New->getType()->isUndeducedType()) {
3676 // We don't know what the new type is until the initializer is attached.
3678 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3679 // These could still be something that needs exception specs checked.
3680 return MergeVarDeclExceptionSpecs(New, Old);
3682 // C++ [basic.link]p10:
3683 // [...] the types specified by all declarations referring to a given
3684 // object or function shall be identical, except that declarations for an
3685 // array object can specify array types that differ by the presence or
3686 // absence of a major array bound (8.3.4).
3687 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3688 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3689 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3691 // We are merging a variable declaration New into Old. If it has an array
3692 // bound, and that bound differs from Old's bound, we should diagnose the
3694 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3695 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3696 PrevVD = PrevVD->getPreviousDecl()) {
3697 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3698 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3701 if (!Context.hasSameType(NewArray, PrevVDTy))
3702 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3706 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3707 if (Context.hasSameType(OldArray->getElementType(),
3708 NewArray->getElementType()))
3709 MergedT = New->getType();
3711 // FIXME: Check visibility. New is hidden but has a complete type. If New
3712 // has no array bound, it should not inherit one from Old, if Old is not
3714 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3715 if (Context.hasSameType(OldArray->getElementType(),
3716 NewArray->getElementType()))
3717 MergedT = Old->getType();
3720 else if (New->getType()->isObjCObjectPointerType() &&
3721 Old->getType()->isObjCObjectPointerType()) {
3722 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3727 // All declarations that refer to the same object or function shall have
3729 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3731 if (MergedT.isNull()) {
3732 // It's OK if we couldn't merge types if either type is dependent, for a
3733 // block-scope variable. In other cases (static data members of class
3734 // templates, variable templates, ...), we require the types to be
3736 // FIXME: The C++ standard doesn't say anything about this.
3737 if ((New->getType()->isDependentType() ||
3738 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3739 // If the old type was dependent, we can't merge with it, so the new type
3740 // becomes dependent for now. We'll reproduce the original type when we
3741 // instantiate the TypeSourceInfo for the variable.
3742 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3743 New->setType(Context.DependentTy);
3746 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3749 // Don't actually update the type on the new declaration if the old
3750 // declaration was an extern declaration in a different scope.
3751 if (MergeTypeWithOld)
3752 New->setType(MergedT);
3755 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3756 LookupResult &Previous) {
3758 // For an identifier with internal or external linkage declared
3759 // in a scope in which a prior declaration of that identifier is
3760 // visible, if the prior declaration specifies internal or
3761 // external linkage, the type of the identifier at the later
3762 // declaration becomes the composite type.
3764 // If the variable isn't visible, we do not merge with its type.
3765 if (Previous.isShadowed())
3768 if (S.getLangOpts().CPlusPlus) {
3769 // C++11 [dcl.array]p3:
3770 // If there is a preceding declaration of the entity in the same
3771 // scope in which the bound was specified, an omitted array bound
3772 // is taken to be the same as in that earlier declaration.
3773 return NewVD->isPreviousDeclInSameBlockScope() ||
3774 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3775 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3777 // If the old declaration was function-local, don't merge with its
3778 // type unless we're in the same function.
3779 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3780 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3784 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3785 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3786 /// situation, merging decls or emitting diagnostics as appropriate.
3788 /// Tentative definition rules (C99 6.9.2p2) are checked by
3789 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3790 /// definitions here, since the initializer hasn't been attached.
3792 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3793 // If the new decl is already invalid, don't do any other checking.
3794 if (New->isInvalidDecl())
3797 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3800 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3802 // Verify the old decl was also a variable or variable template.
3803 VarDecl *Old = nullptr;
3804 VarTemplateDecl *OldTemplate = nullptr;
3805 if (Previous.isSingleResult()) {
3807 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3808 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3811 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3812 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3813 return New->setInvalidDecl();
3815 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3818 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3819 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3820 return New->setInvalidDecl();
3824 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3825 << New->getDeclName();
3826 notePreviousDefinition(Previous.getRepresentativeDecl(),
3827 New->getLocation());
3828 return New->setInvalidDecl();
3831 // Ensure the template parameters are compatible.
3833 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3834 OldTemplate->getTemplateParameters(),
3835 /*Complain=*/true, TPL_TemplateMatch))
3836 return New->setInvalidDecl();
3838 // C++ [class.mem]p1:
3839 // A member shall not be declared twice in the member-specification [...]
3841 // Here, we need only consider static data members.
3842 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3843 Diag(New->getLocation(), diag::err_duplicate_member)
3844 << New->getIdentifier();
3845 Diag(Old->getLocation(), diag::note_previous_declaration);
3846 New->setInvalidDecl();
3849 mergeDeclAttributes(New, Old);
3850 // Warn if an already-declared variable is made a weak_import in a subsequent
3852 if (New->hasAttr<WeakImportAttr>() &&
3853 Old->getStorageClass() == SC_None &&
3854 !Old->hasAttr<WeakImportAttr>()) {
3855 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3856 notePreviousDefinition(Old, New->getLocation());
3857 // Remove weak_import attribute on new declaration.
3858 New->dropAttr<WeakImportAttr>();
3861 if (New->hasAttr<InternalLinkageAttr>() &&
3862 !Old->hasAttr<InternalLinkageAttr>()) {
3863 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3864 << New->getDeclName();
3865 notePreviousDefinition(Old, New->getLocation());
3866 New->dropAttr<InternalLinkageAttr>();
3870 VarDecl *MostRecent = Old->getMostRecentDecl();
3871 if (MostRecent != Old) {
3872 MergeVarDeclTypes(New, MostRecent,
3873 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3874 if (New->isInvalidDecl())
3878 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3879 if (New->isInvalidDecl())
3882 diag::kind PrevDiag;
3883 SourceLocation OldLocation;
3884 std::tie(PrevDiag, OldLocation) =
3885 getNoteDiagForInvalidRedeclaration(Old, New);
3887 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3888 if (New->getStorageClass() == SC_Static &&
3889 !New->isStaticDataMember() &&
3890 Old->hasExternalFormalLinkage()) {
3891 if (getLangOpts().MicrosoftExt) {
3892 Diag(New->getLocation(), diag::ext_static_non_static)
3893 << New->getDeclName();
3894 Diag(OldLocation, PrevDiag);
3896 Diag(New->getLocation(), diag::err_static_non_static)
3897 << New->getDeclName();
3898 Diag(OldLocation, PrevDiag);
3899 return New->setInvalidDecl();
3903 // For an identifier declared with the storage-class specifier
3904 // extern in a scope in which a prior declaration of that
3905 // identifier is visible,23) if the prior declaration specifies
3906 // internal or external linkage, the linkage of the identifier at
3907 // the later declaration is the same as the linkage specified at
3908 // the prior declaration. If no prior declaration is visible, or
3909 // if the prior declaration specifies no linkage, then the
3910 // identifier has external linkage.
3911 if (New->hasExternalStorage() && Old->hasLinkage())
3913 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3914 !New->isStaticDataMember() &&
3915 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3916 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3917 Diag(OldLocation, PrevDiag);
3918 return New->setInvalidDecl();
3921 // Check if extern is followed by non-extern and vice-versa.
3922 if (New->hasExternalStorage() &&
3923 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3924 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3925 Diag(OldLocation, PrevDiag);
3926 return New->setInvalidDecl();
3928 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3929 !New->hasExternalStorage()) {
3930 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3931 Diag(OldLocation, PrevDiag);
3932 return New->setInvalidDecl();
3935 if (CheckRedeclarationModuleOwnership(New, Old))
3938 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3940 // FIXME: The test for external storage here seems wrong? We still
3941 // need to check for mismatches.
3942 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3943 // Don't complain about out-of-line definitions of static members.
3944 !(Old->getLexicalDeclContext()->isRecord() &&
3945 !New->getLexicalDeclContext()->isRecord())) {
3946 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3947 Diag(OldLocation, PrevDiag);
3948 return New->setInvalidDecl();
3951 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3952 if (VarDecl *Def = Old->getDefinition()) {
3953 // C++1z [dcl.fcn.spec]p4:
3954 // If the definition of a variable appears in a translation unit before
3955 // its first declaration as inline, the program is ill-formed.
3956 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3957 Diag(Def->getLocation(), diag::note_previous_definition);
3961 // If this redeclaration makes the variable inline, we may need to add it to
3962 // UndefinedButUsed.
3963 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3964 !Old->getDefinition() && !New->isThisDeclarationADefinition())
3965 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3968 if (New->getTLSKind() != Old->getTLSKind()) {
3969 if (!Old->getTLSKind()) {
3970 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3971 Diag(OldLocation, PrevDiag);
3972 } else if (!New->getTLSKind()) {
3973 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3974 Diag(OldLocation, PrevDiag);
3976 // Do not allow redeclaration to change the variable between requiring
3977 // static and dynamic initialization.
3978 // FIXME: GCC allows this, but uses the TLS keyword on the first
3979 // declaration to determine the kind. Do we need to be compatible here?
3980 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3981 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3982 Diag(OldLocation, PrevDiag);
3986 // C++ doesn't have tentative definitions, so go right ahead and check here.
3987 if (getLangOpts().CPlusPlus &&
3988 New->isThisDeclarationADefinition() == VarDecl::Definition) {
3989 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3990 Old->getCanonicalDecl()->isConstexpr()) {
3991 // This definition won't be a definition any more once it's been merged.
3992 Diag(New->getLocation(),
3993 diag::warn_deprecated_redundant_constexpr_static_def);
3994 } else if (VarDecl *Def = Old->getDefinition()) {
3995 if (checkVarDeclRedefinition(Def, New))
4000 if (haveIncompatibleLanguageLinkages(Old, New)) {
4001 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4002 Diag(OldLocation, PrevDiag);
4003 New->setInvalidDecl();
4007 // Merge "used" flag.
4008 if (Old->getMostRecentDecl()->isUsed(false))
4011 // Keep a chain of previous declarations.
4012 New->setPreviousDecl(Old);
4014 NewTemplate->setPreviousDecl(OldTemplate);
4015 adjustDeclContextForDeclaratorDecl(New, Old);
4017 // Inherit access appropriately.
4018 New->setAccess(Old->getAccess());
4020 NewTemplate->setAccess(New->getAccess());
4022 if (Old->isInline())
4023 New->setImplicitlyInline();
4026 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4027 SourceManager &SrcMgr = getSourceManager();
4028 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4029 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4030 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4031 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4032 auto &HSI = PP.getHeaderSearchInfo();
4033 StringRef HdrFilename =
4034 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4036 auto noteFromModuleOrInclude = [&](Module *Mod,
4037 SourceLocation IncLoc) -> bool {
4038 // Redefinition errors with modules are common with non modular mapped
4039 // headers, example: a non-modular header H in module A that also gets
4040 // included directly in a TU. Pointing twice to the same header/definition
4041 // is confusing, try to get better diagnostics when modules is on.
4042 if (IncLoc.isValid()) {
4044 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4045 << HdrFilename.str() << Mod->getFullModuleName();
4046 if (!Mod->DefinitionLoc.isInvalid())
4047 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4048 << Mod->getFullModuleName();
4050 Diag(IncLoc, diag::note_redefinition_include_same_file)
4051 << HdrFilename.str();
4059 // Is it the same file and same offset? Provide more information on why
4060 // this leads to a redefinition error.
4061 bool EmittedDiag = false;
4062 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4063 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4064 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4065 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4066 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4068 // If the header has no guards, emit a note suggesting one.
4069 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4070 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4076 // Redefinition coming from different files or couldn't do better above.
4077 if (Old->getLocation().isValid())
4078 Diag(Old->getLocation(), diag::note_previous_definition);
4081 /// We've just determined that \p Old and \p New both appear to be definitions
4082 /// of the same variable. Either diagnose or fix the problem.
4083 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4084 if (!hasVisibleDefinition(Old) &&
4085 (New->getFormalLinkage() == InternalLinkage ||
4087 New->getDescribedVarTemplate() ||
4088 New->getNumTemplateParameterLists() ||
4089 New->getDeclContext()->isDependentContext())) {
4090 // The previous definition is hidden, and multiple definitions are
4091 // permitted (in separate TUs). Demote this to a declaration.
4092 New->demoteThisDefinitionToDeclaration();
4094 // Make the canonical definition visible.
4095 if (auto *OldTD = Old->getDescribedVarTemplate())
4096 makeMergedDefinitionVisible(OldTD);
4097 makeMergedDefinitionVisible(Old);
4100 Diag(New->getLocation(), diag::err_redefinition) << New;
4101 notePreviousDefinition(Old, New->getLocation());
4102 New->setInvalidDecl();
4107 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4108 /// no declarator (e.g. "struct foo;") is parsed.
4110 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4111 RecordDecl *&AnonRecord) {
4112 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4116 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4117 // disambiguate entities defined in different scopes.
4118 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4120 // We will pick our mangling number depending on which version of MSVC is being
4122 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4123 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4124 ? S->getMSCurManglingNumber()
4125 : S->getMSLastManglingNumber();
4128 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4129 if (!Context.getLangOpts().CPlusPlus)
4132 if (isa<CXXRecordDecl>(Tag->getParent())) {
4133 // If this tag is the direct child of a class, number it if
4135 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4137 MangleNumberingContext &MCtx =
4138 Context.getManglingNumberContext(Tag->getParent());
4139 Context.setManglingNumber(
4140 Tag, MCtx.getManglingNumber(
4141 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4145 // If this tag isn't a direct child of a class, number it if it is local.
4146 Decl *ManglingContextDecl;
4147 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4148 Tag->getDeclContext(), ManglingContextDecl)) {
4149 Context.setManglingNumber(
4150 Tag, MCtx->getManglingNumber(
4151 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4155 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4156 TypedefNameDecl *NewTD) {
4157 if (TagFromDeclSpec->isInvalidDecl())
4160 // Do nothing if the tag already has a name for linkage purposes.
4161 if (TagFromDeclSpec->hasNameForLinkage())
4164 // A well-formed anonymous tag must always be a TUK_Definition.
4165 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4167 // The type must match the tag exactly; no qualifiers allowed.
4168 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4169 Context.getTagDeclType(TagFromDeclSpec))) {
4170 if (getLangOpts().CPlusPlus)
4171 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4175 // If we've already computed linkage for the anonymous tag, then
4176 // adding a typedef name for the anonymous decl can change that
4177 // linkage, which might be a serious problem. Diagnose this as
4178 // unsupported and ignore the typedef name. TODO: we should
4179 // pursue this as a language defect and establish a formal rule
4180 // for how to handle it.
4181 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4182 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4184 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4185 tagLoc = getLocForEndOfToken(tagLoc);
4187 llvm::SmallString<40> textToInsert;
4188 textToInsert += ' ';
4189 textToInsert += NewTD->getIdentifier()->getName();
4190 Diag(tagLoc, diag::note_typedef_changes_linkage)
4191 << FixItHint::CreateInsertion(tagLoc, textToInsert);
4195 // Otherwise, set this is the anon-decl typedef for the tag.
4196 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4199 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4201 case DeclSpec::TST_class:
4203 case DeclSpec::TST_struct:
4205 case DeclSpec::TST_interface:
4207 case DeclSpec::TST_union:
4209 case DeclSpec::TST_enum:
4212 llvm_unreachable("unexpected type specifier");
4216 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4217 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4218 /// parameters to cope with template friend declarations.
4220 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4221 MultiTemplateParamsArg TemplateParams,
4222 bool IsExplicitInstantiation,
4223 RecordDecl *&AnonRecord) {
4224 Decl *TagD = nullptr;
4225 TagDecl *Tag = nullptr;
4226 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4227 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4228 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4229 DS.getTypeSpecType() == DeclSpec::TST_union ||
4230 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4231 TagD = DS.getRepAsDecl();
4233 if (!TagD) // We probably had an error
4236 // Note that the above type specs guarantee that the
4237 // type rep is a Decl, whereas in many of the others
4239 if (isa<TagDecl>(TagD))
4240 Tag = cast<TagDecl>(TagD);
4241 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4242 Tag = CTD->getTemplatedDecl();
4246 handleTagNumbering(Tag, S);
4247 Tag->setFreeStanding();
4248 if (Tag->isInvalidDecl())
4252 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4253 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4254 // or incomplete types shall not be restrict-qualified."
4255 if (TypeQuals & DeclSpec::TQ_restrict)
4256 Diag(DS.getRestrictSpecLoc(),
4257 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4258 << DS.getSourceRange();
4261 if (DS.isInlineSpecified())
4262 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4263 << getLangOpts().CPlusPlus17;
4265 if (DS.isConstexprSpecified()) {
4266 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4267 // and definitions of functions and variables.
4269 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4270 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4272 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4273 // Don't emit warnings after this error.
4277 DiagnoseFunctionSpecifiers(DS);
4279 if (DS.isFriendSpecified()) {
4280 // If we're dealing with a decl but not a TagDecl, assume that
4281 // whatever routines created it handled the friendship aspect.
4284 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4287 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4288 bool IsExplicitSpecialization =
4289 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4290 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4291 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4292 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4293 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4294 // nested-name-specifier unless it is an explicit instantiation
4295 // or an explicit specialization.
4297 // FIXME: We allow class template partial specializations here too, per the
4298 // obvious intent of DR1819.
4300 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4301 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4302 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4306 // Track whether this decl-specifier declares anything.
4307 bool DeclaresAnything = true;
4309 // Handle anonymous struct definitions.
4310 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4311 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4312 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4313 if (getLangOpts().CPlusPlus ||
4314 Record->getDeclContext()->isRecord()) {
4315 // If CurContext is a DeclContext that can contain statements,
4316 // RecursiveASTVisitor won't visit the decls that
4317 // BuildAnonymousStructOrUnion() will put into CurContext.
4318 // Also store them here so that they can be part of the
4319 // DeclStmt that gets created in this case.
4320 // FIXME: Also return the IndirectFieldDecls created by
4321 // BuildAnonymousStructOr union, for the same reason?
4322 if (CurContext->isFunctionOrMethod())
4323 AnonRecord = Record;
4324 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4325 Context.getPrintingPolicy());
4328 DeclaresAnything = false;
4333 // A struct-declaration that does not declare an anonymous structure or
4334 // anonymous union shall contain a struct-declarator-list.
4336 // This rule also existed in C89 and C99; the grammar for struct-declaration
4337 // did not permit a struct-declaration without a struct-declarator-list.
4338 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4339 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4340 // Check for Microsoft C extension: anonymous struct/union member.
4341 // Handle 2 kinds of anonymous struct/union:
4345 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4346 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4347 if ((Tag && Tag->getDeclName()) ||
4348 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4349 RecordDecl *Record = nullptr;
4351 Record = dyn_cast<RecordDecl>(Tag);
4352 else if (const RecordType *RT =
4353 DS.getRepAsType().get()->getAsStructureType())
4354 Record = RT->getDecl();
4355 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4356 Record = UT->getDecl();
4358 if (Record && getLangOpts().MicrosoftExt) {
4359 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4360 << Record->isUnion() << DS.getSourceRange();
4361 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4364 DeclaresAnything = false;
4368 // Skip all the checks below if we have a type error.
4369 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4370 (TagD && TagD->isInvalidDecl()))
4373 if (getLangOpts().CPlusPlus &&
4374 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4375 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4376 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4377 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4378 DeclaresAnything = false;
4380 if (!DS.isMissingDeclaratorOk()) {
4381 // Customize diagnostic for a typedef missing a name.
4382 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4383 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4384 << DS.getSourceRange();
4386 DeclaresAnything = false;
4389 if (DS.isModulePrivateSpecified() &&
4390 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4391 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4392 << Tag->getTagKind()
4393 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4395 ActOnDocumentableDecl(TagD);
4398 // A declaration [...] shall declare at least a declarator [...], a tag,
4399 // or the members of an enumeration.
4401 // [If there are no declarators], and except for the declaration of an
4402 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4403 // names into the program, or shall redeclare a name introduced by a
4404 // previous declaration.
4405 if (!DeclaresAnything) {
4406 // In C, we allow this as a (popular) extension / bug. Don't bother
4407 // producing further diagnostics for redundant qualifiers after this.
4408 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4413 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4414 // init-declarator-list of the declaration shall not be empty.
4415 // C++ [dcl.fct.spec]p1:
4416 // If a cv-qualifier appears in a decl-specifier-seq, the
4417 // init-declarator-list of the declaration shall not be empty.
4419 // Spurious qualifiers here appear to be valid in C.
4420 unsigned DiagID = diag::warn_standalone_specifier;
4421 if (getLangOpts().CPlusPlus)
4422 DiagID = diag::ext_standalone_specifier;
4424 // Note that a linkage-specification sets a storage class, but
4425 // 'extern "C" struct foo;' is actually valid and not theoretically
4427 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4428 if (SCS == DeclSpec::SCS_mutable)
4429 // Since mutable is not a viable storage class specifier in C, there is
4430 // no reason to treat it as an extension. Instead, diagnose as an error.
4431 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4432 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4433 Diag(DS.getStorageClassSpecLoc(), DiagID)
4434 << DeclSpec::getSpecifierName(SCS);
4437 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4438 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4439 << DeclSpec::getSpecifierName(TSCS);
4440 if (DS.getTypeQualifiers()) {
4441 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4442 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4443 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4444 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4445 // Restrict is covered above.
4446 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4447 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4448 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4449 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4452 // Warn about ignored type attributes, for example:
4453 // __attribute__((aligned)) struct A;
4454 // Attributes should be placed after tag to apply to type declaration.
4455 if (!DS.getAttributes().empty()) {
4456 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4457 if (TypeSpecType == DeclSpec::TST_class ||
4458 TypeSpecType == DeclSpec::TST_struct ||
4459 TypeSpecType == DeclSpec::TST_interface ||
4460 TypeSpecType == DeclSpec::TST_union ||
4461 TypeSpecType == DeclSpec::TST_enum) {
4462 for (const ParsedAttr &AL : DS.getAttributes())
4463 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4464 << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4471 /// We are trying to inject an anonymous member into the given scope;
4472 /// check if there's an existing declaration that can't be overloaded.
4474 /// \return true if this is a forbidden redeclaration
4475 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4478 DeclarationName Name,
4479 SourceLocation NameLoc,
4481 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4482 Sema::ForVisibleRedeclaration);
4483 if (!SemaRef.LookupName(R, S)) return false;
4485 // Pick a representative declaration.
4486 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4487 assert(PrevDecl && "Expected a non-null Decl");
4489 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4492 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4494 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4499 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4500 /// anonymous struct or union AnonRecord into the owning context Owner
4501 /// and scope S. This routine will be invoked just after we realize
4502 /// that an unnamed union or struct is actually an anonymous union or
4509 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4510 /// // f into the surrounding scope.x
4513 /// This routine is recursive, injecting the names of nested anonymous
4514 /// structs/unions into the owning context and scope as well.
4516 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4517 RecordDecl *AnonRecord, AccessSpecifier AS,
4518 SmallVectorImpl<NamedDecl *> &Chaining) {
4519 bool Invalid = false;
4521 // Look every FieldDecl and IndirectFieldDecl with a name.
4522 for (auto *D : AnonRecord->decls()) {
4523 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4524 cast<NamedDecl>(D)->getDeclName()) {
4525 ValueDecl *VD = cast<ValueDecl>(D);
4526 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4528 AnonRecord->isUnion())) {
4529 // C++ [class.union]p2:
4530 // The names of the members of an anonymous union shall be
4531 // distinct from the names of any other entity in the
4532 // scope in which the anonymous union is declared.
4535 // C++ [class.union]p2:
4536 // For the purpose of name lookup, after the anonymous union
4537 // definition, the members of the anonymous union are
4538 // considered to have been defined in the scope in which the
4539 // anonymous union is declared.
4540 unsigned OldChainingSize = Chaining.size();
4541 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4542 Chaining.append(IF->chain_begin(), IF->chain_end());
4544 Chaining.push_back(VD);
4546 assert(Chaining.size() >= 2);
4547 NamedDecl **NamedChain =
4548 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4549 for (unsigned i = 0; i < Chaining.size(); i++)
4550 NamedChain[i] = Chaining[i];
4552 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4553 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4554 VD->getType(), {NamedChain, Chaining.size()});
4556 for (const auto *Attr : VD->attrs())
4557 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4559 IndirectField->setAccess(AS);
4560 IndirectField->setImplicit();
4561 SemaRef.PushOnScopeChains(IndirectField, S);
4563 // That includes picking up the appropriate access specifier.
4564 if (AS != AS_none) IndirectField->setAccess(AS);
4566 Chaining.resize(OldChainingSize);
4574 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4575 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4576 /// illegal input values are mapped to SC_None.
4578 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4579 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4580 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4581 "Parser allowed 'typedef' as storage class VarDecl.");
4582 switch (StorageClassSpec) {
4583 case DeclSpec::SCS_unspecified: return SC_None;
4584 case DeclSpec::SCS_extern:
4585 if (DS.isExternInLinkageSpec())
4588 case DeclSpec::SCS_static: return SC_Static;
4589 case DeclSpec::SCS_auto: return SC_Auto;
4590 case DeclSpec::SCS_register: return SC_Register;
4591 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4592 // Illegal SCSs map to None: error reporting is up to the caller.
4593 case DeclSpec::SCS_mutable: // Fall through.
4594 case DeclSpec::SCS_typedef: return SC_None;
4596 llvm_unreachable("unknown storage class specifier");
4599 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4600 assert(Record->hasInClassInitializer());
4602 for (const auto *I : Record->decls()) {
4603 const auto *FD = dyn_cast<FieldDecl>(I);
4604 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4605 FD = IFD->getAnonField();
4606 if (FD && FD->hasInClassInitializer())
4607 return FD->getLocation();
4610 llvm_unreachable("couldn't find in-class initializer");
4613 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4614 SourceLocation DefaultInitLoc) {
4615 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4618 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4619 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4622 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4623 CXXRecordDecl *AnonUnion) {
4624 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4627 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4630 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4631 /// anonymous structure or union. Anonymous unions are a C++ feature
4632 /// (C++ [class.union]) and a C11 feature; anonymous structures
4633 /// are a C11 feature and GNU C++ extension.
4634 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4637 const PrintingPolicy &Policy) {
4638 DeclContext *Owner = Record->getDeclContext();
4640 // Diagnose whether this anonymous struct/union is an extension.
4641 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4642 Diag(Record->getLocation(), diag::ext_anonymous_union);
4643 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4644 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4645 else if (!Record->isUnion() && !getLangOpts().C11)
4646 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4648 // C and C++ require different kinds of checks for anonymous
4650 bool Invalid = false;
4651 if (getLangOpts().CPlusPlus) {
4652 const char *PrevSpec = nullptr;
4654 if (Record->isUnion()) {
4655 // C++ [class.union]p6:
4656 // C++17 [class.union.anon]p2:
4657 // Anonymous unions declared in a named namespace or in the
4658 // global namespace shall be declared static.
4659 DeclContext *OwnerScope = Owner->getRedeclContext();
4660 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4661 (OwnerScope->isTranslationUnit() ||
4662 (OwnerScope->isNamespace() &&
4663 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4664 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4665 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4667 // Recover by adding 'static'.
4668 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4669 PrevSpec, DiagID, Policy);
4671 // C++ [class.union]p6:
4672 // A storage class is not allowed in a declaration of an
4673 // anonymous union in a class scope.
4674 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4675 isa<RecordDecl>(Owner)) {
4676 Diag(DS.getStorageClassSpecLoc(),
4677 diag::err_anonymous_union_with_storage_spec)
4678 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4680 // Recover by removing the storage specifier.
4681 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4683 PrevSpec, DiagID, Context.getPrintingPolicy());
4687 // Ignore const/volatile/restrict qualifiers.
4688 if (DS.getTypeQualifiers()) {
4689 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4690 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4691 << Record->isUnion() << "const"
4692 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4693 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4694 Diag(DS.getVolatileSpecLoc(),
4695 diag::ext_anonymous_struct_union_qualified)
4696 << Record->isUnion() << "volatile"
4697 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4698 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4699 Diag(DS.getRestrictSpecLoc(),
4700 diag::ext_anonymous_struct_union_qualified)
4701 << Record->isUnion() << "restrict"
4702 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4703 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4704 Diag(DS.getAtomicSpecLoc(),
4705 diag::ext_anonymous_struct_union_qualified)
4706 << Record->isUnion() << "_Atomic"
4707 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4708 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4709 Diag(DS.getUnalignedSpecLoc(),
4710 diag::ext_anonymous_struct_union_qualified)
4711 << Record->isUnion() << "__unaligned"
4712 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4714 DS.ClearTypeQualifiers();
4717 // C++ [class.union]p2:
4718 // The member-specification of an anonymous union shall only
4719 // define non-static data members. [Note: nested types and
4720 // functions cannot be declared within an anonymous union. ]
4721 for (auto *Mem : Record->decls()) {
4722 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4723 // C++ [class.union]p3:
4724 // An anonymous union shall not have private or protected
4725 // members (clause 11).
4726 assert(FD->getAccess() != AS_none);
4727 if (FD->getAccess() != AS_public) {
4728 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4729 << Record->isUnion() << (FD->getAccess() == AS_protected);
4733 // C++ [class.union]p1
4734 // An object of a class with a non-trivial constructor, a non-trivial
4735 // copy constructor, a non-trivial destructor, or a non-trivial copy
4736 // assignment operator cannot be a member of a union, nor can an
4737 // array of such objects.
4738 if (CheckNontrivialField(FD))
4740 } else if (Mem->isImplicit()) {
4741 // Any implicit members are fine.
4742 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4743 // This is a type that showed up in an
4744 // elaborated-type-specifier inside the anonymous struct or
4745 // union, but which actually declares a type outside of the
4746 // anonymous struct or union. It's okay.
4747 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4748 if (!MemRecord->isAnonymousStructOrUnion() &&
4749 MemRecord->getDeclName()) {
4750 // Visual C++ allows type definition in anonymous struct or union.
4751 if (getLangOpts().MicrosoftExt)
4752 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4753 << Record->isUnion();
4755 // This is a nested type declaration.
4756 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4757 << Record->isUnion();
4761 // This is an anonymous type definition within another anonymous type.
4762 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4763 // not part of standard C++.
4764 Diag(MemRecord->getLocation(),
4765 diag::ext_anonymous_record_with_anonymous_type)
4766 << Record->isUnion();
4768 } else if (isa<AccessSpecDecl>(Mem)) {
4769 // Any access specifier is fine.
4770 } else if (isa<StaticAssertDecl>(Mem)) {
4771 // In C++1z, static_assert declarations are also fine.
4773 // We have something that isn't a non-static data
4774 // member. Complain about it.
4775 unsigned DK = diag::err_anonymous_record_bad_member;
4776 if (isa<TypeDecl>(Mem))
4777 DK = diag::err_anonymous_record_with_type;
4778 else if (isa<FunctionDecl>(Mem))
4779 DK = diag::err_anonymous_record_with_function;
4780 else if (isa<VarDecl>(Mem))
4781 DK = diag::err_anonymous_record_with_static;
4783 // Visual C++ allows type definition in anonymous struct or union.
4784 if (getLangOpts().MicrosoftExt &&
4785 DK == diag::err_anonymous_record_with_type)
4786 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4787 << Record->isUnion();
4789 Diag(Mem->getLocation(), DK) << Record->isUnion();
4795 // C++11 [class.union]p8 (DR1460):
4796 // At most one variant member of a union may have a
4797 // brace-or-equal-initializer.
4798 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4800 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4801 cast<CXXRecordDecl>(Record));
4804 if (!Record->isUnion() && !Owner->isRecord()) {
4805 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4806 << getLangOpts().CPlusPlus;
4810 // Mock up a declarator.
4811 Declarator Dc(DS, DeclaratorContext::MemberContext);
4812 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4813 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4815 // Create a declaration for this anonymous struct/union.
4816 NamedDecl *Anon = nullptr;
4817 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4818 Anon = FieldDecl::Create(Context, OwningClass,
4820 Record->getLocation(),
4821 /*IdentifierInfo=*/nullptr,
4822 Context.getTypeDeclType(Record),
4824 /*BitWidth=*/nullptr, /*Mutable=*/false,
4825 /*InitStyle=*/ICIS_NoInit);
4826 Anon->setAccess(AS);
4827 if (getLangOpts().CPlusPlus)
4828 FieldCollector->Add(cast<FieldDecl>(Anon));
4830 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4831 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4832 if (SCSpec == DeclSpec::SCS_mutable) {
4833 // mutable can only appear on non-static class members, so it's always
4835 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4840 Anon = VarDecl::Create(Context, Owner,
4842 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4843 Context.getTypeDeclType(Record),
4846 // Default-initialize the implicit variable. This initialization will be
4847 // trivial in almost all cases, except if a union member has an in-class
4849 // union { int n = 0; };
4850 ActOnUninitializedDecl(Anon);
4852 Anon->setImplicit();
4854 // Mark this as an anonymous struct/union type.
4855 Record->setAnonymousStructOrUnion(true);
4857 // Add the anonymous struct/union object to the current
4858 // context. We'll be referencing this object when we refer to one of
4860 Owner->addDecl(Anon);
4862 // Inject the members of the anonymous struct/union into the owning
4863 // context and into the identifier resolver chain for name lookup
4865 SmallVector<NamedDecl*, 2> Chain;
4866 Chain.push_back(Anon);
4868 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4871 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4872 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4873 Decl *ManglingContextDecl;
4874 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4875 NewVD->getDeclContext(), ManglingContextDecl)) {
4876 Context.setManglingNumber(
4877 NewVD, MCtx->getManglingNumber(
4878 NewVD, getMSManglingNumber(getLangOpts(), S)));
4879 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4885 Anon->setInvalidDecl();
4890 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4891 /// Microsoft C anonymous structure.
4892 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4895 /// struct A { int a; };
4896 /// struct B { struct A; int b; };
4903 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4904 RecordDecl *Record) {
4905 assert(Record && "expected a record!");
4907 // Mock up a declarator.
4908 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4909 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4910 assert(TInfo && "couldn't build declarator info for anonymous struct");
4912 auto *ParentDecl = cast<RecordDecl>(CurContext);
4913 QualType RecTy = Context.getTypeDeclType(Record);
4915 // Create a declaration for this anonymous struct.
4916 NamedDecl *Anon = FieldDecl::Create(Context,
4920 /*IdentifierInfo=*/nullptr,
4923 /*BitWidth=*/nullptr, /*Mutable=*/false,
4924 /*InitStyle=*/ICIS_NoInit);
4925 Anon->setImplicit();
4927 // Add the anonymous struct object to the current context.
4928 CurContext->addDecl(Anon);
4930 // Inject the members of the anonymous struct into the current
4931 // context and into the identifier resolver chain for name lookup
4933 SmallVector<NamedDecl*, 2> Chain;
4934 Chain.push_back(Anon);
4936 RecordDecl *RecordDef = Record->getDefinition();
4937 if (RequireCompleteType(Anon->getLocation(), RecTy,
4938 diag::err_field_incomplete) ||
4939 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4941 Anon->setInvalidDecl();
4942 ParentDecl->setInvalidDecl();
4948 /// GetNameForDeclarator - Determine the full declaration name for the
4949 /// given Declarator.
4950 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4951 return GetNameFromUnqualifiedId(D.getName());
4954 /// Retrieves the declaration name from a parsed unqualified-id.
4956 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4957 DeclarationNameInfo NameInfo;
4958 NameInfo.setLoc(Name.StartLocation);
4960 switch (Name.getKind()) {
4962 case UnqualifiedIdKind::IK_ImplicitSelfParam:
4963 case UnqualifiedIdKind::IK_Identifier:
4964 NameInfo.setName(Name.Identifier);
4965 NameInfo.setLoc(Name.StartLocation);
4968 case UnqualifiedIdKind::IK_DeductionGuideName: {
4969 // C++ [temp.deduct.guide]p3:
4970 // The simple-template-id shall name a class template specialization.
4971 // The template-name shall be the same identifier as the template-name
4972 // of the simple-template-id.
4973 // These together intend to imply that the template-name shall name a
4975 // FIXME: template<typename T> struct X {};
4976 // template<typename T> using Y = X<T>;
4977 // Y(int) -> Y<int>;
4978 // satisfies these rules but does not name a class template.
4979 TemplateName TN = Name.TemplateName.get().get();
4980 auto *Template = TN.getAsTemplateDecl();
4981 if (!Template || !isa<ClassTemplateDecl>(Template)) {
4982 Diag(Name.StartLocation,
4983 diag::err_deduction_guide_name_not_class_template)
4984 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4986 Diag(Template->getLocation(), diag::note_template_decl_here);
4987 return DeclarationNameInfo();
4991 Context.DeclarationNames.getCXXDeductionGuideName(Template));
4992 NameInfo.setLoc(Name.StartLocation);
4996 case UnqualifiedIdKind::IK_OperatorFunctionId:
4997 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4998 Name.OperatorFunctionId.Operator));
4999 NameInfo.setLoc(Name.StartLocation);
5000 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5001 = Name.OperatorFunctionId.SymbolLocations[0];
5002 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5003 = Name.EndLocation.getRawEncoding();
5006 case UnqualifiedIdKind::IK_LiteralOperatorId:
5007 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5009 NameInfo.setLoc(Name.StartLocation);
5010 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5013 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5014 TypeSourceInfo *TInfo;
5015 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5017 return DeclarationNameInfo();
5018 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5019 Context.getCanonicalType(Ty)));
5020 NameInfo.setLoc(Name.StartLocation);
5021 NameInfo.setNamedTypeInfo(TInfo);
5025 case UnqualifiedIdKind::IK_ConstructorName: {
5026 TypeSourceInfo *TInfo;
5027 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5029 return DeclarationNameInfo();
5030 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5031 Context.getCanonicalType(Ty)));
5032 NameInfo.setLoc(Name.StartLocation);
5033 NameInfo.setNamedTypeInfo(TInfo);
5037 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5038 // In well-formed code, we can only have a constructor
5039 // template-id that refers to the current context, so go there
5040 // to find the actual type being constructed.
5041 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5042 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5043 return DeclarationNameInfo();
5045 // Determine the type of the class being constructed.
5046 QualType CurClassType = Context.getTypeDeclType(CurClass);
5048 // FIXME: Check two things: that the template-id names the same type as
5049 // CurClassType, and that the template-id does not occur when the name
5052 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5053 Context.getCanonicalType(CurClassType)));
5054 NameInfo.setLoc(Name.StartLocation);
5055 // FIXME: should we retrieve TypeSourceInfo?
5056 NameInfo.setNamedTypeInfo(nullptr);
5060 case UnqualifiedIdKind::IK_DestructorName: {
5061 TypeSourceInfo *TInfo;
5062 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5064 return DeclarationNameInfo();
5065 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5066 Context.getCanonicalType(Ty)));
5067 NameInfo.setLoc(Name.StartLocation);
5068 NameInfo.setNamedTypeInfo(TInfo);
5072 case UnqualifiedIdKind::IK_TemplateId: {
5073 TemplateName TName = Name.TemplateId->Template.get();
5074 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5075 return Context.getNameForTemplate(TName, TNameLoc);
5078 } // switch (Name.getKind())
5080 llvm_unreachable("Unknown name kind");
5083 static QualType getCoreType(QualType Ty) {
5085 if (Ty->isPointerType() || Ty->isReferenceType())
5086 Ty = Ty->getPointeeType();
5087 else if (Ty->isArrayType())
5088 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5090 return Ty.withoutLocalFastQualifiers();
5094 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5095 /// and Definition have "nearly" matching parameters. This heuristic is
5096 /// used to improve diagnostics in the case where an out-of-line function
5097 /// definition doesn't match any declaration within the class or namespace.
5098 /// Also sets Params to the list of indices to the parameters that differ
5099 /// between the declaration and the definition. If hasSimilarParameters
5100 /// returns true and Params is empty, then all of the parameters match.
5101 static bool hasSimilarParameters(ASTContext &Context,
5102 FunctionDecl *Declaration,
5103 FunctionDecl *Definition,
5104 SmallVectorImpl<unsigned> &Params) {
5106 if (Declaration->param_size() != Definition->param_size())
5108 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5109 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5110 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5112 // The parameter types are identical
5113 if (Context.hasSameType(DefParamTy, DeclParamTy))
5116 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5117 QualType DefParamBaseTy = getCoreType(DefParamTy);
5118 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5119 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5121 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5122 (DeclTyName && DeclTyName == DefTyName))
5123 Params.push_back(Idx);
5124 else // The two parameters aren't even close
5131 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5132 /// declarator needs to be rebuilt in the current instantiation.
5133 /// Any bits of declarator which appear before the name are valid for
5134 /// consideration here. That's specifically the type in the decl spec
5135 /// and the base type in any member-pointer chunks.
5136 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5137 DeclarationName Name) {
5138 // The types we specifically need to rebuild are:
5139 // - typenames, typeofs, and decltypes
5140 // - types which will become injected class names
5141 // Of course, we also need to rebuild any type referencing such a
5142 // type. It's safest to just say "dependent", but we call out a
5145 DeclSpec &DS = D.getMutableDeclSpec();
5146 switch (DS.getTypeSpecType()) {
5147 case DeclSpec::TST_typename:
5148 case DeclSpec::TST_typeofType:
5149 case DeclSpec::TST_underlyingType:
5150 case DeclSpec::TST_atomic: {
5151 // Grab the type from the parser.
5152 TypeSourceInfo *TSI = nullptr;
5153 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5154 if (T.isNull() || !T->isDependentType()) break;
5156 // Make sure there's a type source info. This isn't really much
5157 // of a waste; most dependent types should have type source info
5158 // attached already.
5160 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5162 // Rebuild the type in the current instantiation.
5163 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5164 if (!TSI) return true;
5166 // Store the new type back in the decl spec.
5167 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5168 DS.UpdateTypeRep(LocType);
5172 case DeclSpec::TST_decltype:
5173 case DeclSpec::TST_typeofExpr: {
5174 Expr *E = DS.getRepAsExpr();
5175 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5176 if (Result.isInvalid()) return true;
5177 DS.UpdateExprRep(Result.get());
5182 // Nothing to do for these decl specs.
5186 // It doesn't matter what order we do this in.
5187 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5188 DeclaratorChunk &Chunk = D.getTypeObject(I);
5190 // The only type information in the declarator which can come
5191 // before the declaration name is the base type of a member
5193 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5196 // Rebuild the scope specifier in-place.
5197 CXXScopeSpec &SS = Chunk.Mem.Scope();
5198 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5205 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5206 D.setFunctionDefinitionKind(FDK_Declaration);
5207 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5209 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5210 Dcl && Dcl->getDeclContext()->isFileContext())
5211 Dcl->setTopLevelDeclInObjCContainer();
5213 if (getLangOpts().OpenCL)
5214 setCurrentOpenCLExtensionForDecl(Dcl);
5219 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5220 /// If T is the name of a class, then each of the following shall have a
5221 /// name different from T:
5222 /// - every static data member of class T;
5223 /// - every member function of class T
5224 /// - every member of class T that is itself a type;
5225 /// \returns true if the declaration name violates these rules.
5226 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5227 DeclarationNameInfo NameInfo) {
5228 DeclarationName Name = NameInfo.getName();
5230 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5231 while (Record && Record->isAnonymousStructOrUnion())
5232 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5233 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5234 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5241 /// Diagnose a declaration whose declarator-id has the given
5242 /// nested-name-specifier.
5244 /// \param SS The nested-name-specifier of the declarator-id.
5246 /// \param DC The declaration context to which the nested-name-specifier
5249 /// \param Name The name of the entity being declared.
5251 /// \param Loc The location of the name of the entity being declared.
5253 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5254 /// we're declaring an explicit / partial specialization / instantiation.
5256 /// \returns true if we cannot safely recover from this error, false otherwise.
5257 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5258 DeclarationName Name,
5259 SourceLocation Loc, bool IsTemplateId) {
5260 DeclContext *Cur = CurContext;
5261 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5262 Cur = Cur->getParent();
5264 // If the user provided a superfluous scope specifier that refers back to the
5265 // class in which the entity is already declared, diagnose and ignore it.
5271 // Note, it was once ill-formed to give redundant qualification in all
5272 // contexts, but that rule was removed by DR482.
5273 if (Cur->Equals(DC)) {
5274 if (Cur->isRecord()) {
5275 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5276 : diag::err_member_extra_qualification)
5277 << Name << FixItHint::CreateRemoval(SS.getRange());
5280 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5285 // Check whether the qualifying scope encloses the scope of the original
5286 // declaration. For a template-id, we perform the checks in
5287 // CheckTemplateSpecializationScope.
5288 if (!Cur->Encloses(DC) && !IsTemplateId) {
5289 if (Cur->isRecord())
5290 Diag(Loc, diag::err_member_qualification)
5291 << Name << SS.getRange();
5292 else if (isa<TranslationUnitDecl>(DC))
5293 Diag(Loc, diag::err_invalid_declarator_global_scope)
5294 << Name << SS.getRange();
5295 else if (isa<FunctionDecl>(Cur))
5296 Diag(Loc, diag::err_invalid_declarator_in_function)
5297 << Name << SS.getRange();
5298 else if (isa<BlockDecl>(Cur))
5299 Diag(Loc, diag::err_invalid_declarator_in_block)
5300 << Name << SS.getRange();
5302 Diag(Loc, diag::err_invalid_declarator_scope)
5303 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5308 if (Cur->isRecord()) {
5309 // Cannot qualify members within a class.
5310 Diag(Loc, diag::err_member_qualification)
5311 << Name << SS.getRange();
5314 // C++ constructors and destructors with incorrect scopes can break
5315 // our AST invariants by having the wrong underlying types. If
5316 // that's the case, then drop this declaration entirely.
5317 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5318 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5319 !Context.hasSameType(Name.getCXXNameType(),
5320 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5326 // C++11 [dcl.meaning]p1:
5327 // [...] "The nested-name-specifier of the qualified declarator-id shall
5328 // not begin with a decltype-specifer"
5329 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5330 while (SpecLoc.getPrefix())
5331 SpecLoc = SpecLoc.getPrefix();
5332 if (dyn_cast_or_null<DecltypeType>(
5333 SpecLoc.getNestedNameSpecifier()->getAsType()))
5334 Diag(Loc, diag::err_decltype_in_declarator)
5335 << SpecLoc.getTypeLoc().getSourceRange();
5340 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5341 MultiTemplateParamsArg TemplateParamLists) {
5342 // TODO: consider using NameInfo for diagnostic.
5343 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5344 DeclarationName Name = NameInfo.getName();
5346 // All of these full declarators require an identifier. If it doesn't have
5347 // one, the ParsedFreeStandingDeclSpec action should be used.
5348 if (D.isDecompositionDeclarator()) {
5349 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5351 if (!D.isInvalidType()) // Reject this if we think it is valid.
5352 Diag(D.getDeclSpec().getLocStart(),
5353 diag::err_declarator_need_ident)
5354 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5356 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5359 // The scope passed in may not be a decl scope. Zip up the scope tree until
5360 // we find one that is.
5361 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5362 (S->getFlags() & Scope::TemplateParamScope) != 0)
5365 DeclContext *DC = CurContext;
5366 if (D.getCXXScopeSpec().isInvalid())
5368 else if (D.getCXXScopeSpec().isSet()) {
5369 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5370 UPPC_DeclarationQualifier))
5373 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5374 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5375 if (!DC || isa<EnumDecl>(DC)) {
5376 // If we could not compute the declaration context, it's because the
5377 // declaration context is dependent but does not refer to a class,
5378 // class template, or class template partial specialization. Complain
5379 // and return early, to avoid the coming semantic disaster.
5380 Diag(D.getIdentifierLoc(),
5381 diag::err_template_qualified_declarator_no_match)
5382 << D.getCXXScopeSpec().getScopeRep()
5383 << D.getCXXScopeSpec().getRange();
5386 bool IsDependentContext = DC->isDependentContext();
5388 if (!IsDependentContext &&
5389 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5392 // If a class is incomplete, do not parse entities inside it.
5393 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5394 Diag(D.getIdentifierLoc(),
5395 diag::err_member_def_undefined_record)
5396 << Name << DC << D.getCXXScopeSpec().getRange();
5399 if (!D.getDeclSpec().isFriendSpecified()) {
5400 if (diagnoseQualifiedDeclaration(
5401 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5402 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5410 // Check whether we need to rebuild the type of the given
5411 // declaration in the current instantiation.
5412 if (EnteringContext && IsDependentContext &&
5413 TemplateParamLists.size() != 0) {
5414 ContextRAII SavedContext(*this, DC);
5415 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5420 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5421 QualType R = TInfo->getType();
5423 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5424 UPPC_DeclarationType))
5427 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5428 forRedeclarationInCurContext());
5430 // See if this is a redefinition of a variable in the same scope.
5431 if (!D.getCXXScopeSpec().isSet()) {
5432 bool IsLinkageLookup = false;
5433 bool CreateBuiltins = false;
5435 // If the declaration we're planning to build will be a function
5436 // or object with linkage, then look for another declaration with
5437 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5439 // If the declaration we're planning to build will be declared with
5440 // external linkage in the translation unit, create any builtin with
5442 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5444 else if (CurContext->isFunctionOrMethod() &&
5445 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5446 R->isFunctionType())) {
5447 IsLinkageLookup = true;
5449 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5450 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5451 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5452 CreateBuiltins = true;
5454 if (IsLinkageLookup) {
5455 Previous.clear(LookupRedeclarationWithLinkage);
5456 Previous.setRedeclarationKind(ForExternalRedeclaration);
5459 LookupName(Previous, S, CreateBuiltins);
5460 } else { // Something like "int foo::x;"
5461 LookupQualifiedName(Previous, DC);
5463 // C++ [dcl.meaning]p1:
5464 // When the declarator-id is qualified, the declaration shall refer to a
5465 // previously declared member of the class or namespace to which the
5466 // qualifier refers (or, in the case of a namespace, of an element of the
5467 // inline namespace set of that namespace (7.3.1)) or to a specialization
5470 // Note that we already checked the context above, and that we do not have
5471 // enough information to make sure that Previous contains the declaration
5472 // we want to match. For example, given:
5479 // void X::f(int) { } // ill-formed
5481 // In this case, Previous will point to the overload set
5482 // containing the two f's declared in X, but neither of them
5485 // C++ [dcl.meaning]p1:
5486 // [...] the member shall not merely have been introduced by a
5487 // using-declaration in the scope of the class or namespace nominated by
5488 // the nested-name-specifier of the declarator-id.
5489 RemoveUsingDecls(Previous);
5492 if (Previous.isSingleResult() &&
5493 Previous.getFoundDecl()->isTemplateParameter()) {
5494 // Maybe we will complain about the shadowed template parameter.
5495 if (!D.isInvalidType())
5496 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5497 Previous.getFoundDecl());
5499 // Just pretend that we didn't see the previous declaration.
5503 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5504 // Forget that the previous declaration is the injected-class-name.
5507 // In C++, the previous declaration we find might be a tag type
5508 // (class or enum). In this case, the new declaration will hide the
5509 // tag type. Note that this applies to functions, function templates, and
5510 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5511 if (Previous.isSingleTagDecl() &&
5512 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5513 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5516 // Check that there are no default arguments other than in the parameters
5517 // of a function declaration (C++ only).
5518 if (getLangOpts().CPlusPlus)
5519 CheckExtraCXXDefaultArguments(D);
5523 bool AddToScope = true;
5524 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5525 if (TemplateParamLists.size()) {
5526 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5530 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5531 } else if (R->isFunctionType()) {
5532 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5536 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5543 // If this has an identifier and is not a function template specialization,
5544 // add it to the scope stack.
5545 if (New->getDeclName() && AddToScope) {
5546 // Only make a locally-scoped extern declaration visible if it is the first
5547 // declaration of this entity. Qualified lookup for such an entity should
5548 // only find this declaration if there is no visible declaration of it.
5549 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5550 PushOnScopeChains(New, S, AddToContext);
5552 CurContext->addHiddenDecl(New);
5555 if (isInOpenMPDeclareTargetContext())
5556 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5561 /// Helper method to turn variable array types into constant array
5562 /// types in certain situations which would otherwise be errors (for
5563 /// GCC compatibility).
5564 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5565 ASTContext &Context,
5566 bool &SizeIsNegative,
5567 llvm::APSInt &Oversized) {
5568 // This method tries to turn a variable array into a constant
5569 // array even when the size isn't an ICE. This is necessary
5570 // for compatibility with code that depends on gcc's buggy
5571 // constant expression folding, like struct {char x[(int)(char*)2];}
5572 SizeIsNegative = false;
5575 if (T->isDependentType())
5578 QualifierCollector Qs;
5579 const Type *Ty = Qs.strip(T);
5581 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5582 QualType Pointee = PTy->getPointeeType();
5583 QualType FixedType =
5584 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5586 if (FixedType.isNull()) return FixedType;
5587 FixedType = Context.getPointerType(FixedType);
5588 return Qs.apply(Context, FixedType);
5590 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5591 QualType Inner = PTy->getInnerType();
5592 QualType FixedType =
5593 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5595 if (FixedType.isNull()) return FixedType;
5596 FixedType = Context.getParenType(FixedType);
5597 return Qs.apply(Context, FixedType);
5600 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5603 // FIXME: We should probably handle this case
5604 if (VLATy->getElementType()->isVariablyModifiedType())
5608 if (!VLATy->getSizeExpr() ||
5609 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5612 // Check whether the array size is negative.
5613 if (Res.isSigned() && Res.isNegative()) {
5614 SizeIsNegative = true;
5618 // Check whether the array is too large to be addressed.
5619 unsigned ActiveSizeBits
5620 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5622 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5627 return Context.getConstantArrayType(VLATy->getElementType(),
5628 Res, ArrayType::Normal, 0);
5632 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5633 SrcTL = SrcTL.getUnqualifiedLoc();
5634 DstTL = DstTL.getUnqualifiedLoc();
5635 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5636 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5637 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5638 DstPTL.getPointeeLoc());
5639 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5642 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5643 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5644 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5645 DstPTL.getInnerLoc());
5646 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5647 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5650 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5651 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5652 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5653 TypeLoc DstElemTL = DstATL.getElementLoc();
5654 DstElemTL.initializeFullCopy(SrcElemTL);
5655 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5656 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5657 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5660 /// Helper method to turn variable array types into constant array
5661 /// types in certain situations which would otherwise be errors (for
5662 /// GCC compatibility).
5663 static TypeSourceInfo*
5664 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5665 ASTContext &Context,
5666 bool &SizeIsNegative,
5667 llvm::APSInt &Oversized) {
5669 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5670 SizeIsNegative, Oversized);
5671 if (FixedTy.isNull())
5673 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5674 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5675 FixedTInfo->getTypeLoc());
5679 /// Register the given locally-scoped extern "C" declaration so
5680 /// that it can be found later for redeclarations. We include any extern "C"
5681 /// declaration that is not visible in the translation unit here, not just
5682 /// function-scope declarations.
5684 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5685 if (!getLangOpts().CPlusPlus &&
5686 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5687 // Don't need to track declarations in the TU in C.
5690 // Note that we have a locally-scoped external with this name.
5691 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5694 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5695 // FIXME: We can have multiple results via __attribute__((overloadable)).
5696 auto Result = Context.getExternCContextDecl()->lookup(Name);
5697 return Result.empty() ? nullptr : *Result.begin();
5700 /// Diagnose function specifiers on a declaration of an identifier that
5701 /// does not identify a function.
5702 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5703 // FIXME: We should probably indicate the identifier in question to avoid
5704 // confusion for constructs like "virtual int a(), b;"
5705 if (DS.isVirtualSpecified())
5706 Diag(DS.getVirtualSpecLoc(),
5707 diag::err_virtual_non_function);
5709 if (DS.isExplicitSpecified())
5710 Diag(DS.getExplicitSpecLoc(),
5711 diag::err_explicit_non_function);
5713 if (DS.isNoreturnSpecified())
5714 Diag(DS.getNoreturnSpecLoc(),
5715 diag::err_noreturn_non_function);
5719 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5720 TypeSourceInfo *TInfo, LookupResult &Previous) {
5721 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5722 if (D.getCXXScopeSpec().isSet()) {
5723 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5724 << D.getCXXScopeSpec().getRange();
5726 // Pretend we didn't see the scope specifier.
5731 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5733 if (D.getDeclSpec().isInlineSpecified())
5734 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5735 << getLangOpts().CPlusPlus17;
5736 if (D.getDeclSpec().isConstexprSpecified())
5737 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5740 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5741 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5742 Diag(D.getName().StartLocation,
5743 diag::err_deduction_guide_invalid_specifier)
5746 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5747 << D.getName().getSourceRange();
5751 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5752 if (!NewTD) return nullptr;
5754 // Handle attributes prior to checking for duplicates in MergeVarDecl
5755 ProcessDeclAttributes(S, NewTD, D);
5757 CheckTypedefForVariablyModifiedType(S, NewTD);
5759 bool Redeclaration = D.isRedeclaration();
5760 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5761 D.setRedeclaration(Redeclaration);
5766 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5767 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5768 // then it shall have block scope.
5769 // Note that variably modified types must be fixed before merging the decl so
5770 // that redeclarations will match.
5771 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5772 QualType T = TInfo->getType();
5773 if (T->isVariablyModifiedType()) {
5774 setFunctionHasBranchProtectedScope();
5776 if (S->getFnParent() == nullptr) {
5777 bool SizeIsNegative;
5778 llvm::APSInt Oversized;
5779 TypeSourceInfo *FixedTInfo =
5780 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5784 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5785 NewTD->setTypeSourceInfo(FixedTInfo);
5788 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5789 else if (T->isVariableArrayType())
5790 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5791 else if (Oversized.getBoolValue())
5792 Diag(NewTD->getLocation(), diag::err_array_too_large)
5793 << Oversized.toString(10);
5795 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5796 NewTD->setInvalidDecl();
5802 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5803 /// declares a typedef-name, either using the 'typedef' type specifier or via
5804 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5806 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5807 LookupResult &Previous, bool &Redeclaration) {
5809 // Find the shadowed declaration before filtering for scope.
5810 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5812 // Merge the decl with the existing one if appropriate. If the decl is
5813 // in an outer scope, it isn't the same thing.
5814 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5815 /*AllowInlineNamespace*/false);
5816 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5817 if (!Previous.empty()) {
5818 Redeclaration = true;
5819 MergeTypedefNameDecl(S, NewTD, Previous);
5822 if (ShadowedDecl && !Redeclaration)
5823 CheckShadow(NewTD, ShadowedDecl, Previous);
5825 // If this is the C FILE type, notify the AST context.
5826 if (IdentifierInfo *II = NewTD->getIdentifier())
5827 if (!NewTD->isInvalidDecl() &&
5828 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5829 if (II->isStr("FILE"))
5830 Context.setFILEDecl(NewTD);
5831 else if (II->isStr("jmp_buf"))
5832 Context.setjmp_bufDecl(NewTD);
5833 else if (II->isStr("sigjmp_buf"))
5834 Context.setsigjmp_bufDecl(NewTD);
5835 else if (II->isStr("ucontext_t"))
5836 Context.setucontext_tDecl(NewTD);
5842 /// Determines whether the given declaration is an out-of-scope
5843 /// previous declaration.
5845 /// This routine should be invoked when name lookup has found a
5846 /// previous declaration (PrevDecl) that is not in the scope where a
5847 /// new declaration by the same name is being introduced. If the new
5848 /// declaration occurs in a local scope, previous declarations with
5849 /// linkage may still be considered previous declarations (C99
5850 /// 6.2.2p4-5, C++ [basic.link]p6).
5852 /// \param PrevDecl the previous declaration found by name
5855 /// \param DC the context in which the new declaration is being
5858 /// \returns true if PrevDecl is an out-of-scope previous declaration
5859 /// for a new delcaration with the same name.
5861 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5862 ASTContext &Context) {
5866 if (!PrevDecl->hasLinkage())
5869 if (Context.getLangOpts().CPlusPlus) {
5870 // C++ [basic.link]p6:
5871 // If there is a visible declaration of an entity with linkage
5872 // having the same name and type, ignoring entities declared
5873 // outside the innermost enclosing namespace scope, the block
5874 // scope declaration declares that same entity and receives the
5875 // linkage of the previous declaration.
5876 DeclContext *OuterContext = DC->getRedeclContext();
5877 if (!OuterContext->isFunctionOrMethod())
5878 // This rule only applies to block-scope declarations.
5881 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5882 if (PrevOuterContext->isRecord())
5883 // We found a member function: ignore it.
5886 // Find the innermost enclosing namespace for the new and
5887 // previous declarations.
5888 OuterContext = OuterContext->getEnclosingNamespaceContext();
5889 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5891 // The previous declaration is in a different namespace, so it
5892 // isn't the same function.
5893 if (!OuterContext->Equals(PrevOuterContext))
5900 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5901 CXXScopeSpec &SS = D.getCXXScopeSpec();
5902 if (!SS.isSet()) return;
5903 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5906 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5907 QualType type = decl->getType();
5908 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5909 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5910 // Various kinds of declaration aren't allowed to be __autoreleasing.
5911 unsigned kind = -1U;
5912 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5913 if (var->hasAttr<BlocksAttr>())
5914 kind = 0; // __block
5915 else if (!var->hasLocalStorage())
5917 } else if (isa<ObjCIvarDecl>(decl)) {
5919 } else if (isa<FieldDecl>(decl)) {
5924 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5927 } else if (lifetime == Qualifiers::OCL_None) {
5928 // Try to infer lifetime.
5929 if (!type->isObjCLifetimeType())
5932 lifetime = type->getObjCARCImplicitLifetime();
5933 type = Context.getLifetimeQualifiedType(type, lifetime);
5934 decl->setType(type);
5937 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5938 // Thread-local variables cannot have lifetime.
5939 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5940 var->getTLSKind()) {
5941 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5950 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5951 // Ensure that an auto decl is deduced otherwise the checks below might cache
5952 // the wrong linkage.
5953 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5955 // 'weak' only applies to declarations with external linkage.
5956 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5957 if (!ND.isExternallyVisible()) {
5958 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5959 ND.dropAttr<WeakAttr>();
5962 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5963 if (ND.isExternallyVisible()) {
5964 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5965 ND.dropAttr<WeakRefAttr>();
5966 ND.dropAttr<AliasAttr>();
5970 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5971 if (VD->hasInit()) {
5972 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5973 assert(VD->isThisDeclarationADefinition() &&
5974 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5975 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5976 VD->dropAttr<AliasAttr>();
5981 // 'selectany' only applies to externally visible variable declarations.
5982 // It does not apply to functions.
5983 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5984 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5985 S.Diag(Attr->getLocation(),
5986 diag::err_attribute_selectany_non_extern_data);
5987 ND.dropAttr<SelectAnyAttr>();
5991 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5992 // dll attributes require external linkage. Static locals may have external
5993 // linkage but still cannot be explicitly imported or exported.
5994 auto *VD = dyn_cast<VarDecl>(&ND);
5995 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5996 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5998 ND.setInvalidDecl();
6002 // Virtual functions cannot be marked as 'notail'.
6003 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6004 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6005 if (MD->isVirtual()) {
6006 S.Diag(ND.getLocation(),
6007 diag::err_invalid_attribute_on_virtual_function)
6009 ND.dropAttr<NotTailCalledAttr>();
6013 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6015 bool IsSpecialization,
6016 bool IsDefinition) {
6017 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6020 bool IsTemplate = false;
6021 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6022 OldDecl = OldTD->getTemplatedDecl();
6024 if (!IsSpecialization)
6025 IsDefinition = false;
6027 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6028 NewDecl = NewTD->getTemplatedDecl();
6032 if (!OldDecl || !NewDecl)
6035 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6036 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6037 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6038 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6040 // dllimport and dllexport are inheritable attributes so we have to exclude
6041 // inherited attribute instances.
6042 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6043 (NewExportAttr && !NewExportAttr->isInherited());
6045 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6046 // the only exception being explicit specializations.
6047 // Implicitly generated declarations are also excluded for now because there
6048 // is no other way to switch these to use dllimport or dllexport.
6049 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6051 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6052 // Allow with a warning for free functions and global variables.
6053 bool JustWarn = false;
6054 if (!OldDecl->isCXXClassMember()) {
6055 auto *VD = dyn_cast<VarDecl>(OldDecl);
6056 if (VD && !VD->getDescribedVarTemplate())
6058 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6059 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6063 // We cannot change a declaration that's been used because IR has already
6064 // been emitted. Dllimported functions will still work though (modulo
6065 // address equality) as they can use the thunk.
6066 if (OldDecl->isUsed())
6067 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6070 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6071 : diag::err_attribute_dll_redeclaration;
6072 S.Diag(NewDecl->getLocation(), DiagID)
6074 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6075 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6077 NewDecl->setInvalidDecl();
6082 // A redeclaration is not allowed to drop a dllimport attribute, the only
6083 // exceptions being inline function definitions (except for function
6084 // templates), local extern declarations, qualified friend declarations or
6085 // special MSVC extension: in the last case, the declaration is treated as if
6086 // it were marked dllexport.
6087 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6088 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6089 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6090 // Ignore static data because out-of-line definitions are diagnosed
6092 IsStaticDataMember = VD->isStaticDataMember();
6093 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6094 VarDecl::DeclarationOnly;
6095 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6096 IsInline = FD->isInlined();
6097 IsQualifiedFriend = FD->getQualifier() &&
6098 FD->getFriendObjectKind() == Decl::FOK_Declared;
6101 if (OldImportAttr && !HasNewAttr &&
6102 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6103 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6104 if (IsMicrosoft && IsDefinition) {
6105 S.Diag(NewDecl->getLocation(),
6106 diag::warn_redeclaration_without_import_attribute)
6108 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6109 NewDecl->dropAttr<DLLImportAttr>();
6110 NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6111 NewImportAttr->getRange(), S.Context,
6112 NewImportAttr->getSpellingListIndex()));
6114 S.Diag(NewDecl->getLocation(),
6115 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6116 << NewDecl << OldImportAttr;
6117 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6118 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6119 OldDecl->dropAttr<DLLImportAttr>();
6120 NewDecl->dropAttr<DLLImportAttr>();
6122 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6123 // In MinGW, seeing a function declared inline drops the dllimport
6125 OldDecl->dropAttr<DLLImportAttr>();
6126 NewDecl->dropAttr<DLLImportAttr>();
6127 S.Diag(NewDecl->getLocation(),
6128 diag::warn_dllimport_dropped_from_inline_function)
6129 << NewDecl << OldImportAttr;
6132 // A specialization of a class template member function is processed here
6133 // since it's a redeclaration. If the parent class is dllexport, the
6134 // specialization inherits that attribute. This doesn't happen automatically
6135 // since the parent class isn't instantiated until later.
6136 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6137 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6138 !NewImportAttr && !NewExportAttr) {
6139 if (const DLLExportAttr *ParentExportAttr =
6140 MD->getParent()->getAttr<DLLExportAttr>()) {
6141 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6142 NewAttr->setInherited(true);
6143 NewDecl->addAttr(NewAttr);
6149 /// Given that we are within the definition of the given function,
6150 /// will that definition behave like C99's 'inline', where the
6151 /// definition is discarded except for optimization purposes?
6152 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6153 // Try to avoid calling GetGVALinkageForFunction.
6155 // All cases of this require the 'inline' keyword.
6156 if (!FD->isInlined()) return false;
6158 // This is only possible in C++ with the gnu_inline attribute.
6159 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6162 // Okay, go ahead and call the relatively-more-expensive function.
6163 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6166 /// Determine whether a variable is extern "C" prior to attaching
6167 /// an initializer. We can't just call isExternC() here, because that
6168 /// will also compute and cache whether the declaration is externally
6169 /// visible, which might change when we attach the initializer.
6171 /// This can only be used if the declaration is known to not be a
6172 /// redeclaration of an internal linkage declaration.
6178 /// Attaching the initializer here makes this declaration not externally
6179 /// visible, because its type has internal linkage.
6181 /// FIXME: This is a hack.
6182 template<typename T>
6183 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6184 if (S.getLangOpts().CPlusPlus) {
6185 // In C++, the overloadable attribute negates the effects of extern "C".
6186 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6189 // So do CUDA's host/device attributes.
6190 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6191 D->template hasAttr<CUDAHostAttr>()))
6194 return D->isExternC();
6197 static bool shouldConsiderLinkage(const VarDecl *VD) {
6198 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6199 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6200 return VD->hasExternalStorage();
6201 if (DC->isFileContext())
6205 llvm_unreachable("Unexpected context");
6208 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6209 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6210 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6211 isa<OMPDeclareReductionDecl>(DC))
6215 llvm_unreachable("Unexpected context");
6218 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6219 ParsedAttr::Kind Kind) {
6220 // Check decl attributes on the DeclSpec.
6221 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6224 // Walk the declarator structure, checking decl attributes that were in a type
6225 // position to the decl itself.
6226 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6227 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6231 // Finally, check attributes on the decl itself.
6232 return PD.getAttributes().hasAttribute(Kind);
6235 /// Adjust the \c DeclContext for a function or variable that might be a
6236 /// function-local external declaration.
6237 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6238 if (!DC->isFunctionOrMethod())
6241 // If this is a local extern function or variable declared within a function
6242 // template, don't add it into the enclosing namespace scope until it is
6243 // instantiated; it might have a dependent type right now.
6244 if (DC->isDependentContext())
6247 // C++11 [basic.link]p7:
6248 // When a block scope declaration of an entity with linkage is not found to
6249 // refer to some other declaration, then that entity is a member of the
6250 // innermost enclosing namespace.
6252 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6253 // semantically-enclosing namespace, not a lexically-enclosing one.
6254 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6255 DC = DC->getParent();
6259 /// Returns true if given declaration has external C language linkage.
6260 static bool isDeclExternC(const Decl *D) {
6261 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6262 return FD->isExternC();
6263 if (const auto *VD = dyn_cast<VarDecl>(D))
6264 return VD->isExternC();
6266 llvm_unreachable("Unknown type of decl!");
6269 NamedDecl *Sema::ActOnVariableDeclarator(
6270 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6271 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6272 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6273 QualType R = TInfo->getType();
6274 DeclarationName Name = GetNameForDeclarator(D).getName();
6276 IdentifierInfo *II = Name.getAsIdentifierInfo();
6278 if (D.isDecompositionDeclarator()) {
6279 // Take the name of the first declarator as our name for diagnostic
6281 auto &Decomp = D.getDecompositionDeclarator();
6282 if (!Decomp.bindings().empty()) {
6283 II = Decomp.bindings()[0].Name;
6287 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6291 if (getLangOpts().OpenCL) {
6292 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6293 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6295 if (R->isImageType() || R->isPipeType()) {
6296 Diag(D.getIdentifierLoc(),
6297 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6303 // OpenCL v1.2 s6.9.r:
6304 // The event type cannot be used to declare a program scope variable.
6305 // OpenCL v2.0 s6.9.q:
6306 // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6307 if (NULL == S->getParent()) {
6308 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6309 Diag(D.getIdentifierLoc(),
6310 diag::err_invalid_type_for_program_scope_var) << R;
6316 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6318 while (NR->isPointerType()) {
6319 if (NR->isFunctionPointerType()) {
6320 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6324 NR = NR->getPointeeType();
6327 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6328 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6329 // half array type (unless the cl_khr_fp16 extension is enabled).
6330 if (Context.getBaseElementType(R)->isHalfType()) {
6331 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6336 if (R->isSamplerT()) {
6337 // OpenCL v1.2 s6.9.b p4:
6338 // The sampler type cannot be used with the __local and __global address
6339 // space qualifiers.
6340 if (R.getAddressSpace() == LangAS::opencl_local ||
6341 R.getAddressSpace() == LangAS::opencl_global) {
6342 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6345 // OpenCL v1.2 s6.12.14.1:
6346 // A global sampler must be declared with either the constant address
6347 // space qualifier or with the const qualifier.
6348 if (DC->isTranslationUnit() &&
6349 !(R.getAddressSpace() == LangAS::opencl_constant ||
6350 R.isConstQualified())) {
6351 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6356 // OpenCL v1.2 s6.9.r:
6357 // The event type cannot be used with the __local, __constant and __global
6358 // address space qualifiers.
6359 if (R->isEventT()) {
6360 if (R.getAddressSpace() != LangAS::opencl_private) {
6361 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6366 // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6367 // supported. OpenCL C does not support thread_local either, and
6368 // also reject all other thread storage class specifiers.
6369 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6370 if (TSC != TSCS_unspecified) {
6371 bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6372 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6373 diag::err_opencl_unknown_type_specifier)
6374 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6375 << DeclSpec::getSpecifierName(TSC) << 1;
6381 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6382 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6384 // dllimport globals without explicit storage class are treated as extern. We
6385 // have to change the storage class this early to get the right DeclContext.
6386 if (SC == SC_None && !DC->isRecord() &&
6387 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6388 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6391 DeclContext *OriginalDC = DC;
6392 bool IsLocalExternDecl = SC == SC_Extern &&
6393 adjustContextForLocalExternDecl(DC);
6395 if (SCSpec == DeclSpec::SCS_mutable) {
6396 // mutable can only appear on non-static class members, so it's always
6398 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6403 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6404 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6405 D.getDeclSpec().getStorageClassSpecLoc())) {
6406 // In C++11, the 'register' storage class specifier is deprecated.
6407 // Suppress the warning in system macros, it's used in macros in some
6408 // popular C system headers, such as in glibc's htonl() macro.
6409 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6410 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6411 : diag::warn_deprecated_register)
6412 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6415 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6417 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6418 // C99 6.9p2: The storage-class specifiers auto and register shall not
6419 // appear in the declaration specifiers in an external declaration.
6420 // Global Register+Asm is a GNU extension we support.
6421 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6422 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6427 bool IsMemberSpecialization = false;
6428 bool IsVariableTemplateSpecialization = false;
6429 bool IsPartialSpecialization = false;
6430 bool IsVariableTemplate = false;
6431 VarDecl *NewVD = nullptr;
6432 VarTemplateDecl *NewTemplate = nullptr;
6433 TemplateParameterList *TemplateParams = nullptr;
6434 if (!getLangOpts().CPlusPlus) {
6435 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6436 D.getIdentifierLoc(), II,
6439 if (R->getContainedDeducedType())
6440 ParsingInitForAutoVars.insert(NewVD);
6442 if (D.isInvalidType())
6443 NewVD->setInvalidDecl();
6445 bool Invalid = false;
6447 if (DC->isRecord() && !CurContext->isRecord()) {
6448 // This is an out-of-line definition of a static data member.
6453 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6454 diag::err_static_out_of_line)
6455 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6460 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6461 // to names of variables declared in a block or to function parameters.
6462 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6465 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6466 diag::err_storage_class_for_static_member)
6467 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6469 case SC_PrivateExtern:
6470 llvm_unreachable("C storage class in c++!");
6474 if (SC == SC_Static && CurContext->isRecord()) {
6475 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6476 if (RD->isLocalClass())
6477 Diag(D.getIdentifierLoc(),
6478 diag::err_static_data_member_not_allowed_in_local_class)
6479 << Name << RD->getDeclName();
6481 // C++98 [class.union]p1: If a union contains a static data member,
6482 // the program is ill-formed. C++11 drops this restriction.
6484 Diag(D.getIdentifierLoc(),
6485 getLangOpts().CPlusPlus11
6486 ? diag::warn_cxx98_compat_static_data_member_in_union
6487 : diag::ext_static_data_member_in_union) << Name;
6488 // We conservatively disallow static data members in anonymous structs.
6489 else if (!RD->getDeclName())
6490 Diag(D.getIdentifierLoc(),
6491 diag::err_static_data_member_not_allowed_in_anon_struct)
6492 << Name << RD->isUnion();
6496 // Match up the template parameter lists with the scope specifier, then
6497 // determine whether we have a template or a template specialization.
6498 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6499 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6500 D.getCXXScopeSpec(),
6501 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6502 ? D.getName().TemplateId
6505 /*never a friend*/ false, IsMemberSpecialization, Invalid);
6507 if (TemplateParams) {
6508 if (!TemplateParams->size() &&
6509 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6510 // There is an extraneous 'template<>' for this variable. Complain
6511 // about it, but allow the declaration of the variable.
6512 Diag(TemplateParams->getTemplateLoc(),
6513 diag::err_template_variable_noparams)
6515 << SourceRange(TemplateParams->getTemplateLoc(),
6516 TemplateParams->getRAngleLoc());
6517 TemplateParams = nullptr;
6519 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6520 // This is an explicit specialization or a partial specialization.
6521 // FIXME: Check that we can declare a specialization here.
6522 IsVariableTemplateSpecialization = true;
6523 IsPartialSpecialization = TemplateParams->size() > 0;
6524 } else { // if (TemplateParams->size() > 0)
6525 // This is a template declaration.
6526 IsVariableTemplate = true;
6528 // Check that we can declare a template here.
6529 if (CheckTemplateDeclScope(S, TemplateParams))
6532 // Only C++1y supports variable templates (N3651).
6533 Diag(D.getIdentifierLoc(),
6534 getLangOpts().CPlusPlus14
6535 ? diag::warn_cxx11_compat_variable_template
6536 : diag::ext_variable_template);
6541 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6542 "should have a 'template<>' for this decl");
6545 if (IsVariableTemplateSpecialization) {
6546 SourceLocation TemplateKWLoc =
6547 TemplateParamLists.size() > 0
6548 ? TemplateParamLists[0]->getTemplateLoc()
6550 DeclResult Res = ActOnVarTemplateSpecialization(
6551 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6552 IsPartialSpecialization);
6553 if (Res.isInvalid())
6555 NewVD = cast<VarDecl>(Res.get());
6557 } else if (D.isDecompositionDeclarator()) {
6558 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6559 D.getIdentifierLoc(), R, TInfo, SC,
6562 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6563 D.getIdentifierLoc(), II, R, TInfo, SC);
6565 // If this is supposed to be a variable template, create it as such.
6566 if (IsVariableTemplate) {
6568 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6569 TemplateParams, NewVD);
6570 NewVD->setDescribedVarTemplate(NewTemplate);
6573 // If this decl has an auto type in need of deduction, make a note of the
6574 // Decl so we can diagnose uses of it in its own initializer.
6575 if (R->getContainedDeducedType())
6576 ParsingInitForAutoVars.insert(NewVD);
6578 if (D.isInvalidType() || Invalid) {
6579 NewVD->setInvalidDecl();
6581 NewTemplate->setInvalidDecl();
6584 SetNestedNameSpecifier(NewVD, D);
6586 // If we have any template parameter lists that don't directly belong to
6587 // the variable (matching the scope specifier), store them.
6588 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6589 if (TemplateParamLists.size() > VDTemplateParamLists)
6590 NewVD->setTemplateParameterListsInfo(
6591 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6593 if (D.getDeclSpec().isConstexprSpecified()) {
6594 NewVD->setConstexpr(true);
6595 // C++1z [dcl.spec.constexpr]p1:
6596 // A static data member declared with the constexpr specifier is
6597 // implicitly an inline variable.
6598 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6599 NewVD->setImplicitlyInline();
6603 if (D.getDeclSpec().isInlineSpecified()) {
6604 if (!getLangOpts().CPlusPlus) {
6605 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6607 } else if (CurContext->isFunctionOrMethod()) {
6608 // 'inline' is not allowed on block scope variable declaration.
6609 Diag(D.getDeclSpec().getInlineSpecLoc(),
6610 diag::err_inline_declaration_block_scope) << Name
6611 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6613 Diag(D.getDeclSpec().getInlineSpecLoc(),
6614 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6615 : diag::ext_inline_variable);
6616 NewVD->setInlineSpecified();
6620 // Set the lexical context. If the declarator has a C++ scope specifier, the
6621 // lexical context will be different from the semantic context.
6622 NewVD->setLexicalDeclContext(CurContext);
6624 NewTemplate->setLexicalDeclContext(CurContext);
6626 if (IsLocalExternDecl) {
6627 if (D.isDecompositionDeclarator())
6628 for (auto *B : Bindings)
6629 B->setLocalExternDecl();
6631 NewVD->setLocalExternDecl();
6634 bool EmitTLSUnsupportedError = false;
6635 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6636 // C++11 [dcl.stc]p4:
6637 // When thread_local is applied to a variable of block scope the
6638 // storage-class-specifier static is implied if it does not appear
6640 // Core issue: 'static' is not implied if the variable is declared
6642 if (NewVD->hasLocalStorage() &&
6643 (SCSpec != DeclSpec::SCS_unspecified ||
6644 TSCS != DeclSpec::TSCS_thread_local ||
6645 !DC->isFunctionOrMethod()))
6646 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6647 diag::err_thread_non_global)
6648 << DeclSpec::getSpecifierName(TSCS);
6649 else if (!Context.getTargetInfo().isTLSSupported()) {
6650 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6651 // Postpone error emission until we've collected attributes required to
6652 // figure out whether it's a host or device variable and whether the
6653 // error should be ignored.
6654 EmitTLSUnsupportedError = true;
6655 // We still need to mark the variable as TLS so it shows up in AST with
6656 // proper storage class for other tools to use even if we're not going
6657 // to emit any code for it.
6658 NewVD->setTSCSpec(TSCS);
6660 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6661 diag::err_thread_unsupported);
6663 NewVD->setTSCSpec(TSCS);
6667 // An inline definition of a function with external linkage shall
6668 // not contain a definition of a modifiable object with static or
6669 // thread storage duration...
6670 // We only apply this when the function is required to be defined
6671 // elsewhere, i.e. when the function is not 'extern inline'. Note
6672 // that a local variable with thread storage duration still has to
6673 // be marked 'static'. Also note that it's possible to get these
6674 // semantics in C++ using __attribute__((gnu_inline)).
6675 if (SC == SC_Static && S->getFnParent() != nullptr &&
6676 !NewVD->getType().isConstQualified()) {
6677 FunctionDecl *CurFD = getCurFunctionDecl();
6678 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6679 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6680 diag::warn_static_local_in_extern_inline);
6681 MaybeSuggestAddingStaticToDecl(CurFD);
6685 if (D.getDeclSpec().isModulePrivateSpecified()) {
6686 if (IsVariableTemplateSpecialization)
6687 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6688 << (IsPartialSpecialization ? 1 : 0)
6689 << FixItHint::CreateRemoval(
6690 D.getDeclSpec().getModulePrivateSpecLoc());
6691 else if (IsMemberSpecialization)
6692 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6694 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6695 else if (NewVD->hasLocalStorage())
6696 Diag(NewVD->getLocation(), diag::err_module_private_local)
6697 << 0 << NewVD->getDeclName()
6698 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6699 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6701 NewVD->setModulePrivate();
6703 NewTemplate->setModulePrivate();
6704 for (auto *B : Bindings)
6705 B->setModulePrivate();
6709 // Handle attributes prior to checking for duplicates in MergeVarDecl
6710 ProcessDeclAttributes(S, NewVD, D);
6712 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6713 if (EmitTLSUnsupportedError &&
6714 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6715 (getLangOpts().OpenMPIsDevice &&
6716 NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6717 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6718 diag::err_thread_unsupported);
6719 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6720 // storage [duration]."
6721 if (SC == SC_None && S->getFnParent() != nullptr &&
6722 (NewVD->hasAttr<CUDASharedAttr>() ||
6723 NewVD->hasAttr<CUDAConstantAttr>())) {
6724 NewVD->setStorageClass(SC_Static);
6728 // Ensure that dllimport globals without explicit storage class are treated as
6729 // extern. The storage class is set above using parsed attributes. Now we can
6730 // check the VarDecl itself.
6731 assert(!NewVD->hasAttr<DLLImportAttr>() ||
6732 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6733 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6735 // In auto-retain/release, infer strong retension for variables of
6737 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6738 NewVD->setInvalidDecl();
6740 // Handle GNU asm-label extension (encoded as an attribute).
6741 if (Expr *E = (Expr*)D.getAsmLabel()) {
6742 // The parser guarantees this is a string.
6743 StringLiteral *SE = cast<StringLiteral>(E);
6744 StringRef Label = SE->getString();
6745 if (S->getFnParent() != nullptr) {
6749 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6752 // Local Named register
6753 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6754 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6755 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6759 case SC_PrivateExtern:
6762 } else if (SC == SC_Register) {
6763 // Global Named register
6764 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6765 const auto &TI = Context.getTargetInfo();
6766 bool HasSizeMismatch;
6768 if (!TI.isValidGCCRegisterName(Label))
6769 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6770 else if (!TI.validateGlobalRegisterVariable(Label,
6771 Context.getTypeSize(R),
6773 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6774 else if (HasSizeMismatch)
6775 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6778 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6779 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6780 NewVD->setInvalidDecl(true);
6784 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6785 Context, Label, 0));
6786 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6787 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6788 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6789 if (I != ExtnameUndeclaredIdentifiers.end()) {
6790 if (isDeclExternC(NewVD)) {
6791 NewVD->addAttr(I->second);
6792 ExtnameUndeclaredIdentifiers.erase(I);
6794 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6795 << /*Variable*/1 << NewVD;
6799 // Find the shadowed declaration before filtering for scope.
6800 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6801 ? getShadowedDeclaration(NewVD, Previous)
6804 // Don't consider existing declarations that are in a different
6805 // scope and are out-of-semantic-context declarations (if the new
6806 // declaration has linkage).
6807 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6808 D.getCXXScopeSpec().isNotEmpty() ||
6809 IsMemberSpecialization ||
6810 IsVariableTemplateSpecialization);
6812 // Check whether the previous declaration is in the same block scope. This
6813 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6814 if (getLangOpts().CPlusPlus &&
6815 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6816 NewVD->setPreviousDeclInSameBlockScope(
6817 Previous.isSingleResult() && !Previous.isShadowed() &&
6818 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6820 if (!getLangOpts().CPlusPlus) {
6821 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6823 // If this is an explicit specialization of a static data member, check it.
6824 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6825 CheckMemberSpecialization(NewVD, Previous))
6826 NewVD->setInvalidDecl();
6828 // Merge the decl with the existing one if appropriate.
6829 if (!Previous.empty()) {
6830 if (Previous.isSingleResult() &&
6831 isa<FieldDecl>(Previous.getFoundDecl()) &&
6832 D.getCXXScopeSpec().isSet()) {
6833 // The user tried to define a non-static data member
6834 // out-of-line (C++ [dcl.meaning]p1).
6835 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6836 << D.getCXXScopeSpec().getRange();
6838 NewVD->setInvalidDecl();
6840 } else if (D.getCXXScopeSpec().isSet()) {
6841 // No previous declaration in the qualifying scope.
6842 Diag(D.getIdentifierLoc(), diag::err_no_member)
6843 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6844 << D.getCXXScopeSpec().getRange();
6845 NewVD->setInvalidDecl();
6848 if (!IsVariableTemplateSpecialization)
6849 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6852 VarTemplateDecl *PrevVarTemplate =
6853 NewVD->getPreviousDecl()
6854 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6857 // Check the template parameter list of this declaration, possibly
6858 // merging in the template parameter list from the previous variable
6859 // template declaration.
6860 if (CheckTemplateParameterList(
6862 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6864 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6865 DC->isDependentContext())
6866 ? TPC_ClassTemplateMember
6868 NewVD->setInvalidDecl();
6870 // If we are providing an explicit specialization of a static variable
6871 // template, make a note of that.
6872 if (PrevVarTemplate &&
6873 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6874 PrevVarTemplate->setMemberSpecialization();
6878 // Diagnose shadowed variables iff this isn't a redeclaration.
6879 if (ShadowedDecl && !D.isRedeclaration())
6880 CheckShadow(NewVD, ShadowedDecl, Previous);
6882 ProcessPragmaWeak(S, NewVD);
6884 // If this is the first declaration of an extern C variable, update
6885 // the map of such variables.
6886 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6887 isIncompleteDeclExternC(*this, NewVD))
6888 RegisterLocallyScopedExternCDecl(NewVD, S);
6890 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6891 Decl *ManglingContextDecl;
6892 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6893 NewVD->getDeclContext(), ManglingContextDecl)) {
6894 Context.setManglingNumber(
6895 NewVD, MCtx->getManglingNumber(
6896 NewVD, getMSManglingNumber(getLangOpts(), S)));
6897 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6901 // Special handling of variable named 'main'.
6902 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6903 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6904 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6906 // C++ [basic.start.main]p3
6907 // A program that declares a variable main at global scope is ill-formed.
6908 if (getLangOpts().CPlusPlus)
6909 Diag(D.getLocStart(), diag::err_main_global_variable);
6911 // In C, and external-linkage variable named main results in undefined
6913 else if (NewVD->hasExternalFormalLinkage())
6914 Diag(D.getLocStart(), diag::warn_main_redefined);
6917 if (D.isRedeclaration() && !Previous.empty()) {
6918 NamedDecl *Prev = Previous.getRepresentativeDecl();
6919 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6920 D.isFunctionDefinition());
6924 if (NewVD->isInvalidDecl())
6925 NewTemplate->setInvalidDecl();
6926 ActOnDocumentableDecl(NewTemplate);
6930 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6931 CompleteMemberSpecialization(NewVD, Previous);
6936 /// Enum describing the %select options in diag::warn_decl_shadow.
6937 enum ShadowedDeclKind {
6946 /// Determine what kind of declaration we're shadowing.
6947 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6948 const DeclContext *OldDC) {
6949 if (isa<TypeAliasDecl>(ShadowedDecl))
6951 else if (isa<TypedefDecl>(ShadowedDecl))
6953 else if (isa<RecordDecl>(OldDC))
6954 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6956 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6959 /// Return the location of the capture if the given lambda captures the given
6960 /// variable \p VD, or an invalid source location otherwise.
6961 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6962 const VarDecl *VD) {
6963 for (const Capture &Capture : LSI->Captures) {
6964 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6965 return Capture.getLocation();
6967 return SourceLocation();
6970 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6971 const LookupResult &R) {
6972 // Only diagnose if we're shadowing an unambiguous field or variable.
6973 if (R.getResultKind() != LookupResult::Found)
6976 // Return false if warning is ignored.
6977 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6980 /// Return the declaration shadowed by the given variable \p D, or null
6981 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6982 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6983 const LookupResult &R) {
6984 if (!shouldWarnIfShadowedDecl(Diags, R))
6987 // Don't diagnose declarations at file scope.
6988 if (D->hasGlobalStorage())
6991 NamedDecl *ShadowedDecl = R.getFoundDecl();
6992 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6997 /// Return the declaration shadowed by the given typedef \p D, or null
6998 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6999 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7000 const LookupResult &R) {
7001 // Don't warn if typedef declaration is part of a class
7002 if (D->getDeclContext()->isRecord())
7005 if (!shouldWarnIfShadowedDecl(Diags, R))
7008 NamedDecl *ShadowedDecl = R.getFoundDecl();
7009 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7012 /// Diagnose variable or built-in function shadowing. Implements
7015 /// This method is called whenever a VarDecl is added to a "useful"
7018 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7019 /// \param R the lookup of the name
7021 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7022 const LookupResult &R) {
7023 DeclContext *NewDC = D->getDeclContext();
7025 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7026 // Fields are not shadowed by variables in C++ static methods.
7027 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7031 // Fields shadowed by constructor parameters are a special case. Usually
7032 // the constructor initializes the field with the parameter.
7033 if (isa<CXXConstructorDecl>(NewDC))
7034 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7035 // Remember that this was shadowed so we can either warn about its
7036 // modification or its existence depending on warning settings.
7037 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7042 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7043 if (shadowedVar->isExternC()) {
7044 // For shadowing external vars, make sure that we point to the global
7045 // declaration, not a locally scoped extern declaration.
7046 for (auto I : shadowedVar->redecls())
7047 if (I->isFileVarDecl()) {
7053 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7055 unsigned WarningDiag = diag::warn_decl_shadow;
7056 SourceLocation CaptureLoc;
7057 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7058 isa<CXXMethodDecl>(NewDC)) {
7059 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7060 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7061 if (RD->getLambdaCaptureDefault() == LCD_None) {
7062 // Try to avoid warnings for lambdas with an explicit capture list.
7063 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7064 // Warn only when the lambda captures the shadowed decl explicitly.
7065 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7066 if (CaptureLoc.isInvalid())
7067 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7069 // Remember that this was shadowed so we can avoid the warning if the
7070 // shadowed decl isn't captured and the warning settings allow it.
7071 cast<LambdaScopeInfo>(getCurFunction())
7072 ->ShadowingDecls.push_back(
7073 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7078 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7079 // A variable can't shadow a local variable in an enclosing scope, if
7080 // they are separated by a non-capturing declaration context.
7081 for (DeclContext *ParentDC = NewDC;
7082 ParentDC && !ParentDC->Equals(OldDC);
7083 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7084 // Only block literals, captured statements, and lambda expressions
7085 // can capture; other scopes don't.
7086 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7087 !isLambdaCallOperator(ParentDC)) {
7095 // Only warn about certain kinds of shadowing for class members.
7096 if (NewDC && NewDC->isRecord()) {
7097 // In particular, don't warn about shadowing non-class members.
7098 if (!OldDC->isRecord())
7101 // TODO: should we warn about static data members shadowing
7102 // static data members from base classes?
7104 // TODO: don't diagnose for inaccessible shadowed members.
7105 // This is hard to do perfectly because we might friend the
7106 // shadowing context, but that's just a false negative.
7110 DeclarationName Name = R.getLookupName();
7112 // Emit warning and note.
7113 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7115 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7116 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7117 if (!CaptureLoc.isInvalid())
7118 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7119 << Name << /*explicitly*/ 1;
7120 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7123 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7124 /// when these variables are captured by the lambda.
7125 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7126 for (const auto &Shadow : LSI->ShadowingDecls) {
7127 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7128 // Try to avoid the warning when the shadowed decl isn't captured.
7129 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7130 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7131 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7132 ? diag::warn_decl_shadow_uncaptured_local
7133 : diag::warn_decl_shadow)
7134 << Shadow.VD->getDeclName()
7135 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7136 if (!CaptureLoc.isInvalid())
7137 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7138 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7139 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7143 /// Check -Wshadow without the advantage of a previous lookup.
7144 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7145 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7148 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7149 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7151 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7152 CheckShadow(D, ShadowedDecl, R);
7155 /// Check if 'E', which is an expression that is about to be modified, refers
7156 /// to a constructor parameter that shadows a field.
7157 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7158 // Quickly ignore expressions that can't be shadowing ctor parameters.
7159 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7161 E = E->IgnoreParenImpCasts();
7162 auto *DRE = dyn_cast<DeclRefExpr>(E);
7165 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7166 auto I = ShadowingDecls.find(D);
7167 if (I == ShadowingDecls.end())
7169 const NamedDecl *ShadowedDecl = I->second;
7170 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7171 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7172 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7173 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7175 // Avoid issuing multiple warnings about the same decl.
7176 ShadowingDecls.erase(I);
7179 /// Check for conflict between this global or extern "C" declaration and
7180 /// previous global or extern "C" declarations. This is only used in C++.
7181 template<typename T>
7182 static bool checkGlobalOrExternCConflict(
7183 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7184 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7185 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7187 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7188 // The common case: this global doesn't conflict with any extern "C"
7194 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7195 // Both the old and new declarations have C language linkage. This is a
7198 Previous.addDecl(Prev);
7202 // This is a global, non-extern "C" declaration, and there is a previous
7203 // non-global extern "C" declaration. Diagnose if this is a variable
7205 if (!isa<VarDecl>(ND))
7208 // The declaration is extern "C". Check for any declaration in the
7209 // translation unit which might conflict.
7211 // We have already performed the lookup into the translation unit.
7213 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7215 if (isa<VarDecl>(*I)) {
7221 DeclContext::lookup_result R =
7222 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7223 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7225 if (isa<VarDecl>(*I)) {
7229 // FIXME: If we have any other entity with this name in global scope,
7230 // the declaration is ill-formed, but that is a defect: it breaks the
7231 // 'stat' hack, for instance. Only variables can have mangled name
7232 // clashes with extern "C" declarations, so only they deserve a
7241 // Use the first declaration's location to ensure we point at something which
7242 // is lexically inside an extern "C" linkage-spec.
7243 assert(Prev && "should have found a previous declaration to diagnose");
7244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7245 Prev = FD->getFirstDecl();
7247 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7249 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7251 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7256 /// Apply special rules for handling extern "C" declarations. Returns \c true
7257 /// if we have found that this is a redeclaration of some prior entity.
7259 /// Per C++ [dcl.link]p6:
7260 /// Two declarations [for a function or variable] with C language linkage
7261 /// with the same name that appear in different scopes refer to the same
7262 /// [entity]. An entity with C language linkage shall not be declared with
7263 /// the same name as an entity in global scope.
7264 template<typename T>
7265 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7266 LookupResult &Previous) {
7267 if (!S.getLangOpts().CPlusPlus) {
7268 // In C, when declaring a global variable, look for a corresponding 'extern'
7269 // variable declared in function scope. We don't need this in C++, because
7270 // we find local extern decls in the surrounding file-scope DeclContext.
7271 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7272 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7274 Previous.addDecl(Prev);
7281 // A declaration in the translation unit can conflict with an extern "C"
7283 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7284 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7286 // An extern "C" declaration can conflict with a declaration in the
7287 // translation unit or can be a redeclaration of an extern "C" declaration
7288 // in another scope.
7289 if (isIncompleteDeclExternC(S,ND))
7290 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7292 // Neither global nor extern "C": nothing to do.
7296 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7297 // If the decl is already known invalid, don't check it.
7298 if (NewVD->isInvalidDecl())
7301 QualType T = NewVD->getType();
7303 // Defer checking an 'auto' type until its initializer is attached.
7304 if (T->isUndeducedType())
7307 if (NewVD->hasAttrs())
7308 CheckAlignasUnderalignment(NewVD);
7310 if (T->isObjCObjectType()) {
7311 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7312 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7313 T = Context.getObjCObjectPointerType(T);
7317 // Emit an error if an address space was applied to decl with local storage.
7318 // This includes arrays of objects with address space qualifiers, but not
7319 // automatic variables that point to other address spaces.
7320 // ISO/IEC TR 18037 S5.1.2
7321 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7322 T.getAddressSpace() != LangAS::Default) {
7323 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7324 NewVD->setInvalidDecl();
7328 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7330 if (getLangOpts().OpenCLVersion == 120 &&
7331 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7332 NewVD->isStaticLocal()) {
7333 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7334 NewVD->setInvalidDecl();
7338 if (getLangOpts().OpenCL) {
7339 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7340 if (NewVD->hasAttr<BlocksAttr>()) {
7341 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7345 if (T->isBlockPointerType()) {
7346 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7347 // can't use 'extern' storage class.
7348 if (!T.isConstQualified()) {
7349 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7351 NewVD->setInvalidDecl();
7354 if (NewVD->hasExternalStorage()) {
7355 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7356 NewVD->setInvalidDecl();
7360 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7361 // __constant address space.
7362 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7363 // variables inside a function can also be declared in the global
7365 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7366 NewVD->hasExternalStorage()) {
7367 if (!T->isSamplerT() &&
7368 !(T.getAddressSpace() == LangAS::opencl_constant ||
7369 (T.getAddressSpace() == LangAS::opencl_global &&
7370 getLangOpts().OpenCLVersion == 200))) {
7371 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7372 if (getLangOpts().OpenCLVersion == 200)
7373 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7374 << Scope << "global or constant";
7376 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7377 << Scope << "constant";
7378 NewVD->setInvalidDecl();
7382 if (T.getAddressSpace() == LangAS::opencl_global) {
7383 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7384 << 1 /*is any function*/ << "global";
7385 NewVD->setInvalidDecl();
7388 if (T.getAddressSpace() == LangAS::opencl_constant ||
7389 T.getAddressSpace() == LangAS::opencl_local) {
7390 FunctionDecl *FD = getCurFunctionDecl();
7391 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7393 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7394 if (T.getAddressSpace() == LangAS::opencl_constant)
7395 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7396 << 0 /*non-kernel only*/ << "constant";
7398 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7399 << 0 /*non-kernel only*/ << "local";
7400 NewVD->setInvalidDecl();
7403 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7404 // in the outermost scope of a kernel function.
7405 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7406 if (!getCurScope()->isFunctionScope()) {
7407 if (T.getAddressSpace() == LangAS::opencl_constant)
7408 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7411 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7413 NewVD->setInvalidDecl();
7417 } else if (T.getAddressSpace() != LangAS::opencl_private) {
7418 // Do not allow other address spaces on automatic variable.
7419 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7420 NewVD->setInvalidDecl();
7426 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7427 && !NewVD->hasAttr<BlocksAttr>()) {
7428 if (getLangOpts().getGC() != LangOptions::NonGC)
7429 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7431 assert(!getLangOpts().ObjCAutoRefCount);
7432 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7436 bool isVM = T->isVariablyModifiedType();
7437 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7438 NewVD->hasAttr<BlocksAttr>())
7439 setFunctionHasBranchProtectedScope();
7441 if ((isVM && NewVD->hasLinkage()) ||
7442 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7443 bool SizeIsNegative;
7444 llvm::APSInt Oversized;
7445 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7446 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7448 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
7449 FixedT = FixedTInfo->getType();
7450 else if (FixedTInfo) {
7451 // Type and type-as-written are canonically different. We need to fix up
7452 // both types separately.
7453 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7456 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7457 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7458 // FIXME: This won't give the correct result for
7460 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7462 if (NewVD->isFileVarDecl())
7463 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7465 else if (NewVD->isStaticLocal())
7466 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7469 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7471 NewVD->setInvalidDecl();
7476 if (NewVD->isFileVarDecl())
7477 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7479 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7480 NewVD->setInvalidDecl();
7484 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7485 NewVD->setType(FixedT);
7486 NewVD->setTypeSourceInfo(FixedTInfo);
7489 if (T->isVoidType()) {
7490 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7491 // of objects and functions.
7492 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7493 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7495 NewVD->setInvalidDecl();
7500 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7501 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7502 NewVD->setInvalidDecl();
7506 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7507 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7508 NewVD->setInvalidDecl();
7512 if (NewVD->isConstexpr() && !T->isDependentType() &&
7513 RequireLiteralType(NewVD->getLocation(), T,
7514 diag::err_constexpr_var_non_literal)) {
7515 NewVD->setInvalidDecl();
7520 /// Perform semantic checking on a newly-created variable
7523 /// This routine performs all of the type-checking required for a
7524 /// variable declaration once it has been built. It is used both to
7525 /// check variables after they have been parsed and their declarators
7526 /// have been translated into a declaration, and to check variables
7527 /// that have been instantiated from a template.
7529 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7531 /// Returns true if the variable declaration is a redeclaration.
7532 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7533 CheckVariableDeclarationType(NewVD);
7535 // If the decl is already known invalid, don't check it.
7536 if (NewVD->isInvalidDecl())
7539 // If we did not find anything by this name, look for a non-visible
7540 // extern "C" declaration with the same name.
7541 if (Previous.empty() &&
7542 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7543 Previous.setShadowed();
7545 if (!Previous.empty()) {
7546 MergeVarDecl(NewVD, Previous);
7553 struct FindOverriddenMethod {
7555 CXXMethodDecl *Method;
7557 /// Member lookup function that determines whether a given C++
7558 /// method overrides a method in a base class, to be used with
7559 /// CXXRecordDecl::lookupInBases().
7560 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7561 RecordDecl *BaseRecord =
7562 Specifier->getType()->getAs<RecordType>()->getDecl();
7564 DeclarationName Name = Method->getDeclName();
7566 // FIXME: Do we care about other names here too?
7567 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7568 // We really want to find the base class destructor here.
7569 QualType T = S->Context.getTypeDeclType(BaseRecord);
7570 CanQualType CT = S->Context.getCanonicalType(T);
7572 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7575 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7576 Path.Decls = Path.Decls.slice(1)) {
7577 NamedDecl *D = Path.Decls.front();
7578 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7579 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7588 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7589 } // end anonymous namespace
7591 /// Report an error regarding overriding, along with any relevant
7592 /// overridden methods.
7594 /// \param DiagID the primary error to report.
7595 /// \param MD the overriding method.
7596 /// \param OEK which overrides to include as notes.
7597 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7598 OverrideErrorKind OEK = OEK_All) {
7599 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7600 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7601 // This check (& the OEK parameter) could be replaced by a predicate, but
7602 // without lambdas that would be overkill. This is still nicer than writing
7603 // out the diag loop 3 times.
7604 if ((OEK == OEK_All) ||
7605 (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7606 (OEK == OEK_Deleted && O->isDeleted()))
7607 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7611 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7612 /// and if so, check that it's a valid override and remember it.
7613 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7614 // Look for methods in base classes that this method might override.
7616 FindOverriddenMethod FOM;
7619 bool hasDeletedOverridenMethods = false;
7620 bool hasNonDeletedOverridenMethods = false;
7621 bool AddedAny = false;
7622 if (DC->lookupInBases(FOM, Paths)) {
7623 for (auto *I : Paths.found_decls()) {
7624 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7625 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7626 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7627 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7628 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7629 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7630 hasDeletedOverridenMethods |= OldMD->isDeleted();
7631 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7638 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7639 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7641 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7642 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7649 // Struct for holding all of the extra arguments needed by
7650 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7651 struct ActOnFDArgs {
7654 MultiTemplateParamsArg TemplateParamLists;
7657 } // end anonymous namespace
7661 // Callback to only accept typo corrections that have a non-zero edit distance.
7662 // Also only accept corrections that have the same parent decl.
7663 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7665 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7666 CXXRecordDecl *Parent)
7667 : Context(Context), OriginalFD(TypoFD),
7668 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7670 bool ValidateCandidate(const TypoCorrection &candidate) override {
7671 if (candidate.getEditDistance() == 0)
7674 SmallVector<unsigned, 1> MismatchedParams;
7675 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7676 CDeclEnd = candidate.end();
7677 CDecl != CDeclEnd; ++CDecl) {
7678 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7680 if (FD && !FD->hasBody() &&
7681 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7682 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7683 CXXRecordDecl *Parent = MD->getParent();
7684 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7686 } else if (!ExpectedParent) {
7696 ASTContext &Context;
7697 FunctionDecl *OriginalFD;
7698 CXXRecordDecl *ExpectedParent;
7701 } // end anonymous namespace
7703 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7704 TypoCorrectedFunctionDefinitions.insert(F);
7707 /// Generate diagnostics for an invalid function redeclaration.
7709 /// This routine handles generating the diagnostic messages for an invalid
7710 /// function redeclaration, including finding possible similar declarations
7711 /// or performing typo correction if there are no previous declarations with
7714 /// Returns a NamedDecl iff typo correction was performed and substituting in
7715 /// the new declaration name does not cause new errors.
7716 static NamedDecl *DiagnoseInvalidRedeclaration(
7717 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7718 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7719 DeclarationName Name = NewFD->getDeclName();
7720 DeclContext *NewDC = NewFD->getDeclContext();
7721 SmallVector<unsigned, 1> MismatchedParams;
7722 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7723 TypoCorrection Correction;
7724 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7725 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7726 : diag::err_member_decl_does_not_match;
7727 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7728 IsLocalFriend ? Sema::LookupLocalFriendName
7729 : Sema::LookupOrdinaryName,
7730 Sema::ForVisibleRedeclaration);
7732 NewFD->setInvalidDecl();
7734 SemaRef.LookupName(Prev, S);
7736 SemaRef.LookupQualifiedName(Prev, NewDC);
7737 assert(!Prev.isAmbiguous() &&
7738 "Cannot have an ambiguity in previous-declaration lookup");
7739 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7740 if (!Prev.empty()) {
7741 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7742 Func != FuncEnd; ++Func) {
7743 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7745 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7746 // Add 1 to the index so that 0 can mean the mismatch didn't
7747 // involve a parameter
7749 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7750 NearMatches.push_back(std::make_pair(FD, ParamNum));
7753 // If the qualified name lookup yielded nothing, try typo correction
7754 } else if ((Correction = SemaRef.CorrectTypo(
7755 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7756 &ExtraArgs.D.getCXXScopeSpec(),
7757 llvm::make_unique<DifferentNameValidatorCCC>(
7758 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7759 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7760 // Set up everything for the call to ActOnFunctionDeclarator
7761 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7762 ExtraArgs.D.getIdentifierLoc());
7764 Previous.setLookupName(Correction.getCorrection());
7765 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7766 CDeclEnd = Correction.end();
7767 CDecl != CDeclEnd; ++CDecl) {
7768 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7769 if (FD && !FD->hasBody() &&
7770 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7771 Previous.addDecl(FD);
7774 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7777 // Retry building the function declaration with the new previous
7778 // declarations, and with errors suppressed.
7781 Sema::SFINAETrap Trap(SemaRef);
7783 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7784 // pieces need to verify the typo-corrected C++ declaration and hopefully
7785 // eliminate the need for the parameter pack ExtraArgs.
7786 Result = SemaRef.ActOnFunctionDeclarator(
7787 ExtraArgs.S, ExtraArgs.D,
7788 Correction.getCorrectionDecl()->getDeclContext(),
7789 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7790 ExtraArgs.AddToScope);
7792 if (Trap.hasErrorOccurred())
7797 // Determine which correction we picked.
7798 Decl *Canonical = Result->getCanonicalDecl();
7799 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7801 if ((*I)->getCanonicalDecl() == Canonical)
7802 Correction.setCorrectionDecl(*I);
7804 // Let Sema know about the correction.
7805 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7806 SemaRef.diagnoseTypo(
7808 SemaRef.PDiag(IsLocalFriend
7809 ? diag::err_no_matching_local_friend_suggest
7810 : diag::err_member_decl_does_not_match_suggest)
7811 << Name << NewDC << IsDefinition);
7815 // Pretend the typo correction never occurred
7816 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7817 ExtraArgs.D.getIdentifierLoc());
7818 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7820 Previous.setLookupName(Name);
7823 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7824 << Name << NewDC << IsDefinition << NewFD->getLocation();
7826 bool NewFDisConst = false;
7827 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7828 NewFDisConst = NewMD->isConst();
7830 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7831 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7832 NearMatch != NearMatchEnd; ++NearMatch) {
7833 FunctionDecl *FD = NearMatch->first;
7834 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7835 bool FDisConst = MD && MD->isConst();
7836 bool IsMember = MD || !IsLocalFriend;
7838 // FIXME: These notes are poorly worded for the local friend case.
7839 if (unsigned Idx = NearMatch->second) {
7840 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7841 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7842 if (Loc.isInvalid()) Loc = FD->getLocation();
7843 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7844 : diag::note_local_decl_close_param_match)
7845 << Idx << FDParam->getType()
7846 << NewFD->getParamDecl(Idx - 1)->getType();
7847 } else if (FDisConst != NewFDisConst) {
7848 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7849 << NewFDisConst << FD->getSourceRange().getEnd();
7851 SemaRef.Diag(FD->getLocation(),
7852 IsMember ? diag::note_member_def_close_match
7853 : diag::note_local_decl_close_match);
7858 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7859 switch (D.getDeclSpec().getStorageClassSpec()) {
7860 default: llvm_unreachable("Unknown storage class!");
7861 case DeclSpec::SCS_auto:
7862 case DeclSpec::SCS_register:
7863 case DeclSpec::SCS_mutable:
7864 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7865 diag::err_typecheck_sclass_func);
7866 D.getMutableDeclSpec().ClearStorageClassSpecs();
7869 case DeclSpec::SCS_unspecified: break;
7870 case DeclSpec::SCS_extern:
7871 if (D.getDeclSpec().isExternInLinkageSpec())
7874 case DeclSpec::SCS_static: {
7875 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7877 // The declaration of an identifier for a function that has
7878 // block scope shall have no explicit storage-class specifier
7879 // other than extern
7880 // See also (C++ [dcl.stc]p4).
7881 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7882 diag::err_static_block_func);
7887 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7890 // No explicit storage class has already been returned
7894 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7895 DeclContext *DC, QualType &R,
7896 TypeSourceInfo *TInfo,
7898 bool &IsVirtualOkay) {
7899 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7900 DeclarationName Name = NameInfo.getName();
7902 FunctionDecl *NewFD = nullptr;
7903 bool isInline = D.getDeclSpec().isInlineSpecified();
7905 if (!SemaRef.getLangOpts().CPlusPlus) {
7906 // Determine whether the function was written with a
7907 // prototype. This true when:
7908 // - there is a prototype in the declarator, or
7909 // - the type R of the function is some kind of typedef or other non-
7910 // attributed reference to a type name (which eventually refers to a
7913 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7914 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7916 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7917 D.getLocStart(), NameInfo, R,
7918 TInfo, SC, isInline,
7919 HasPrototype, false);
7920 if (D.isInvalidType())
7921 NewFD->setInvalidDecl();
7926 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7927 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7929 // Check that the return type is not an abstract class type.
7930 // For record types, this is done by the AbstractClassUsageDiagnoser once
7931 // the class has been completely parsed.
7932 if (!DC->isRecord() &&
7933 SemaRef.RequireNonAbstractType(
7934 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7935 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7938 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7939 // This is a C++ constructor declaration.
7940 assert(DC->isRecord() &&
7941 "Constructors can only be declared in a member context");
7943 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7944 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7945 D.getLocStart(), NameInfo,
7946 R, TInfo, isExplicit, isInline,
7947 /*isImplicitlyDeclared=*/false,
7950 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7951 // This is a C++ destructor declaration.
7952 if (DC->isRecord()) {
7953 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7954 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7955 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7956 SemaRef.Context, Record,
7958 NameInfo, R, TInfo, isInline,
7959 /*isImplicitlyDeclared=*/false);
7961 // If the class is complete, then we now create the implicit exception
7962 // specification. If the class is incomplete or dependent, we can't do
7964 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7965 Record->getDefinition() && !Record->isBeingDefined() &&
7966 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7967 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7970 IsVirtualOkay = true;
7974 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7977 // Create a FunctionDecl to satisfy the function definition parsing
7979 return FunctionDecl::Create(SemaRef.Context, DC,
7981 D.getIdentifierLoc(), Name, R, TInfo,
7983 /*hasPrototype=*/true, isConstexpr);
7986 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7987 if (!DC->isRecord()) {
7988 SemaRef.Diag(D.getIdentifierLoc(),
7989 diag::err_conv_function_not_member);
7993 SemaRef.CheckConversionDeclarator(D, R, SC);
7994 IsVirtualOkay = true;
7995 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7996 D.getLocStart(), NameInfo,
7997 R, TInfo, isInline, isExplicit,
7998 isConstexpr, SourceLocation());
8000 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8001 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8003 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
8004 isExplicit, NameInfo, R, TInfo,
8006 } else if (DC->isRecord()) {
8007 // If the name of the function is the same as the name of the record,
8008 // then this must be an invalid constructor that has a return type.
8009 // (The parser checks for a return type and makes the declarator a
8010 // constructor if it has no return type).
8011 if (Name.getAsIdentifierInfo() &&
8012 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8013 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8014 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8015 << SourceRange(D.getIdentifierLoc());
8019 // This is a C++ method declaration.
8020 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
8021 cast<CXXRecordDecl>(DC),
8022 D.getLocStart(), NameInfo, R,
8023 TInfo, SC, isInline,
8024 isConstexpr, SourceLocation());
8025 IsVirtualOkay = !Ret->isStatic();
8029 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8030 if (!isFriend && SemaRef.CurContext->isRecord())
8033 // Determine whether the function was written with a
8034 // prototype. This true when:
8035 // - we're in C++ (where every function has a prototype),
8036 return FunctionDecl::Create(SemaRef.Context, DC,
8038 NameInfo, R, TInfo, SC, isInline,
8039 true/*HasPrototype*/, isConstexpr);
8043 enum OpenCLParamType {
8047 InvalidAddrSpacePtrKernelParam,
8052 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8053 if (PT->isPointerType()) {
8054 QualType PointeeType = PT->getPointeeType();
8055 if (PointeeType->isPointerType())
8056 return PtrPtrKernelParam;
8057 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8058 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8059 PointeeType.getAddressSpace() == LangAS::Default)
8060 return InvalidAddrSpacePtrKernelParam;
8061 return PtrKernelParam;
8064 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
8065 // be used as builtin types.
8067 if (PT->isImageType())
8068 return PtrKernelParam;
8070 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8071 return InvalidKernelParam;
8073 // OpenCL extension spec v1.2 s9.5:
8074 // This extension adds support for half scalar and vector types as built-in
8075 // types that can be used for arithmetic operations, conversions etc.
8076 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8077 return InvalidKernelParam;
8079 if (PT->isRecordType())
8080 return RecordKernelParam;
8082 return ValidKernelParam;
8085 static void checkIsValidOpenCLKernelParameter(
8089 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8090 QualType PT = Param->getType();
8092 // Cache the valid types we encounter to avoid rechecking structs that are
8094 if (ValidTypes.count(PT.getTypePtr()))
8097 switch (getOpenCLKernelParameterType(S, PT)) {
8098 case PtrPtrKernelParam:
8099 // OpenCL v1.2 s6.9.a:
8100 // A kernel function argument cannot be declared as a
8101 // pointer to a pointer type.
8102 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8106 case InvalidAddrSpacePtrKernelParam:
8107 // OpenCL v1.0 s6.5:
8108 // __kernel function arguments declared to be a pointer of a type can point
8109 // to one of the following address spaces only : __global, __local or
8111 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8115 // OpenCL v1.2 s6.9.k:
8116 // Arguments to kernel functions in a program cannot be declared with the
8117 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8118 // uintptr_t or a struct and/or union that contain fields declared to be
8119 // one of these built-in scalar types.
8121 case InvalidKernelParam:
8122 // OpenCL v1.2 s6.8 n:
8123 // A kernel function argument cannot be declared
8125 // Do not diagnose half type since it is diagnosed as invalid argument
8126 // type for any function elsewhere.
8127 if (!PT->isHalfType())
8128 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8132 case PtrKernelParam:
8133 case ValidKernelParam:
8134 ValidTypes.insert(PT.getTypePtr());
8137 case RecordKernelParam:
8141 // Track nested structs we will inspect
8142 SmallVector<const Decl *, 4> VisitStack;
8144 // Track where we are in the nested structs. Items will migrate from
8145 // VisitStack to HistoryStack as we do the DFS for bad field.
8146 SmallVector<const FieldDecl *, 4> HistoryStack;
8147 HistoryStack.push_back(nullptr);
8149 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8150 VisitStack.push_back(PD);
8152 assert(VisitStack.back() && "First decl null?");
8155 const Decl *Next = VisitStack.pop_back_val();
8157 assert(!HistoryStack.empty());
8158 // Found a marker, we have gone up a level
8159 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8160 ValidTypes.insert(Hist->getType().getTypePtr());
8165 // Adds everything except the original parameter declaration (which is not a
8166 // field itself) to the history stack.
8167 const RecordDecl *RD;
8168 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8169 HistoryStack.push_back(Field);
8170 RD = Field->getType()->castAs<RecordType>()->getDecl();
8172 RD = cast<RecordDecl>(Next);
8175 // Add a null marker so we know when we've gone back up a level
8176 VisitStack.push_back(nullptr);
8178 for (const auto *FD : RD->fields()) {
8179 QualType QT = FD->getType();
8181 if (ValidTypes.count(QT.getTypePtr()))
8184 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8185 if (ParamType == ValidKernelParam)
8188 if (ParamType == RecordKernelParam) {
8189 VisitStack.push_back(FD);
8193 // OpenCL v1.2 s6.9.p:
8194 // Arguments to kernel functions that are declared to be a struct or union
8195 // do not allow OpenCL objects to be passed as elements of the struct or
8197 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8198 ParamType == InvalidAddrSpacePtrKernelParam) {
8199 S.Diag(Param->getLocation(),
8200 diag::err_record_with_pointers_kernel_param)
8201 << PT->isUnionType()
8204 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8207 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8208 << PD->getDeclName();
8210 // We have an error, now let's go back up through history and show where
8211 // the offending field came from
8212 for (ArrayRef<const FieldDecl *>::const_iterator
8213 I = HistoryStack.begin() + 1,
8214 E = HistoryStack.end();
8216 const FieldDecl *OuterField = *I;
8217 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8218 << OuterField->getType();
8221 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8222 << QT->isPointerType()
8227 } while (!VisitStack.empty());
8230 /// Find the DeclContext in which a tag is implicitly declared if we see an
8231 /// elaborated type specifier in the specified context, and lookup finds
8233 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8234 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8235 DC = DC->getParent();
8239 /// Find the Scope in which a tag is implicitly declared if we see an
8240 /// elaborated type specifier in the specified context, and lookup finds
8242 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8243 while (S->isClassScope() ||
8244 (LangOpts.CPlusPlus &&
8245 S->isFunctionPrototypeScope()) ||
8246 ((S->getFlags() & Scope::DeclScope) == 0) ||
8247 (S->getEntity() && S->getEntity()->isTransparentContext()))
8253 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8254 TypeSourceInfo *TInfo, LookupResult &Previous,
8255 MultiTemplateParamsArg TemplateParamLists,
8257 QualType R = TInfo->getType();
8259 assert(R->isFunctionType());
8261 // TODO: consider using NameInfo for diagnostic.
8262 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8263 DeclarationName Name = NameInfo.getName();
8264 StorageClass SC = getFunctionStorageClass(*this, D);
8266 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8267 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8268 diag::err_invalid_thread)
8269 << DeclSpec::getSpecifierName(TSCS);
8271 if (D.isFirstDeclarationOfMember())
8272 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8273 D.getIdentifierLoc());
8275 bool isFriend = false;
8276 FunctionTemplateDecl *FunctionTemplate = nullptr;
8277 bool isMemberSpecialization = false;
8278 bool isFunctionTemplateSpecialization = false;
8280 bool isDependentClassScopeExplicitSpecialization = false;
8281 bool HasExplicitTemplateArgs = false;
8282 TemplateArgumentListInfo TemplateArgs;
8284 bool isVirtualOkay = false;
8286 DeclContext *OriginalDC = DC;
8287 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8289 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8291 if (!NewFD) return nullptr;
8293 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8294 NewFD->setTopLevelDeclInObjCContainer();
8296 // Set the lexical context. If this is a function-scope declaration, or has a
8297 // C++ scope specifier, or is the object of a friend declaration, the lexical
8298 // context will be different from the semantic context.
8299 NewFD->setLexicalDeclContext(CurContext);
8301 if (IsLocalExternDecl)
8302 NewFD->setLocalExternDecl();
8304 if (getLangOpts().CPlusPlus) {
8305 bool isInline = D.getDeclSpec().isInlineSpecified();
8306 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8307 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8308 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8309 isFriend = D.getDeclSpec().isFriendSpecified();
8310 if (isFriend && !isInline && D.isFunctionDefinition()) {
8311 // C++ [class.friend]p5
8312 // A function can be defined in a friend declaration of a
8313 // class . . . . Such a function is implicitly inline.
8314 NewFD->setImplicitlyInline();
8317 // If this is a method defined in an __interface, and is not a constructor
8318 // or an overloaded operator, then set the pure flag (isVirtual will already
8320 if (const CXXRecordDecl *Parent =
8321 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8322 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8323 NewFD->setPure(true);
8325 // C++ [class.union]p2
8326 // A union can have member functions, but not virtual functions.
8327 if (isVirtual && Parent->isUnion())
8328 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8331 SetNestedNameSpecifier(NewFD, D);
8332 isMemberSpecialization = false;
8333 isFunctionTemplateSpecialization = false;
8334 if (D.isInvalidType())
8335 NewFD->setInvalidDecl();
8337 // Match up the template parameter lists with the scope specifier, then
8338 // determine whether we have a template or a template specialization.
8339 bool Invalid = false;
8340 if (TemplateParameterList *TemplateParams =
8341 MatchTemplateParametersToScopeSpecifier(
8342 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8343 D.getCXXScopeSpec(),
8344 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8345 ? D.getName().TemplateId
8347 TemplateParamLists, isFriend, isMemberSpecialization,
8349 if (TemplateParams->size() > 0) {
8350 // This is a function template
8352 // Check that we can declare a template here.
8353 if (CheckTemplateDeclScope(S, TemplateParams))
8354 NewFD->setInvalidDecl();
8356 // A destructor cannot be a template.
8357 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8358 Diag(NewFD->getLocation(), diag::err_destructor_template);
8359 NewFD->setInvalidDecl();
8362 // If we're adding a template to a dependent context, we may need to
8363 // rebuilding some of the types used within the template parameter list,
8364 // now that we know what the current instantiation is.
8365 if (DC->isDependentContext()) {
8366 ContextRAII SavedContext(*this, DC);
8367 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8371 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8372 NewFD->getLocation(),
8373 Name, TemplateParams,
8375 FunctionTemplate->setLexicalDeclContext(CurContext);
8376 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8378 // For source fidelity, store the other template param lists.
8379 if (TemplateParamLists.size() > 1) {
8380 NewFD->setTemplateParameterListsInfo(Context,
8381 TemplateParamLists.drop_back(1));
8384 // This is a function template specialization.
8385 isFunctionTemplateSpecialization = true;
8386 // For source fidelity, store all the template param lists.
8387 if (TemplateParamLists.size() > 0)
8388 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8390 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8392 // We want to remove the "template<>", found here.
8393 SourceRange RemoveRange = TemplateParams->getSourceRange();
8395 // If we remove the template<> and the name is not a
8396 // template-id, we're actually silently creating a problem:
8397 // the friend declaration will refer to an untemplated decl,
8398 // and clearly the user wants a template specialization. So
8399 // we need to insert '<>' after the name.
8400 SourceLocation InsertLoc;
8401 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8402 InsertLoc = D.getName().getSourceRange().getEnd();
8403 InsertLoc = getLocForEndOfToken(InsertLoc);
8406 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8407 << Name << RemoveRange
8408 << FixItHint::CreateRemoval(RemoveRange)
8409 << FixItHint::CreateInsertion(InsertLoc, "<>");
8414 // All template param lists were matched against the scope specifier:
8415 // this is NOT (an explicit specialization of) a template.
8416 if (TemplateParamLists.size() > 0)
8417 // For source fidelity, store all the template param lists.
8418 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8422 NewFD->setInvalidDecl();
8423 if (FunctionTemplate)
8424 FunctionTemplate->setInvalidDecl();
8427 // C++ [dcl.fct.spec]p5:
8428 // The virtual specifier shall only be used in declarations of
8429 // nonstatic class member functions that appear within a
8430 // member-specification of a class declaration; see 10.3.
8432 if (isVirtual && !NewFD->isInvalidDecl()) {
8433 if (!isVirtualOkay) {
8434 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8435 diag::err_virtual_non_function);
8436 } else if (!CurContext->isRecord()) {
8437 // 'virtual' was specified outside of the class.
8438 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8439 diag::err_virtual_out_of_class)
8440 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8441 } else if (NewFD->getDescribedFunctionTemplate()) {
8442 // C++ [temp.mem]p3:
8443 // A member function template shall not be virtual.
8444 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8445 diag::err_virtual_member_function_template)
8446 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8448 // Okay: Add virtual to the method.
8449 NewFD->setVirtualAsWritten(true);
8452 if (getLangOpts().CPlusPlus14 &&
8453 NewFD->getReturnType()->isUndeducedType())
8454 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8457 if (getLangOpts().CPlusPlus14 &&
8458 (NewFD->isDependentContext() ||
8459 (isFriend && CurContext->isDependentContext())) &&
8460 NewFD->getReturnType()->isUndeducedType()) {
8461 // If the function template is referenced directly (for instance, as a
8462 // member of the current instantiation), pretend it has a dependent type.
8463 // This is not really justified by the standard, but is the only sane
8465 // FIXME: For a friend function, we have not marked the function as being
8466 // a friend yet, so 'isDependentContext' on the FD doesn't work.
8467 const FunctionProtoType *FPT =
8468 NewFD->getType()->castAs<FunctionProtoType>();
8470 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8471 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8472 FPT->getExtProtoInfo()));
8475 // C++ [dcl.fct.spec]p3:
8476 // The inline specifier shall not appear on a block scope function
8478 if (isInline && !NewFD->isInvalidDecl()) {
8479 if (CurContext->isFunctionOrMethod()) {
8480 // 'inline' is not allowed on block scope function declaration.
8481 Diag(D.getDeclSpec().getInlineSpecLoc(),
8482 diag::err_inline_declaration_block_scope) << Name
8483 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8487 // C++ [dcl.fct.spec]p6:
8488 // The explicit specifier shall be used only in the declaration of a
8489 // constructor or conversion function within its class definition;
8490 // see 12.3.1 and 12.3.2.
8491 if (isExplicit && !NewFD->isInvalidDecl() &&
8492 !isa<CXXDeductionGuideDecl>(NewFD)) {
8493 if (!CurContext->isRecord()) {
8494 // 'explicit' was specified outside of the class.
8495 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8496 diag::err_explicit_out_of_class)
8497 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8498 } else if (!isa<CXXConstructorDecl>(NewFD) &&
8499 !isa<CXXConversionDecl>(NewFD)) {
8500 // 'explicit' was specified on a function that wasn't a constructor
8501 // or conversion function.
8502 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8503 diag::err_explicit_non_ctor_or_conv_function)
8504 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8509 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8510 // are implicitly inline.
8511 NewFD->setImplicitlyInline();
8513 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8514 // be either constructors or to return a literal type. Therefore,
8515 // destructors cannot be declared constexpr.
8516 if (isa<CXXDestructorDecl>(NewFD))
8517 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8520 // If __module_private__ was specified, mark the function accordingly.
8521 if (D.getDeclSpec().isModulePrivateSpecified()) {
8522 if (isFunctionTemplateSpecialization) {
8523 SourceLocation ModulePrivateLoc
8524 = D.getDeclSpec().getModulePrivateSpecLoc();
8525 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8527 << FixItHint::CreateRemoval(ModulePrivateLoc);
8529 NewFD->setModulePrivate();
8530 if (FunctionTemplate)
8531 FunctionTemplate->setModulePrivate();
8536 if (FunctionTemplate) {
8537 FunctionTemplate->setObjectOfFriendDecl();
8538 FunctionTemplate->setAccess(AS_public);
8540 NewFD->setObjectOfFriendDecl();
8541 NewFD->setAccess(AS_public);
8544 // If a function is defined as defaulted or deleted, mark it as such now.
8545 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8546 // definition kind to FDK_Definition.
8547 switch (D.getFunctionDefinitionKind()) {
8548 case FDK_Declaration:
8549 case FDK_Definition:
8553 NewFD->setDefaulted();
8557 NewFD->setDeletedAsWritten();
8561 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8562 D.isFunctionDefinition()) {
8563 // C++ [class.mfct]p2:
8564 // A member function may be defined (8.4) in its class definition, in
8565 // which case it is an inline member function (7.1.2)
8566 NewFD->setImplicitlyInline();
8569 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8570 !CurContext->isRecord()) {
8571 // C++ [class.static]p1:
8572 // A data or function member of a class may be declared static
8573 // in a class definition, in which case it is a static member of
8576 // Complain about the 'static' specifier if it's on an out-of-line
8577 // member function definition.
8578 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8579 diag::err_static_out_of_line)
8580 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8583 // C++11 [except.spec]p15:
8584 // A deallocation function with no exception-specification is treated
8585 // as if it were specified with noexcept(true).
8586 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8587 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8588 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8589 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8590 NewFD->setType(Context.getFunctionType(
8591 FPT->getReturnType(), FPT->getParamTypes(),
8592 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8595 // Filter out previous declarations that don't match the scope.
8596 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8597 D.getCXXScopeSpec().isNotEmpty() ||
8598 isMemberSpecialization ||
8599 isFunctionTemplateSpecialization);
8601 // Handle GNU asm-label extension (encoded as an attribute).
8602 if (Expr *E = (Expr*) D.getAsmLabel()) {
8603 // The parser guarantees this is a string.
8604 StringLiteral *SE = cast<StringLiteral>(E);
8605 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8606 SE->getString(), 0));
8607 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8608 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8609 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8610 if (I != ExtnameUndeclaredIdentifiers.end()) {
8611 if (isDeclExternC(NewFD)) {
8612 NewFD->addAttr(I->second);
8613 ExtnameUndeclaredIdentifiers.erase(I);
8615 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8616 << /*Variable*/0 << NewFD;
8620 // Copy the parameter declarations from the declarator D to the function
8621 // declaration NewFD, if they are available. First scavenge them into Params.
8622 SmallVector<ParmVarDecl*, 16> Params;
8624 if (D.isFunctionDeclarator(FTIIdx)) {
8625 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8627 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8628 // function that takes no arguments, not a function that takes a
8629 // single void argument.
8630 // We let through "const void" here because Sema::GetTypeForDeclarator
8631 // already checks for that case.
8632 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8633 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8634 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8635 assert(Param->getDeclContext() != NewFD && "Was set before ?");
8636 Param->setDeclContext(NewFD);
8637 Params.push_back(Param);
8639 if (Param->isInvalidDecl())
8640 NewFD->setInvalidDecl();
8644 if (!getLangOpts().CPlusPlus) {
8645 // In C, find all the tag declarations from the prototype and move them
8646 // into the function DeclContext. Remove them from the surrounding tag
8647 // injection context of the function, which is typically but not always
8649 DeclContext *PrototypeTagContext =
8650 getTagInjectionContext(NewFD->getLexicalDeclContext());
8651 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8652 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8654 // We don't want to reparent enumerators. Look at their parent enum
8657 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8658 TD = cast<EnumDecl>(ECD->getDeclContext());
8662 DeclContext *TagDC = TD->getLexicalDeclContext();
8663 if (!TagDC->containsDecl(TD))
8665 TagDC->removeDecl(TD);
8666 TD->setDeclContext(NewFD);
8669 // Preserve the lexical DeclContext if it is not the surrounding tag
8670 // injection context of the FD. In this example, the semantic context of
8671 // E will be f and the lexical context will be S, while both the
8672 // semantic and lexical contexts of S will be f:
8673 // void f(struct S { enum E { a } f; } s);
8674 if (TagDC != PrototypeTagContext)
8675 TD->setLexicalDeclContext(TagDC);
8678 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8679 // When we're declaring a function with a typedef, typeof, etc as in the
8680 // following example, we'll need to synthesize (unnamed)
8681 // parameters for use in the declaration.
8684 // typedef void fn(int);
8688 // Synthesize a parameter for each argument type.
8689 for (const auto &AI : FT->param_types()) {
8690 ParmVarDecl *Param =
8691 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8692 Param->setScopeInfo(0, Params.size());
8693 Params.push_back(Param);
8696 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8697 "Should not need args for typedef of non-prototype fn");
8700 // Finally, we know we have the right number of parameters, install them.
8701 NewFD->setParams(Params);
8703 if (D.getDeclSpec().isNoreturnSpecified())
8705 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8708 // Functions returning a variably modified type violate C99 6.7.5.2p2
8709 // because all functions have linkage.
8710 if (!NewFD->isInvalidDecl() &&
8711 NewFD->getReturnType()->isVariablyModifiedType()) {
8712 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8713 NewFD->setInvalidDecl();
8716 // Apply an implicit SectionAttr if '#pragma clang section text' is active
8717 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8718 !NewFD->hasAttr<SectionAttr>()) {
8719 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8720 PragmaClangTextSection.SectionName,
8721 PragmaClangTextSection.PragmaLocation));
8724 // Apply an implicit SectionAttr if #pragma code_seg is active.
8725 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8726 !NewFD->hasAttr<SectionAttr>()) {
8728 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8729 CodeSegStack.CurrentValue->getString(),
8730 CodeSegStack.CurrentPragmaLocation));
8731 if (UnifySection(CodeSegStack.CurrentValue->getString(),
8732 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8733 ASTContext::PSF_Read,
8735 NewFD->dropAttr<SectionAttr>();
8738 // Apply an implicit CodeSegAttr from class declspec or
8739 // apply an implicit SectionAttr from #pragma code_seg if active.
8740 if (!NewFD->hasAttr<CodeSegAttr>()) {
8741 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8742 D.isFunctionDefinition())) {
8743 NewFD->addAttr(SAttr);
8747 // Handle attributes.
8748 ProcessDeclAttributes(S, NewFD, D);
8750 if (getLangOpts().OpenCL) {
8751 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8752 // type declaration will generate a compilation error.
8753 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8754 if (AddressSpace != LangAS::Default) {
8755 Diag(NewFD->getLocation(),
8756 diag::err_opencl_return_value_with_address_space);
8757 NewFD->setInvalidDecl();
8761 if (!getLangOpts().CPlusPlus) {
8762 // Perform semantic checking on the function declaration.
8763 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8764 CheckMain(NewFD, D.getDeclSpec());
8766 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8767 CheckMSVCRTEntryPoint(NewFD);
8769 if (!NewFD->isInvalidDecl())
8770 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8771 isMemberSpecialization));
8772 else if (!Previous.empty())
8773 // Recover gracefully from an invalid redeclaration.
8774 D.setRedeclaration(true);
8775 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8776 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8777 "previous declaration set still overloaded");
8779 // Diagnose no-prototype function declarations with calling conventions that
8780 // don't support variadic calls. Only do this in C and do it after merging
8781 // possibly prototyped redeclarations.
8782 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8783 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8784 CallingConv CC = FT->getExtInfo().getCC();
8785 if (!supportsVariadicCall(CC)) {
8786 // Windows system headers sometimes accidentally use stdcall without
8787 // (void) parameters, so we relax this to a warning.
8789 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8790 Diag(NewFD->getLocation(), DiagID)
8791 << FunctionType::getNameForCallConv(CC);
8795 // C++11 [replacement.functions]p3:
8796 // The program's definitions shall not be specified as inline.
8798 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8800 // Suppress the diagnostic if the function is __attribute__((used)), since
8801 // that forces an external definition to be emitted.
8802 if (D.getDeclSpec().isInlineSpecified() &&
8803 NewFD->isReplaceableGlobalAllocationFunction() &&
8804 !NewFD->hasAttr<UsedAttr>())
8805 Diag(D.getDeclSpec().getInlineSpecLoc(),
8806 diag::ext_operator_new_delete_declared_inline)
8807 << NewFD->getDeclName();
8809 // If the declarator is a template-id, translate the parser's template
8810 // argument list into our AST format.
8811 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8812 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8813 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8814 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8815 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8816 TemplateId->NumArgs);
8817 translateTemplateArguments(TemplateArgsPtr,
8820 HasExplicitTemplateArgs = true;
8822 if (NewFD->isInvalidDecl()) {
8823 HasExplicitTemplateArgs = false;
8824 } else if (FunctionTemplate) {
8825 // Function template with explicit template arguments.
8826 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8827 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8829 HasExplicitTemplateArgs = false;
8831 assert((isFunctionTemplateSpecialization ||
8832 D.getDeclSpec().isFriendSpecified()) &&
8833 "should have a 'template<>' for this decl");
8834 // "friend void foo<>(int);" is an implicit specialization decl.
8835 isFunctionTemplateSpecialization = true;
8837 } else if (isFriend && isFunctionTemplateSpecialization) {
8838 // This combination is only possible in a recovery case; the user
8839 // wrote something like:
8840 // template <> friend void foo(int);
8841 // which we're recovering from as if the user had written:
8842 // friend void foo<>(int);
8843 // Go ahead and fake up a template id.
8844 HasExplicitTemplateArgs = true;
8845 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8846 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8849 // We do not add HD attributes to specializations here because
8850 // they may have different constexpr-ness compared to their
8851 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8852 // may end up with different effective targets. Instead, a
8853 // specialization inherits its target attributes from its template
8854 // in the CheckFunctionTemplateSpecialization() call below.
8855 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8856 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8858 // If it's a friend (and only if it's a friend), it's possible
8859 // that either the specialized function type or the specialized
8860 // template is dependent, and therefore matching will fail. In
8861 // this case, don't check the specialization yet.
8862 bool InstantiationDependent = false;
8863 if (isFunctionTemplateSpecialization && isFriend &&
8864 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8865 TemplateSpecializationType::anyDependentTemplateArguments(
8867 InstantiationDependent))) {
8868 assert(HasExplicitTemplateArgs &&
8869 "friend function specialization without template args");
8870 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8872 NewFD->setInvalidDecl();
8873 } else if (isFunctionTemplateSpecialization) {
8874 if (CurContext->isDependentContext() && CurContext->isRecord()
8876 isDependentClassScopeExplicitSpecialization = true;
8877 } else if (!NewFD->isInvalidDecl() &&
8878 CheckFunctionTemplateSpecialization(
8879 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8881 NewFD->setInvalidDecl();
8884 // A storage-class-specifier shall not be specified in an explicit
8885 // specialization (14.7.3)
8886 FunctionTemplateSpecializationInfo *Info =
8887 NewFD->getTemplateSpecializationInfo();
8888 if (Info && SC != SC_None) {
8889 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8890 Diag(NewFD->getLocation(),
8891 diag::err_explicit_specialization_inconsistent_storage_class)
8893 << FixItHint::CreateRemoval(
8894 D.getDeclSpec().getStorageClassSpecLoc());
8897 Diag(NewFD->getLocation(),
8898 diag::ext_explicit_specialization_storage_class)
8899 << FixItHint::CreateRemoval(
8900 D.getDeclSpec().getStorageClassSpecLoc());
8902 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8903 if (CheckMemberSpecialization(NewFD, Previous))
8904 NewFD->setInvalidDecl();
8907 // Perform semantic checking on the function declaration.
8908 if (!isDependentClassScopeExplicitSpecialization) {
8909 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8910 CheckMain(NewFD, D.getDeclSpec());
8912 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8913 CheckMSVCRTEntryPoint(NewFD);
8915 if (!NewFD->isInvalidDecl())
8916 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8917 isMemberSpecialization));
8918 else if (!Previous.empty())
8919 // Recover gracefully from an invalid redeclaration.
8920 D.setRedeclaration(true);
8923 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8924 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8925 "previous declaration set still overloaded");
8927 NamedDecl *PrincipalDecl = (FunctionTemplate
8928 ? cast<NamedDecl>(FunctionTemplate)
8931 if (isFriend && NewFD->getPreviousDecl()) {
8932 AccessSpecifier Access = AS_public;
8933 if (!NewFD->isInvalidDecl())
8934 Access = NewFD->getPreviousDecl()->getAccess();
8936 NewFD->setAccess(Access);
8937 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8940 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8941 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8942 PrincipalDecl->setNonMemberOperator();
8944 // If we have a function template, check the template parameter
8945 // list. This will check and merge default template arguments.
8946 if (FunctionTemplate) {
8947 FunctionTemplateDecl *PrevTemplate =
8948 FunctionTemplate->getPreviousDecl();
8949 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8950 PrevTemplate ? PrevTemplate->getTemplateParameters()
8952 D.getDeclSpec().isFriendSpecified()
8953 ? (D.isFunctionDefinition()
8954 ? TPC_FriendFunctionTemplateDefinition
8955 : TPC_FriendFunctionTemplate)
8956 : (D.getCXXScopeSpec().isSet() &&
8957 DC && DC->isRecord() &&
8958 DC->isDependentContext())
8959 ? TPC_ClassTemplateMember
8960 : TPC_FunctionTemplate);
8963 if (NewFD->isInvalidDecl()) {
8964 // Ignore all the rest of this.
8965 } else if (!D.isRedeclaration()) {
8966 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8968 // Fake up an access specifier if it's supposed to be a class member.
8969 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8970 NewFD->setAccess(AS_public);
8972 // Qualified decls generally require a previous declaration.
8973 if (D.getCXXScopeSpec().isSet()) {
8974 // ...with the major exception of templated-scope or
8975 // dependent-scope friend declarations.
8977 // TODO: we currently also suppress this check in dependent
8978 // contexts because (1) the parameter depth will be off when
8979 // matching friend templates and (2) we might actually be
8980 // selecting a friend based on a dependent factor. But there
8981 // are situations where these conditions don't apply and we
8982 // can actually do this check immediately.
8984 (TemplateParamLists.size() ||
8985 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8986 CurContext->isDependentContext())) {
8989 // The user tried to provide an out-of-line definition for a
8990 // function that is a member of a class or namespace, but there
8991 // was no such member function declared (C++ [class.mfct]p2,
8992 // C++ [namespace.memdef]p2). For example:
8998 // void X::f() { } // ill-formed
9000 // Complain about this problem, and attempt to suggest close
9001 // matches (e.g., those that differ only in cv-qualifiers and
9002 // whether the parameter types are references).
9004 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9005 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9006 AddToScope = ExtraArgs.AddToScope;
9011 // Unqualified local friend declarations are required to resolve
9013 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9014 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9015 *this, Previous, NewFD, ExtraArgs, true, S)) {
9016 AddToScope = ExtraArgs.AddToScope;
9020 } else if (!D.isFunctionDefinition() &&
9021 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9022 !isFriend && !isFunctionTemplateSpecialization &&
9023 !isMemberSpecialization) {
9024 // An out-of-line member function declaration must also be a
9025 // definition (C++ [class.mfct]p2).
9026 // Note that this is not the case for explicit specializations of
9027 // function templates or member functions of class templates, per
9028 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9029 // extension for compatibility with old SWIG code which likes to
9031 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9032 << D.getCXXScopeSpec().getRange();
9036 ProcessPragmaWeak(S, NewFD);
9037 checkAttributesAfterMerging(*this, *NewFD);
9039 AddKnownFunctionAttributes(NewFD);
9041 if (NewFD->hasAttr<OverloadableAttr>() &&
9042 !NewFD->getType()->getAs<FunctionProtoType>()) {
9043 Diag(NewFD->getLocation(),
9044 diag::err_attribute_overloadable_no_prototype)
9047 // Turn this into a variadic function with no parameters.
9048 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9049 FunctionProtoType::ExtProtoInfo EPI(
9050 Context.getDefaultCallingConvention(true, false));
9051 EPI.Variadic = true;
9052 EPI.ExtInfo = FT->getExtInfo();
9054 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9058 // If there's a #pragma GCC visibility in scope, and this isn't a class
9059 // member, set the visibility of this function.
9060 if (!DC->isRecord() && NewFD->isExternallyVisible())
9061 AddPushedVisibilityAttribute(NewFD);
9063 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9064 // marking the function.
9065 AddCFAuditedAttribute(NewFD);
9067 // If this is a function definition, check if we have to apply optnone due to
9069 if(D.isFunctionDefinition())
9070 AddRangeBasedOptnone(NewFD);
9072 // If this is the first declaration of an extern C variable, update
9073 // the map of such variables.
9074 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9075 isIncompleteDeclExternC(*this, NewFD))
9076 RegisterLocallyScopedExternCDecl(NewFD, S);
9078 // Set this FunctionDecl's range up to the right paren.
9079 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9081 if (D.isRedeclaration() && !Previous.empty()) {
9082 NamedDecl *Prev = Previous.getRepresentativeDecl();
9083 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9084 isMemberSpecialization ||
9085 isFunctionTemplateSpecialization,
9086 D.isFunctionDefinition());
9089 if (getLangOpts().CUDA) {
9090 IdentifierInfo *II = NewFD->getIdentifier();
9092 II->isStr(getLangOpts().HIP ? "hipConfigureCall"
9093 : "cudaConfigureCall") &&
9094 !NewFD->isInvalidDecl() &&
9095 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9096 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9097 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9098 Context.setcudaConfigureCallDecl(NewFD);
9101 // Variadic functions, other than a *declaration* of printf, are not allowed
9102 // in device-side CUDA code, unless someone passed
9103 // -fcuda-allow-variadic-functions.
9104 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9105 (NewFD->hasAttr<CUDADeviceAttr>() ||
9106 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9107 !(II && II->isStr("printf") && NewFD->isExternC() &&
9108 !D.isFunctionDefinition())) {
9109 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9113 MarkUnusedFileScopedDecl(NewFD);
9115 if (getLangOpts().CPlusPlus) {
9116 if (FunctionTemplate) {
9117 if (NewFD->isInvalidDecl())
9118 FunctionTemplate->setInvalidDecl();
9119 return FunctionTemplate;
9122 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9123 CompleteMemberSpecialization(NewFD, Previous);
9126 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9127 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9128 if ((getLangOpts().OpenCLVersion >= 120)
9129 && (SC == SC_Static)) {
9130 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9134 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9135 if (!NewFD->getReturnType()->isVoidType()) {
9136 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9137 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9138 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9143 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9144 for (auto Param : NewFD->parameters())
9145 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9147 for (const ParmVarDecl *Param : NewFD->parameters()) {
9148 QualType PT = Param->getType();
9150 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9152 if (getLangOpts().OpenCLVersion >= 200) {
9153 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9154 QualType ElemTy = PipeTy->getElementType();
9155 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9156 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9163 // Here we have an function template explicit specialization at class scope.
9164 // The actual specialization will be postponed to template instatiation
9165 // time via the ClassScopeFunctionSpecializationDecl node.
9166 if (isDependentClassScopeExplicitSpecialization) {
9167 ClassScopeFunctionSpecializationDecl *NewSpec =
9168 ClassScopeFunctionSpecializationDecl::Create(
9169 Context, CurContext, NewFD->getLocation(),
9170 cast<CXXMethodDecl>(NewFD),
9171 HasExplicitTemplateArgs, TemplateArgs);
9172 CurContext->addDecl(NewSpec);
9176 // Diagnose availability attributes. Availability cannot be used on functions
9177 // that are run during load/unload.
9178 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9179 if (NewFD->hasAttr<ConstructorAttr>()) {
9180 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9182 NewFD->dropAttr<AvailabilityAttr>();
9184 if (NewFD->hasAttr<DestructorAttr>()) {
9185 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9187 NewFD->dropAttr<AvailabilityAttr>();
9194 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
9195 /// when __declspec(code_seg) "is applied to a class, all member functions of
9196 /// the class and nested classes -- this includes compiler-generated special
9197 /// member functions -- are put in the specified segment."
9198 /// The actual behavior is a little more complicated. The Microsoft compiler
9199 /// won't check outer classes if there is an active value from #pragma code_seg.
9200 /// The CodeSeg is always applied from the direct parent but only from outer
9201 /// classes when the #pragma code_seg stack is empty. See:
9202 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9203 /// available since MS has removed the page.
9204 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9205 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9208 const CXXRecordDecl *Parent = Method->getParent();
9209 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9210 Attr *NewAttr = SAttr->clone(S.getASTContext());
9211 NewAttr->setImplicit(true);
9215 // The Microsoft compiler won't check outer classes for the CodeSeg
9216 // when the #pragma code_seg stack is active.
9217 if (S.CodeSegStack.CurrentValue)
9220 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9221 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9222 Attr *NewAttr = SAttr->clone(S.getASTContext());
9223 NewAttr->setImplicit(true);
9230 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9231 /// containing class. Otherwise it will return implicit SectionAttr if the
9232 /// function is a definition and there is an active value on CodeSegStack
9233 /// (from the current #pragma code-seg value).
9235 /// \param FD Function being declared.
9236 /// \param IsDefinition Whether it is a definition or just a declarartion.
9237 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9238 /// nullptr if no attribute should be added.
9239 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9240 bool IsDefinition) {
9241 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9243 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9244 CodeSegStack.CurrentValue) {
9245 return SectionAttr::CreateImplicit(getASTContext(),
9246 SectionAttr::Declspec_allocate,
9247 CodeSegStack.CurrentValue->getString(),
9248 CodeSegStack.CurrentPragmaLocation);
9252 /// Checks if the new declaration declared in dependent context must be
9253 /// put in the same redeclaration chain as the specified declaration.
9255 /// \param D Declaration that is checked.
9256 /// \param PrevDecl Previous declaration found with proper lookup method for the
9257 /// same declaration name.
9258 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9261 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9262 // Any declarations should be put into redeclaration chains except for
9263 // friend declaration in a dependent context that names a function in
9266 // This allows to compile code like:
9269 // template<typename T> class C1 { friend void func() { } };
9270 // template<typename T> class C2 { friend void func() { } };
9272 // This code snippet is a valid code unless both templates are instantiated.
9273 return !(D->getLexicalDeclContext()->isDependentContext() &&
9274 D->getDeclContext()->isFileContext() &&
9275 D->getFriendObjectKind() != Decl::FOK_None);
9278 namespace MultiVersioning {
9279 enum Type { None, Target, CPUSpecific, CPUDispatch};
9280 } // MultiVersionType
9282 static MultiVersioning::Type
9283 getMultiVersionType(const FunctionDecl *FD) {
9284 if (FD->hasAttr<TargetAttr>())
9285 return MultiVersioning::Target;
9286 if (FD->hasAttr<CPUDispatchAttr>())
9287 return MultiVersioning::CPUDispatch;
9288 if (FD->hasAttr<CPUSpecificAttr>())
9289 return MultiVersioning::CPUSpecific;
9290 return MultiVersioning::None;
9292 /// Check the target attribute of the function for MultiVersion
9295 /// Returns true if there was an error, false otherwise.
9296 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9297 const auto *TA = FD->getAttr<TargetAttr>();
9298 assert(TA && "MultiVersion Candidate requires a target attribute");
9299 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9300 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9301 enum ErrType { Feature = 0, Architecture = 1 };
9303 if (!ParseInfo.Architecture.empty() &&
9304 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9305 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9306 << Architecture << ParseInfo.Architecture;
9310 for (const auto &Feat : ParseInfo.Features) {
9311 auto BareFeat = StringRef{Feat}.substr(1);
9312 if (Feat[0] == '-') {
9313 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9314 << Feature << ("no-" + BareFeat).str();
9318 if (!TargetInfo.validateCpuSupports(BareFeat) ||
9319 !TargetInfo.isValidFeatureName(BareFeat)) {
9320 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9321 << Feature << BareFeat;
9328 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9329 const FunctionDecl *NewFD,
9331 MultiVersioning::Type MVType) {
9332 enum DoesntSupport {
9351 bool IsCPUSpecificCPUDispatchMVType =
9352 MVType == MultiVersioning::CPUDispatch ||
9353 MVType == MultiVersioning::CPUSpecific;
9355 if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9356 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9357 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9361 if (!NewFD->getType()->getAs<FunctionProtoType>())
9362 return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9364 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9365 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9367 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9371 // For now, disallow all other attributes. These should be opt-in, but
9372 // an analysis of all of them is a future FIXME.
9373 if (CausesMV && OldFD &&
9374 std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
9375 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9376 << IsCPUSpecificCPUDispatchMVType;
9377 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9381 if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1)
9382 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9383 << IsCPUSpecificCPUDispatchMVType;
9385 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9386 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9387 << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9389 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9390 if (NewCXXFD->isVirtual())
9391 return S.Diag(NewCXXFD->getLocation(),
9392 diag::err_multiversion_doesnt_support)
9393 << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9395 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9396 return S.Diag(NewCXXCtor->getLocation(),
9397 diag::err_multiversion_doesnt_support)
9398 << IsCPUSpecificCPUDispatchMVType << Constructors;
9400 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9401 return S.Diag(NewCXXDtor->getLocation(),
9402 diag::err_multiversion_doesnt_support)
9403 << IsCPUSpecificCPUDispatchMVType << Destructors;
9406 if (NewFD->isDeleted())
9407 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9408 << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9410 if (NewFD->isDefaulted())
9411 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9412 << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9414 if (NewFD->isConstexpr() && (MVType == MultiVersioning::CPUDispatch ||
9415 MVType == MultiVersioning::CPUSpecific))
9416 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9417 << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9419 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9420 const auto *NewType = cast<FunctionType>(NewQType);
9421 QualType NewReturnType = NewType->getReturnType();
9423 if (NewReturnType->isUndeducedType())
9424 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9425 << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9427 // Only allow transition to MultiVersion if it hasn't been used.
9428 if (OldFD && CausesMV && OldFD->isUsed(false))
9429 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9431 // Ensure the return type is identical.
9433 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9434 const auto *OldType = cast<FunctionType>(OldQType);
9435 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9436 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9438 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9439 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9442 QualType OldReturnType = OldType->getReturnType();
9444 if (OldReturnType != NewReturnType)
9445 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9448 if (OldFD->isConstexpr() != NewFD->isConstexpr())
9449 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9452 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9453 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9456 if (OldFD->getStorageClass() != NewFD->getStorageClass())
9457 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9460 if (OldFD->isExternC() != NewFD->isExternC())
9461 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9464 if (S.CheckEquivalentExceptionSpec(
9465 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9466 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9472 /// Check the validity of a multiversion function declaration that is the
9473 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9475 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9477 /// Returns true if there was an error, false otherwise.
9478 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9479 MultiVersioning::Type MVType,
9480 const TargetAttr *TA,
9481 const CPUDispatchAttr *CPUDisp,
9482 const CPUSpecificAttr *CPUSpec) {
9483 assert(MVType != MultiVersioning::None &&
9484 "Function lacks multiversion attribute");
9486 // Target only causes MV if it is default, otherwise this is a normal
9488 if (MVType == MultiVersioning::Target && !TA->isDefaultVersion())
9491 if (MVType == MultiVersioning::Target && CheckMultiVersionValue(S, FD)) {
9492 FD->setInvalidDecl();
9496 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9497 FD->setInvalidDecl();
9501 FD->setIsMultiVersion();
9505 static bool CheckTargetCausesMultiVersioning(
9506 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9507 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9508 LookupResult &Previous) {
9509 const auto *OldTA = OldFD->getAttr<TargetAttr>();
9510 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9511 // Sort order doesn't matter, it just needs to be consistent.
9512 llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9514 // If the old decl is NOT MultiVersioned yet, and we don't cause that
9515 // to change, this is a simple redeclaration.
9516 if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
9519 // Otherwise, this decl causes MultiVersioning.
9520 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9521 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9522 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9523 NewFD->setInvalidDecl();
9527 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9528 MultiVersioning::Target)) {
9529 NewFD->setInvalidDecl();
9533 if (CheckMultiVersionValue(S, NewFD)) {
9534 NewFD->setInvalidDecl();
9538 if (CheckMultiVersionValue(S, OldFD)) {
9539 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9540 NewFD->setInvalidDecl();
9544 TargetAttr::ParsedTargetAttr OldParsed =
9545 OldTA->parse(std::less<std::string>());
9547 if (OldParsed == NewParsed) {
9548 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9549 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9550 NewFD->setInvalidDecl();
9554 for (const auto *FD : OldFD->redecls()) {
9555 const auto *CurTA = FD->getAttr<TargetAttr>();
9556 if (!CurTA || CurTA->isInherited()) {
9557 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9559 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9560 NewFD->setInvalidDecl();
9565 OldFD->setIsMultiVersion();
9566 NewFD->setIsMultiVersion();
9567 Redeclaration = false;
9568 MergeTypeWithPrevious = false;
9574 /// Check the validity of a new function declaration being added to an existing
9575 /// multiversioned declaration collection.
9576 static bool CheckMultiVersionAdditionalDecl(
9577 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9578 MultiVersioning::Type NewMVType, const TargetAttr *NewTA,
9579 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9580 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9581 LookupResult &Previous) {
9583 MultiVersioning::Type OldMVType = getMultiVersionType(OldFD);
9584 // Disallow mixing of multiversioning types.
9585 if ((OldMVType == MultiVersioning::Target &&
9586 NewMVType != MultiVersioning::Target) ||
9587 (NewMVType == MultiVersioning::Target &&
9588 OldMVType != MultiVersioning::Target)) {
9589 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9590 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9591 NewFD->setInvalidDecl();
9595 TargetAttr::ParsedTargetAttr NewParsed;
9597 NewParsed = NewTA->parse();
9598 llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9601 bool UseMemberUsingDeclRules =
9602 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9604 // Next, check ALL non-overloads to see if this is a redeclaration of a
9605 // previous member of the MultiVersion set.
9606 for (NamedDecl *ND : Previous) {
9607 FunctionDecl *CurFD = ND->getAsFunction();
9610 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9613 if (NewMVType == MultiVersioning::Target) {
9614 const auto *CurTA = CurFD->getAttr<TargetAttr>();
9615 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9616 NewFD->setIsMultiVersion();
9617 Redeclaration = true;
9622 TargetAttr::ParsedTargetAttr CurParsed =
9623 CurTA->parse(std::less<std::string>());
9624 if (CurParsed == NewParsed) {
9625 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9626 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9627 NewFD->setInvalidDecl();
9631 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9632 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9633 // Handle CPUDispatch/CPUSpecific versions.
9634 // Only 1 CPUDispatch function is allowed, this will make it go through
9635 // the redeclaration errors.
9636 if (NewMVType == MultiVersioning::CPUDispatch &&
9637 CurFD->hasAttr<CPUDispatchAttr>()) {
9638 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9640 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9641 NewCPUDisp->cpus_begin(),
9642 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9643 return Cur->getName() == New->getName();
9645 NewFD->setIsMultiVersion();
9646 Redeclaration = true;
9651 // If the declarations don't match, this is an error condition.
9652 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9653 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9654 NewFD->setInvalidDecl();
9657 if (NewMVType == MultiVersioning::CPUSpecific && CurCPUSpec) {
9659 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9661 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9662 NewCPUSpec->cpus_begin(),
9663 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9664 return Cur->getName() == New->getName();
9666 NewFD->setIsMultiVersion();
9667 Redeclaration = true;
9672 // Only 1 version of CPUSpecific is allowed for each CPU.
9673 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9674 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9675 if (CurII == NewII) {
9676 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9678 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9679 NewFD->setInvalidDecl();
9685 // If the two decls aren't the same MVType, there is no possible error
9690 // Else, this is simply a non-redecl case. Checking the 'value' is only
9691 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9692 // handled in the attribute adding step.
9693 if (NewMVType == MultiVersioning::Target &&
9694 CheckMultiVersionValue(S, NewFD)) {
9695 NewFD->setInvalidDecl();
9699 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false, NewMVType)) {
9700 NewFD->setInvalidDecl();
9704 NewFD->setIsMultiVersion();
9705 Redeclaration = false;
9706 MergeTypeWithPrevious = false;
9713 /// Check the validity of a mulitversion function declaration.
9714 /// Also sets the multiversion'ness' of the function itself.
9716 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9718 /// Returns true if there was an error, false otherwise.
9719 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9720 bool &Redeclaration, NamedDecl *&OldDecl,
9721 bool &MergeTypeWithPrevious,
9722 LookupResult &Previous) {
9723 const auto *NewTA = NewFD->getAttr<TargetAttr>();
9724 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9725 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9727 // Mixing Multiversioning types is prohibited.
9728 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9729 (NewCPUDisp && NewCPUSpec)) {
9730 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9731 NewFD->setInvalidDecl();
9735 MultiVersioning::Type MVType = getMultiVersionType(NewFD);
9737 // Main isn't allowed to become a multiversion function, however it IS
9738 // permitted to have 'main' be marked with the 'target' optimization hint.
9739 if (NewFD->isMain()) {
9740 if ((MVType == MultiVersioning::Target && NewTA->isDefaultVersion()) ||
9741 MVType == MultiVersioning::CPUDispatch ||
9742 MVType == MultiVersioning::CPUSpecific) {
9743 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9744 NewFD->setInvalidDecl();
9750 if (!OldDecl || !OldDecl->getAsFunction() ||
9751 OldDecl->getDeclContext()->getRedeclContext() !=
9752 NewFD->getDeclContext()->getRedeclContext()) {
9753 // If there's no previous declaration, AND this isn't attempting to cause
9754 // multiversioning, this isn't an error condition.
9755 if (MVType == MultiVersioning::None)
9757 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
9761 FunctionDecl *OldFD = OldDecl->getAsFunction();
9763 if (!OldFD->isMultiVersion() && MVType == MultiVersioning::None)
9766 if (OldFD->isMultiVersion() && MVType == MultiVersioning::None) {
9767 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9768 << (getMultiVersionType(OldFD) != MultiVersioning::Target);
9769 NewFD->setInvalidDecl();
9773 // Handle the target potentially causes multiversioning case.
9774 if (!OldFD->isMultiVersion() && MVType == MultiVersioning::Target)
9775 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9776 Redeclaration, OldDecl,
9777 MergeTypeWithPrevious, Previous);
9778 // Previous declarations lack CPUDispatch/CPUSpecific.
9779 if (!OldFD->isMultiVersion()) {
9780 S.Diag(OldFD->getLocation(), diag::err_multiversion_required_in_redecl)
9782 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9783 NewFD->setInvalidDecl();
9787 // At this point, we have a multiversion function decl (in OldFD) AND an
9788 // appropriate attribute in the current function decl. Resolve that these are
9789 // still compatible with previous declarations.
9790 return CheckMultiVersionAdditionalDecl(
9791 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9792 OldDecl, MergeTypeWithPrevious, Previous);
9795 /// Perform semantic checking of a new function declaration.
9797 /// Performs semantic analysis of the new function declaration
9798 /// NewFD. This routine performs all semantic checking that does not
9799 /// require the actual declarator involved in the declaration, and is
9800 /// used both for the declaration of functions as they are parsed
9801 /// (called via ActOnDeclarator) and for the declaration of functions
9802 /// that have been instantiated via C++ template instantiation (called
9803 /// via InstantiateDecl).
9805 /// \param IsMemberSpecialization whether this new function declaration is
9806 /// a member specialization (that replaces any definition provided by the
9807 /// previous declaration).
9809 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9811 /// \returns true if the function declaration is a redeclaration.
9812 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9813 LookupResult &Previous,
9814 bool IsMemberSpecialization) {
9815 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9816 "Variably modified return types are not handled here");
9818 // Determine whether the type of this function should be merged with
9819 // a previous visible declaration. This never happens for functions in C++,
9820 // and always happens in C if the previous declaration was visible.
9821 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9822 !Previous.isShadowed();
9824 bool Redeclaration = false;
9825 NamedDecl *OldDecl = nullptr;
9826 bool MayNeedOverloadableChecks = false;
9828 // Merge or overload the declaration with an existing declaration of
9829 // the same name, if appropriate.
9830 if (!Previous.empty()) {
9831 // Determine whether NewFD is an overload of PrevDecl or
9832 // a declaration that requires merging. If it's an overload,
9833 // there's no more work to do here; we'll just add the new
9834 // function to the scope.
9835 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9836 NamedDecl *Candidate = Previous.getRepresentativeDecl();
9837 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9838 Redeclaration = true;
9839 OldDecl = Candidate;
9842 MayNeedOverloadableChecks = true;
9843 switch (CheckOverload(S, NewFD, Previous, OldDecl,
9844 /*NewIsUsingDecl*/ false)) {
9846 Redeclaration = true;
9849 case Ovl_NonFunction:
9850 Redeclaration = true;
9854 Redeclaration = false;
9860 // Check for a previous extern "C" declaration with this name.
9861 if (!Redeclaration &&
9862 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9863 if (!Previous.empty()) {
9864 // This is an extern "C" declaration with the same name as a previous
9865 // declaration, and thus redeclares that entity...
9866 Redeclaration = true;
9867 OldDecl = Previous.getFoundDecl();
9868 MergeTypeWithPrevious = false;
9870 // ... except in the presence of __attribute__((overloadable)).
9871 if (OldDecl->hasAttr<OverloadableAttr>() ||
9872 NewFD->hasAttr<OverloadableAttr>()) {
9873 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9874 MayNeedOverloadableChecks = true;
9875 Redeclaration = false;
9882 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
9883 MergeTypeWithPrevious, Previous))
9884 return Redeclaration;
9886 // C++11 [dcl.constexpr]p8:
9887 // A constexpr specifier for a non-static member function that is not
9888 // a constructor declares that member function to be const.
9890 // This needs to be delayed until we know whether this is an out-of-line
9891 // definition of a static member function.
9893 // This rule is not present in C++1y, so we produce a backwards
9894 // compatibility warning whenever it happens in C++11.
9895 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9896 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9897 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9898 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9899 CXXMethodDecl *OldMD = nullptr;
9901 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9902 if (!OldMD || !OldMD->isStatic()) {
9903 const FunctionProtoType *FPT =
9904 MD->getType()->castAs<FunctionProtoType>();
9905 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9906 EPI.TypeQuals |= Qualifiers::Const;
9907 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9908 FPT->getParamTypes(), EPI));
9910 // Warn that we did this, if we're not performing template instantiation.
9911 // In that case, we'll have warned already when the template was defined.
9912 if (!inTemplateInstantiation()) {
9913 SourceLocation AddConstLoc;
9914 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9915 .IgnoreParens().getAs<FunctionTypeLoc>())
9916 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9918 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9919 << FixItHint::CreateInsertion(AddConstLoc, " const");
9924 if (Redeclaration) {
9925 // NewFD and OldDecl represent declarations that need to be
9927 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9928 NewFD->setInvalidDecl();
9929 return Redeclaration;
9933 Previous.addDecl(OldDecl);
9935 if (FunctionTemplateDecl *OldTemplateDecl =
9936 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9937 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
9938 NewFD->setPreviousDeclaration(OldFD);
9939 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9940 FunctionTemplateDecl *NewTemplateDecl
9941 = NewFD->getDescribedFunctionTemplate();
9942 assert(NewTemplateDecl && "Template/non-template mismatch");
9943 if (NewFD->isCXXClassMember()) {
9944 NewFD->setAccess(OldTemplateDecl->getAccess());
9945 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9948 // If this is an explicit specialization of a member that is a function
9949 // template, mark it as a member specialization.
9950 if (IsMemberSpecialization &&
9951 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9952 NewTemplateDecl->setMemberSpecialization();
9953 assert(OldTemplateDecl->isMemberSpecialization());
9954 // Explicit specializations of a member template do not inherit deleted
9955 // status from the parent member template that they are specializing.
9956 if (OldFD->isDeleted()) {
9957 // FIXME: This assert will not hold in the presence of modules.
9958 assert(OldFD->getCanonicalDecl() == OldFD);
9959 // FIXME: We need an update record for this AST mutation.
9960 OldFD->setDeletedAsWritten(false);
9965 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9966 auto *OldFD = cast<FunctionDecl>(OldDecl);
9967 // This needs to happen first so that 'inline' propagates.
9968 NewFD->setPreviousDeclaration(OldFD);
9969 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9970 if (NewFD->isCXXClassMember())
9971 NewFD->setAccess(OldFD->getAccess());
9974 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9975 !NewFD->getAttr<OverloadableAttr>()) {
9976 assert((Previous.empty() ||
9977 llvm::any_of(Previous,
9978 [](const NamedDecl *ND) {
9979 return ND->hasAttr<OverloadableAttr>();
9981 "Non-redecls shouldn't happen without overloadable present");
9983 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9984 const auto *FD = dyn_cast<FunctionDecl>(ND);
9985 return FD && !FD->hasAttr<OverloadableAttr>();
9988 if (OtherUnmarkedIter != Previous.end()) {
9989 Diag(NewFD->getLocation(),
9990 diag::err_attribute_overloadable_multiple_unmarked_overloads);
9991 Diag((*OtherUnmarkedIter)->getLocation(),
9992 diag::note_attribute_overloadable_prev_overload)
9995 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9999 // Semantic checking for this function declaration (in isolation).
10001 if (getLangOpts().CPlusPlus) {
10002 // C++-specific checks.
10003 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10004 CheckConstructor(Constructor);
10005 } else if (CXXDestructorDecl *Destructor =
10006 dyn_cast<CXXDestructorDecl>(NewFD)) {
10007 CXXRecordDecl *Record = Destructor->getParent();
10008 QualType ClassType = Context.getTypeDeclType(Record);
10010 // FIXME: Shouldn't we be able to perform this check even when the class
10011 // type is dependent? Both gcc and edg can handle that.
10012 if (!ClassType->isDependentType()) {
10013 DeclarationName Name
10014 = Context.DeclarationNames.getCXXDestructorName(
10015 Context.getCanonicalType(ClassType));
10016 if (NewFD->getDeclName() != Name) {
10017 Diag(NewFD->getLocation(), diag::err_destructor_name);
10018 NewFD->setInvalidDecl();
10019 return Redeclaration;
10022 } else if (CXXConversionDecl *Conversion
10023 = dyn_cast<CXXConversionDecl>(NewFD)) {
10024 ActOnConversionDeclarator(Conversion);
10025 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10026 if (auto *TD = Guide->getDescribedFunctionTemplate())
10027 CheckDeductionGuideTemplate(TD);
10029 // A deduction guide is not on the list of entities that can be
10030 // explicitly specialized.
10031 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10032 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
10033 << /*explicit specialization*/ 1;
10036 // Find any virtual functions that this function overrides.
10037 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10038 if (!Method->isFunctionTemplateSpecialization() &&
10039 !Method->getDescribedFunctionTemplate() &&
10040 Method->isCanonicalDecl()) {
10041 if (AddOverriddenMethods(Method->getParent(), Method)) {
10042 // If the function was marked as "static", we have a problem.
10043 if (NewFD->getStorageClass() == SC_Static) {
10044 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10049 if (Method->isStatic())
10050 checkThisInStaticMemberFunctionType(Method);
10053 // Extra checking for C++ overloaded operators (C++ [over.oper]).
10054 if (NewFD->isOverloadedOperator() &&
10055 CheckOverloadedOperatorDeclaration(NewFD)) {
10056 NewFD->setInvalidDecl();
10057 return Redeclaration;
10060 // Extra checking for C++0x literal operators (C++0x [over.literal]).
10061 if (NewFD->getLiteralIdentifier() &&
10062 CheckLiteralOperatorDeclaration(NewFD)) {
10063 NewFD->setInvalidDecl();
10064 return Redeclaration;
10067 // In C++, check default arguments now that we have merged decls. Unless
10068 // the lexical context is the class, because in this case this is done
10069 // during delayed parsing anyway.
10070 if (!CurContext->isRecord())
10071 CheckCXXDefaultArguments(NewFD);
10073 // If this function declares a builtin function, check the type of this
10074 // declaration against the expected type for the builtin.
10075 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10076 ASTContext::GetBuiltinTypeError Error;
10077 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10078 QualType T = Context.GetBuiltinType(BuiltinID, Error);
10079 // If the type of the builtin differs only in its exception
10080 // specification, that's OK.
10081 // FIXME: If the types do differ in this way, it would be better to
10082 // retain the 'noexcept' form of the type.
10084 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10086 // The type of this function differs from the type of the builtin,
10087 // so forget about the builtin entirely.
10088 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10091 // If this function is declared as being extern "C", then check to see if
10092 // the function returns a UDT (class, struct, or union type) that is not C
10093 // compatible, and if it does, warn the user.
10094 // But, issue any diagnostic on the first declaration only.
10095 if (Previous.empty() && NewFD->isExternC()) {
10096 QualType R = NewFD->getReturnType();
10097 if (R->isIncompleteType() && !R->isVoidType())
10098 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10100 else if (!R.isPODType(Context) && !R->isVoidType() &&
10101 !R->isObjCObjectPointerType())
10102 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10105 // C++1z [dcl.fct]p6:
10106 // [...] whether the function has a non-throwing exception-specification
10107 // [is] part of the function type
10109 // This results in an ABI break between C++14 and C++17 for functions whose
10110 // declared type includes an exception-specification in a parameter or
10111 // return type. (Exception specifications on the function itself are OK in
10112 // most cases, and exception specifications are not permitted in most other
10113 // contexts where they could make it into a mangling.)
10114 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10115 auto HasNoexcept = [&](QualType T) -> bool {
10116 // Strip off declarator chunks that could be between us and a function
10117 // type. We don't need to look far, exception specifications are very
10118 // restricted prior to C++17.
10119 if (auto *RT = T->getAs<ReferenceType>())
10120 T = RT->getPointeeType();
10121 else if (T->isAnyPointerType())
10122 T = T->getPointeeType();
10123 else if (auto *MPT = T->getAs<MemberPointerType>())
10124 T = MPT->getPointeeType();
10125 if (auto *FPT = T->getAs<FunctionProtoType>())
10126 if (FPT->isNothrow())
10131 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10132 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10133 for (QualType T : FPT->param_types())
10134 AnyNoexcept |= HasNoexcept(T);
10136 Diag(NewFD->getLocation(),
10137 diag::warn_cxx17_compat_exception_spec_in_signature)
10141 if (!Redeclaration && LangOpts.CUDA)
10142 checkCUDATargetOverload(NewFD, Previous);
10144 return Redeclaration;
10147 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10148 // C++11 [basic.start.main]p3:
10149 // A program that [...] declares main to be inline, static or
10150 // constexpr is ill-formed.
10151 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
10152 // appear in a declaration of main.
10153 // static main is not an error under C99, but we should warn about it.
10154 // We accept _Noreturn main as an extension.
10155 if (FD->getStorageClass() == SC_Static)
10156 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10157 ? diag::err_static_main : diag::warn_static_main)
10158 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10159 if (FD->isInlineSpecified())
10160 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10161 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10162 if (DS.isNoreturnSpecified()) {
10163 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10164 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10165 Diag(NoreturnLoc, diag::ext_noreturn_main);
10166 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10167 << FixItHint::CreateRemoval(NoreturnRange);
10169 if (FD->isConstexpr()) {
10170 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10171 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10172 FD->setConstexpr(false);
10175 if (getLangOpts().OpenCL) {
10176 Diag(FD->getLocation(), diag::err_opencl_no_main)
10177 << FD->hasAttr<OpenCLKernelAttr>();
10178 FD->setInvalidDecl();
10182 QualType T = FD->getType();
10183 assert(T->isFunctionType() && "function decl is not of function type");
10184 const FunctionType* FT = T->castAs<FunctionType>();
10186 // Set default calling convention for main()
10187 if (FT->getCallConv() != CC_C) {
10188 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10189 FD->setType(QualType(FT, 0));
10190 T = Context.getCanonicalType(FD->getType());
10193 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10194 // In C with GNU extensions we allow main() to have non-integer return
10195 // type, but we should warn about the extension, and we disable the
10196 // implicit-return-zero rule.
10198 // GCC in C mode accepts qualified 'int'.
10199 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10200 FD->setHasImplicitReturnZero(true);
10202 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10203 SourceRange RTRange = FD->getReturnTypeSourceRange();
10204 if (RTRange.isValid())
10205 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10206 << FixItHint::CreateReplacement(RTRange, "int");
10209 // In C and C++, main magically returns 0 if you fall off the end;
10210 // set the flag which tells us that.
10211 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10213 // All the standards say that main() should return 'int'.
10214 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10215 FD->setHasImplicitReturnZero(true);
10217 // Otherwise, this is just a flat-out error.
10218 SourceRange RTRange = FD->getReturnTypeSourceRange();
10219 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10220 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10222 FD->setInvalidDecl(true);
10226 // Treat protoless main() as nullary.
10227 if (isa<FunctionNoProtoType>(FT)) return;
10229 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10230 unsigned nparams = FTP->getNumParams();
10231 assert(FD->getNumParams() == nparams);
10233 bool HasExtraParameters = (nparams > 3);
10235 if (FTP->isVariadic()) {
10236 Diag(FD->getLocation(), diag::ext_variadic_main);
10237 // FIXME: if we had information about the location of the ellipsis, we
10238 // could add a FixIt hint to remove it as a parameter.
10241 // Darwin passes an undocumented fourth argument of type char**. If
10242 // other platforms start sprouting these, the logic below will start
10244 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10245 HasExtraParameters = false;
10247 if (HasExtraParameters) {
10248 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10249 FD->setInvalidDecl(true);
10253 // FIXME: a lot of the following diagnostics would be improved
10254 // if we had some location information about types.
10257 Context.getPointerType(Context.getPointerType(Context.CharTy));
10258 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10260 for (unsigned i = 0; i < nparams; ++i) {
10261 QualType AT = FTP->getParamType(i);
10263 bool mismatch = true;
10265 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10267 else if (Expected[i] == CharPP) {
10268 // As an extension, the following forms are okay:
10270 // char const * const *
10273 QualifierCollector qs;
10274 const PointerType* PT;
10275 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10276 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10277 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10280 mismatch = !qs.empty();
10285 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10286 // TODO: suggest replacing given type with expected type
10287 FD->setInvalidDecl(true);
10291 if (nparams == 1 && !FD->isInvalidDecl()) {
10292 Diag(FD->getLocation(), diag::warn_main_one_arg);
10295 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10296 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10297 FD->setInvalidDecl();
10301 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10302 QualType T = FD->getType();
10303 assert(T->isFunctionType() && "function decl is not of function type");
10304 const FunctionType *FT = T->castAs<FunctionType>();
10306 // Set an implicit return of 'zero' if the function can return some integral,
10307 // enumeration, pointer or nullptr type.
10308 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10309 FT->getReturnType()->isAnyPointerType() ||
10310 FT->getReturnType()->isNullPtrType())
10311 // DllMain is exempt because a return value of zero means it failed.
10312 if (FD->getName() != "DllMain")
10313 FD->setHasImplicitReturnZero(true);
10315 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10316 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10317 FD->setInvalidDecl();
10321 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10322 // FIXME: Need strict checking. In C89, we need to check for
10323 // any assignment, increment, decrement, function-calls, or
10324 // commas outside of a sizeof. In C99, it's the same list,
10325 // except that the aforementioned are allowed in unevaluated
10326 // expressions. Everything else falls under the
10327 // "may accept other forms of constant expressions" exception.
10328 // (We never end up here for C++, so the constant expression
10329 // rules there don't matter.)
10330 const Expr *Culprit;
10331 if (Init->isConstantInitializer(Context, false, &Culprit))
10333 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10334 << Culprit->getSourceRange();
10339 // Visits an initialization expression to see if OrigDecl is evaluated in
10340 // its own initialization and throws a warning if it does.
10341 class SelfReferenceChecker
10342 : public EvaluatedExprVisitor<SelfReferenceChecker> {
10347 bool isReferenceType;
10350 llvm::SmallVector<unsigned, 4> InitFieldIndex;
10353 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10355 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10356 S(S), OrigDecl(OrigDecl) {
10358 isRecordType = false;
10359 isReferenceType = false;
10360 isInitList = false;
10361 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10362 isPODType = VD->getType().isPODType(S.Context);
10363 isRecordType = VD->getType()->isRecordType();
10364 isReferenceType = VD->getType()->isReferenceType();
10368 // For most expressions, just call the visitor. For initializer lists,
10369 // track the index of the field being initialized since fields are
10370 // initialized in order allowing use of previously initialized fields.
10371 void CheckExpr(Expr *E) {
10372 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10378 // Track and increment the index here.
10380 InitFieldIndex.push_back(0);
10381 for (auto Child : InitList->children()) {
10382 CheckExpr(cast<Expr>(Child));
10383 ++InitFieldIndex.back();
10385 InitFieldIndex.pop_back();
10388 // Returns true if MemberExpr is checked and no further checking is needed.
10389 // Returns false if additional checking is required.
10390 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10391 llvm::SmallVector<FieldDecl*, 4> Fields;
10393 bool ReferenceField = false;
10395 // Get the field memebers used.
10396 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10397 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10400 Fields.push_back(FD);
10401 if (FD->getType()->isReferenceType())
10402 ReferenceField = true;
10403 Base = ME->getBase()->IgnoreParenImpCasts();
10406 // Keep checking only if the base Decl is the same.
10407 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10408 if (!DRE || DRE->getDecl() != OrigDecl)
10411 // A reference field can be bound to an unininitialized field.
10412 if (CheckReference && !ReferenceField)
10415 // Convert FieldDecls to their index number.
10416 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10417 for (const FieldDecl *I : llvm::reverse(Fields))
10418 UsedFieldIndex.push_back(I->getFieldIndex());
10420 // See if a warning is needed by checking the first difference in index
10421 // numbers. If field being used has index less than the field being
10422 // initialized, then the use is safe.
10423 for (auto UsedIter = UsedFieldIndex.begin(),
10424 UsedEnd = UsedFieldIndex.end(),
10425 OrigIter = InitFieldIndex.begin(),
10426 OrigEnd = InitFieldIndex.end();
10427 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10428 if (*UsedIter < *OrigIter)
10430 if (*UsedIter > *OrigIter)
10434 // TODO: Add a different warning which will print the field names.
10435 HandleDeclRefExpr(DRE);
10439 // For most expressions, the cast is directly above the DeclRefExpr.
10440 // For conditional operators, the cast can be outside the conditional
10441 // operator if both expressions are DeclRefExpr's.
10442 void HandleValue(Expr *E) {
10443 E = E->IgnoreParens();
10444 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10445 HandleDeclRefExpr(DRE);
10449 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10450 Visit(CO->getCond());
10451 HandleValue(CO->getTrueExpr());
10452 HandleValue(CO->getFalseExpr());
10456 if (BinaryConditionalOperator *BCO =
10457 dyn_cast<BinaryConditionalOperator>(E)) {
10458 Visit(BCO->getCond());
10459 HandleValue(BCO->getFalseExpr());
10463 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10464 HandleValue(OVE->getSourceExpr());
10468 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10469 if (BO->getOpcode() == BO_Comma) {
10470 Visit(BO->getLHS());
10471 HandleValue(BO->getRHS());
10476 if (isa<MemberExpr>(E)) {
10478 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10479 false /*CheckReference*/))
10483 Expr *Base = E->IgnoreParenImpCasts();
10484 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10485 // Check for static member variables and don't warn on them.
10486 if (!isa<FieldDecl>(ME->getMemberDecl()))
10488 Base = ME->getBase()->IgnoreParenImpCasts();
10490 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10491 HandleDeclRefExpr(DRE);
10498 // Reference types not handled in HandleValue are handled here since all
10499 // uses of references are bad, not just r-value uses.
10500 void VisitDeclRefExpr(DeclRefExpr *E) {
10501 if (isReferenceType)
10502 HandleDeclRefExpr(E);
10505 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10506 if (E->getCastKind() == CK_LValueToRValue) {
10507 HandleValue(E->getSubExpr());
10511 Inherited::VisitImplicitCastExpr(E);
10514 void VisitMemberExpr(MemberExpr *E) {
10516 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10520 // Don't warn on arrays since they can be treated as pointers.
10521 if (E->getType()->canDecayToPointerType()) return;
10523 // Warn when a non-static method call is followed by non-static member
10524 // field accesses, which is followed by a DeclRefExpr.
10525 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10526 bool Warn = (MD && !MD->isStatic());
10527 Expr *Base = E->getBase()->IgnoreParenImpCasts();
10528 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10529 if (!isa<FieldDecl>(ME->getMemberDecl()))
10531 Base = ME->getBase()->IgnoreParenImpCasts();
10534 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10536 HandleDeclRefExpr(DRE);
10540 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10541 // Visit that expression.
10545 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10546 Expr *Callee = E->getCallee();
10548 if (isa<UnresolvedLookupExpr>(Callee))
10549 return Inherited::VisitCXXOperatorCallExpr(E);
10552 for (auto Arg: E->arguments())
10553 HandleValue(Arg->IgnoreParenImpCasts());
10556 void VisitUnaryOperator(UnaryOperator *E) {
10557 // For POD record types, addresses of its own members are well-defined.
10558 if (E->getOpcode() == UO_AddrOf && isRecordType &&
10559 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10561 HandleValue(E->getSubExpr());
10565 if (E->isIncrementDecrementOp()) {
10566 HandleValue(E->getSubExpr());
10570 Inherited::VisitUnaryOperator(E);
10573 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10575 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10576 if (E->getConstructor()->isCopyConstructor()) {
10577 Expr *ArgExpr = E->getArg(0);
10578 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10579 if (ILE->getNumInits() == 1)
10580 ArgExpr = ILE->getInit(0);
10581 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10582 if (ICE->getCastKind() == CK_NoOp)
10583 ArgExpr = ICE->getSubExpr();
10584 HandleValue(ArgExpr);
10587 Inherited::VisitCXXConstructExpr(E);
10590 void VisitCallExpr(CallExpr *E) {
10591 // Treat std::move as a use.
10592 if (E->isCallToStdMove()) {
10593 HandleValue(E->getArg(0));
10597 Inherited::VisitCallExpr(E);
10600 void VisitBinaryOperator(BinaryOperator *E) {
10601 if (E->isCompoundAssignmentOp()) {
10602 HandleValue(E->getLHS());
10603 Visit(E->getRHS());
10607 Inherited::VisitBinaryOperator(E);
10610 // A custom visitor for BinaryConditionalOperator is needed because the
10611 // regular visitor would check the condition and true expression separately
10612 // but both point to the same place giving duplicate diagnostics.
10613 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10614 Visit(E->getCond());
10615 Visit(E->getFalseExpr());
10618 void HandleDeclRefExpr(DeclRefExpr *DRE) {
10619 Decl* ReferenceDecl = DRE->getDecl();
10620 if (OrigDecl != ReferenceDecl) return;
10622 if (isReferenceType) {
10623 diag = diag::warn_uninit_self_reference_in_reference_init;
10624 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10625 diag = diag::warn_static_self_reference_in_init;
10626 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10627 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10628 DRE->getDecl()->getType()->isRecordType()) {
10629 diag = diag::warn_uninit_self_reference_in_init;
10631 // Local variables will be handled by the CFG analysis.
10635 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10638 << OrigDecl->getLocation()
10639 << DRE->getSourceRange());
10643 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10644 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10646 // Parameters arguments are occassionially constructed with itself,
10647 // for instance, in recursive functions. Skip them.
10648 if (isa<ParmVarDecl>(OrigDecl))
10651 E = E->IgnoreParens();
10653 // Skip checking T a = a where T is not a record or reference type.
10654 // Doing so is a way to silence uninitialized warnings.
10655 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10656 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10657 if (ICE->getCastKind() == CK_LValueToRValue)
10658 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10659 if (DRE->getDecl() == OrigDecl)
10662 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10664 } // end anonymous namespace
10667 // Simple wrapper to add the name of a variable or (if no variable is
10668 // available) a DeclarationName into a diagnostic.
10669 struct VarDeclOrName {
10671 DeclarationName Name;
10673 friend const Sema::SemaDiagnosticBuilder &
10674 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10675 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10678 } // end anonymous namespace
10680 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10681 DeclarationName Name, QualType Type,
10682 TypeSourceInfo *TSI,
10683 SourceRange Range, bool DirectInit,
10685 bool IsInitCapture = !VDecl;
10686 assert((!VDecl || !VDecl->isInitCapture()) &&
10687 "init captures are expected to be deduced prior to initialization");
10689 VarDeclOrName VN{VDecl, Name};
10691 DeducedType *Deduced = Type->getContainedDeducedType();
10692 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10694 // C++11 [dcl.spec.auto]p3
10696 assert(VDecl && "no init for init capture deduction?");
10698 // Except for class argument deduction, and then for an initializing
10699 // declaration only, i.e. no static at class scope or extern.
10700 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10701 VDecl->hasExternalStorage() ||
10702 VDecl->isStaticDataMember()) {
10703 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10704 << VDecl->getDeclName() << Type;
10709 ArrayRef<Expr*> DeduceInits;
10711 DeduceInits = Init;
10714 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10715 DeduceInits = PL->exprs();
10718 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10719 assert(VDecl && "non-auto type for init capture deduction?");
10720 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10721 InitializationKind Kind = InitializationKind::CreateForInit(
10722 VDecl->getLocation(), DirectInit, Init);
10723 // FIXME: Initialization should not be taking a mutable list of inits.
10724 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10725 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10730 if (auto *IL = dyn_cast<InitListExpr>(Init))
10731 DeduceInits = IL->inits();
10734 // Deduction only works if we have exactly one source expression.
10735 if (DeduceInits.empty()) {
10736 // It isn't possible to write this directly, but it is possible to
10737 // end up in this situation with "auto x(some_pack...);"
10738 Diag(Init->getLocStart(), IsInitCapture
10739 ? diag::err_init_capture_no_expression
10740 : diag::err_auto_var_init_no_expression)
10741 << VN << Type << Range;
10745 if (DeduceInits.size() > 1) {
10746 Diag(DeduceInits[1]->getLocStart(),
10747 IsInitCapture ? diag::err_init_capture_multiple_expressions
10748 : diag::err_auto_var_init_multiple_expressions)
10749 << VN << Type << Range;
10753 Expr *DeduceInit = DeduceInits[0];
10754 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10755 Diag(Init->getLocStart(), IsInitCapture
10756 ? diag::err_init_capture_paren_braces
10757 : diag::err_auto_var_init_paren_braces)
10758 << isa<InitListExpr>(Init) << VN << Type << Range;
10762 // Expressions default to 'id' when we're in a debugger.
10763 bool DefaultedAnyToId = false;
10764 if (getLangOpts().DebuggerCastResultToId &&
10765 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10766 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10767 if (Result.isInvalid()) {
10770 Init = Result.get();
10771 DefaultedAnyToId = true;
10774 // C++ [dcl.decomp]p1:
10775 // If the assignment-expression [...] has array type A and no ref-qualifier
10776 // is present, e has type cv A
10777 if (VDecl && isa<DecompositionDecl>(VDecl) &&
10778 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10779 DeduceInit->getType()->isConstantArrayType())
10780 return Context.getQualifiedType(DeduceInit->getType(),
10781 Type.getQualifiers());
10783 QualType DeducedType;
10784 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10785 if (!IsInitCapture)
10786 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10787 else if (isa<InitListExpr>(Init))
10788 Diag(Range.getBegin(),
10789 diag::err_init_capture_deduction_failure_from_init_list)
10791 << (DeduceInit->getType().isNull() ? TSI->getType()
10792 : DeduceInit->getType())
10793 << DeduceInit->getSourceRange();
10795 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10796 << VN << TSI->getType()
10797 << (DeduceInit->getType().isNull() ? TSI->getType()
10798 : DeduceInit->getType())
10799 << DeduceInit->getSourceRange();
10802 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10803 // 'id' instead of a specific object type prevents most of our usual
10805 // We only want to warn outside of template instantiations, though:
10806 // inside a template, the 'id' could have come from a parameter.
10807 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10808 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10809 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10810 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10813 return DeducedType;
10816 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10818 QualType DeducedType = deduceVarTypeFromInitializer(
10819 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10820 VDecl->getSourceRange(), DirectInit, Init);
10821 if (DeducedType.isNull()) {
10822 VDecl->setInvalidDecl();
10826 VDecl->setType(DeducedType);
10827 assert(VDecl->isLinkageValid());
10829 // In ARC, infer lifetime.
10830 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10831 VDecl->setInvalidDecl();
10833 // If this is a redeclaration, check that the type we just deduced matches
10834 // the previously declared type.
10835 if (VarDecl *Old = VDecl->getPreviousDecl()) {
10836 // We never need to merge the type, because we cannot form an incomplete
10837 // array of auto, nor deduce such a type.
10838 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10841 // Check the deduced type is valid for a variable declaration.
10842 CheckVariableDeclarationType(VDecl);
10843 return VDecl->isInvalidDecl();
10846 /// AddInitializerToDecl - Adds the initializer Init to the
10847 /// declaration dcl. If DirectInit is true, this is C++ direct
10848 /// initialization rather than copy initialization.
10849 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10850 // If there is no declaration, there was an error parsing it. Just ignore
10851 // the initializer.
10852 if (!RealDecl || RealDecl->isInvalidDecl()) {
10853 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10857 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10858 // Pure-specifiers are handled in ActOnPureSpecifier.
10859 Diag(Method->getLocation(), diag::err_member_function_initialization)
10860 << Method->getDeclName() << Init->getSourceRange();
10861 Method->setInvalidDecl();
10865 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10867 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10868 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10869 RealDecl->setInvalidDecl();
10873 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10874 if (VDecl->getType()->isUndeducedType()) {
10875 // Attempt typo correction early so that the type of the init expression can
10876 // be deduced based on the chosen correction if the original init contains a
10878 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10879 if (!Res.isUsable()) {
10880 RealDecl->setInvalidDecl();
10885 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10889 // dllimport cannot be used on variable definitions.
10890 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10891 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10892 VDecl->setInvalidDecl();
10896 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10897 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10898 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10899 VDecl->setInvalidDecl();
10903 if (!VDecl->getType()->isDependentType()) {
10904 // A definition must end up with a complete type, which means it must be
10905 // complete with the restriction that an array type might be completed by
10906 // the initializer; note that later code assumes this restriction.
10907 QualType BaseDeclType = VDecl->getType();
10908 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10909 BaseDeclType = Array->getElementType();
10910 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10911 diag::err_typecheck_decl_incomplete_type)) {
10912 RealDecl->setInvalidDecl();
10916 // The variable can not have an abstract class type.
10917 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10918 diag::err_abstract_type_in_decl,
10919 AbstractVariableType))
10920 VDecl->setInvalidDecl();
10923 // If adding the initializer will turn this declaration into a definition,
10924 // and we already have a definition for this variable, diagnose or otherwise
10925 // handle the situation.
10927 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10928 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10929 !VDecl->isThisDeclarationADemotedDefinition() &&
10930 checkVarDeclRedefinition(Def, VDecl))
10933 if (getLangOpts().CPlusPlus) {
10934 // C++ [class.static.data]p4
10935 // If a static data member is of const integral or const
10936 // enumeration type, its declaration in the class definition can
10937 // specify a constant-initializer which shall be an integral
10938 // constant expression (5.19). In that case, the member can appear
10939 // in integral constant expressions. The member shall still be
10940 // defined in a namespace scope if it is used in the program and the
10941 // namespace scope definition shall not contain an initializer.
10943 // We already performed a redefinition check above, but for static
10944 // data members we also need to check whether there was an in-class
10945 // declaration with an initializer.
10946 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10947 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10948 << VDecl->getDeclName();
10949 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10950 diag::note_previous_initializer)
10955 if (VDecl->hasLocalStorage())
10956 setFunctionHasBranchProtectedScope();
10958 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10959 VDecl->setInvalidDecl();
10964 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10965 // a kernel function cannot be initialized."
10966 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10967 Diag(VDecl->getLocation(), diag::err_local_cant_init);
10968 VDecl->setInvalidDecl();
10972 // Get the decls type and save a reference for later, since
10973 // CheckInitializerTypes may change it.
10974 QualType DclT = VDecl->getType(), SavT = DclT;
10976 // Expressions default to 'id' when we're in a debugger
10977 // and we are assigning it to a variable of Objective-C pointer type.
10978 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10979 Init->getType() == Context.UnknownAnyTy) {
10980 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10981 if (Result.isInvalid()) {
10982 VDecl->setInvalidDecl();
10985 Init = Result.get();
10988 // Perform the initialization.
10989 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10990 if (!VDecl->isInvalidDecl()) {
10991 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10992 InitializationKind Kind = InitializationKind::CreateForInit(
10993 VDecl->getLocation(), DirectInit, Init);
10995 MultiExprArg Args = Init;
10997 Args = MultiExprArg(CXXDirectInit->getExprs(),
10998 CXXDirectInit->getNumExprs());
11000 // Try to correct any TypoExprs in the initialization arguments.
11001 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11002 ExprResult Res = CorrectDelayedTyposInExpr(
11003 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11004 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11005 return Init.Failed() ? ExprError() : E;
11007 if (Res.isInvalid()) {
11008 VDecl->setInvalidDecl();
11009 } else if (Res.get() != Args[Idx]) {
11010 Args[Idx] = Res.get();
11013 if (VDecl->isInvalidDecl())
11016 InitializationSequence InitSeq(*this, Entity, Kind, Args,
11017 /*TopLevelOfInitList=*/false,
11018 /*TreatUnavailableAsInvalid=*/false);
11019 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11020 if (Result.isInvalid()) {
11021 VDecl->setInvalidDecl();
11025 Init = Result.getAs<Expr>();
11028 // Check for self-references within variable initializers.
11029 // Variables declared within a function/method body (except for references)
11030 // are handled by a dataflow analysis.
11031 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11032 VDecl->getType()->isReferenceType()) {
11033 CheckSelfReference(*this, RealDecl, Init, DirectInit);
11036 // If the type changed, it means we had an incomplete type that was
11037 // completed by the initializer. For example:
11038 // int ary[] = { 1, 3, 5 };
11039 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11040 if (!VDecl->isInvalidDecl() && (DclT != SavT))
11041 VDecl->setType(DclT);
11043 if (!VDecl->isInvalidDecl()) {
11044 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11046 if (VDecl->hasAttr<BlocksAttr>())
11047 checkRetainCycles(VDecl, Init);
11049 // It is safe to assign a weak reference into a strong variable.
11050 // Although this code can still have problems:
11051 // id x = self.weakProp;
11052 // id y = self.weakProp;
11053 // we do not warn to warn spuriously when 'x' and 'y' are on separate
11054 // paths through the function. This should be revisited if
11055 // -Wrepeated-use-of-weak is made flow-sensitive.
11056 if (FunctionScopeInfo *FSI = getCurFunction())
11057 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11058 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11059 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11060 Init->getLocStart()))
11061 FSI->markSafeWeakUse(Init);
11064 // The initialization is usually a full-expression.
11066 // FIXME: If this is a braced initialization of an aggregate, it is not
11067 // an expression, and each individual field initializer is a separate
11068 // full-expression. For instance, in:
11070 // struct Temp { ~Temp(); };
11071 // struct S { S(Temp); };
11072 // struct T { S a, b; } t = { Temp(), Temp() }
11074 // we should destroy the first Temp before constructing the second.
11075 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
11077 VDecl->isConstexpr());
11078 if (Result.isInvalid()) {
11079 VDecl->setInvalidDecl();
11082 Init = Result.get();
11084 // Attach the initializer to the decl.
11085 VDecl->setInit(Init);
11087 if (VDecl->isLocalVarDecl()) {
11088 // Don't check the initializer if the declaration is malformed.
11089 if (VDecl->isInvalidDecl()) {
11092 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11093 // This is true even in OpenCL C++.
11094 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11095 CheckForConstantInitializer(Init, DclT);
11097 // Otherwise, C++ does not restrict the initializer.
11098 } else if (getLangOpts().CPlusPlus) {
11101 // C99 6.7.8p4: All the expressions in an initializer for an object that has
11102 // static storage duration shall be constant expressions or string literals.
11103 } else if (VDecl->getStorageClass() == SC_Static) {
11104 CheckForConstantInitializer(Init, DclT);
11106 // C89 is stricter than C99 for aggregate initializers.
11107 // C89 6.5.7p3: All the expressions [...] in an initializer list
11108 // for an object that has aggregate or union type shall be
11109 // constant expressions.
11110 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11111 isa<InitListExpr>(Init)) {
11112 const Expr *Culprit;
11113 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11114 Diag(Culprit->getExprLoc(),
11115 diag::ext_aggregate_init_not_constant)
11116 << Culprit->getSourceRange();
11119 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11120 VDecl->getLexicalDeclContext()->isRecord()) {
11121 // This is an in-class initialization for a static data member, e.g.,
11124 // static const int value = 17;
11127 // C++ [class.mem]p4:
11128 // A member-declarator can contain a constant-initializer only
11129 // if it declares a static member (9.4) of const integral or
11130 // const enumeration type, see 9.4.2.
11132 // C++11 [class.static.data]p3:
11133 // If a non-volatile non-inline const static data member is of integral
11134 // or enumeration type, its declaration in the class definition can
11135 // specify a brace-or-equal-initializer in which every initializer-clause
11136 // that is an assignment-expression is a constant expression. A static
11137 // data member of literal type can be declared in the class definition
11138 // with the constexpr specifier; if so, its declaration shall specify a
11139 // brace-or-equal-initializer in which every initializer-clause that is
11140 // an assignment-expression is a constant expression.
11142 // Do nothing on dependent types.
11143 if (DclT->isDependentType()) {
11145 // Allow any 'static constexpr' members, whether or not they are of literal
11146 // type. We separately check that every constexpr variable is of literal
11148 } else if (VDecl->isConstexpr()) {
11150 // Require constness.
11151 } else if (!DclT.isConstQualified()) {
11152 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11153 << Init->getSourceRange();
11154 VDecl->setInvalidDecl();
11156 // We allow integer constant expressions in all cases.
11157 } else if (DclT->isIntegralOrEnumerationType()) {
11158 // Check whether the expression is a constant expression.
11159 SourceLocation Loc;
11160 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11161 // In C++11, a non-constexpr const static data member with an
11162 // in-class initializer cannot be volatile.
11163 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11164 else if (Init->isValueDependent())
11165 ; // Nothing to check.
11166 else if (Init->isIntegerConstantExpr(Context, &Loc))
11167 ; // Ok, it's an ICE!
11168 else if (Init->getType()->isScopedEnumeralType() &&
11169 Init->isCXX11ConstantExpr(Context))
11170 ; // Ok, it is a scoped-enum constant expression.
11171 else if (Init->isEvaluatable(Context)) {
11172 // If we can constant fold the initializer through heroics, accept it,
11173 // but report this as a use of an extension for -pedantic.
11174 Diag(Loc, diag::ext_in_class_initializer_non_constant)
11175 << Init->getSourceRange();
11177 // Otherwise, this is some crazy unknown case. Report the issue at the
11178 // location provided by the isIntegerConstantExpr failed check.
11179 Diag(Loc, diag::err_in_class_initializer_non_constant)
11180 << Init->getSourceRange();
11181 VDecl->setInvalidDecl();
11184 // We allow foldable floating-point constants as an extension.
11185 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11186 // In C++98, this is a GNU extension. In C++11, it is not, but we support
11187 // it anyway and provide a fixit to add the 'constexpr'.
11188 if (getLangOpts().CPlusPlus11) {
11189 Diag(VDecl->getLocation(),
11190 diag::ext_in_class_initializer_float_type_cxx11)
11191 << DclT << Init->getSourceRange();
11192 Diag(VDecl->getLocStart(),
11193 diag::note_in_class_initializer_float_type_cxx11)
11194 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
11196 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11197 << DclT << Init->getSourceRange();
11199 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11200 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11201 << Init->getSourceRange();
11202 VDecl->setInvalidDecl();
11206 // Suggest adding 'constexpr' in C++11 for literal types.
11207 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11208 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11209 << DclT << Init->getSourceRange()
11210 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
11211 VDecl->setConstexpr(true);
11214 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11215 << DclT << Init->getSourceRange();
11216 VDecl->setInvalidDecl();
11218 } else if (VDecl->isFileVarDecl()) {
11219 // In C, extern is typically used to avoid tentative definitions when
11220 // declaring variables in headers, but adding an intializer makes it a
11221 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11222 // In C++, extern is often used to give implictly static const variables
11223 // external linkage, so don't warn in that case. If selectany is present,
11224 // this might be header code intended for C and C++ inclusion, so apply the
11226 if (VDecl->getStorageClass() == SC_Extern &&
11227 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11228 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11229 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11230 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11231 Diag(VDecl->getLocation(), diag::warn_extern_init);
11233 // C99 6.7.8p4. All file scoped initializers need to be constant.
11234 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11235 CheckForConstantInitializer(Init, DclT);
11238 // We will represent direct-initialization similarly to copy-initialization:
11239 // int x(1); -as-> int x = 1;
11240 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11242 // Clients that want to distinguish between the two forms, can check for
11243 // direct initializer using VarDecl::getInitStyle().
11244 // A major benefit is that clients that don't particularly care about which
11245 // exactly form was it (like the CodeGen) can handle both cases without
11246 // special case code.
11249 // The form of initialization (using parentheses or '=') is generally
11250 // insignificant, but does matter when the entity being initialized has a
11252 if (CXXDirectInit) {
11253 assert(DirectInit && "Call-style initializer must be direct init.");
11254 VDecl->setInitStyle(VarDecl::CallInit);
11255 } else if (DirectInit) {
11256 // This must be list-initialization. No other way is direct-initialization.
11257 VDecl->setInitStyle(VarDecl::ListInit);
11260 CheckCompleteVariableDeclaration(VDecl);
11263 /// ActOnInitializerError - Given that there was an error parsing an
11264 /// initializer for the given declaration, try to return to some form
11266 void Sema::ActOnInitializerError(Decl *D) {
11267 // Our main concern here is re-establishing invariants like "a
11268 // variable's type is either dependent or complete".
11269 if (!D || D->isInvalidDecl()) return;
11271 VarDecl *VD = dyn_cast<VarDecl>(D);
11274 // Bindings are not usable if we can't make sense of the initializer.
11275 if (auto *DD = dyn_cast<DecompositionDecl>(D))
11276 for (auto *BD : DD->bindings())
11277 BD->setInvalidDecl();
11279 // Auto types are meaningless if we can't make sense of the initializer.
11280 if (ParsingInitForAutoVars.count(D)) {
11281 D->setInvalidDecl();
11285 QualType Ty = VD->getType();
11286 if (Ty->isDependentType()) return;
11288 // Require a complete type.
11289 if (RequireCompleteType(VD->getLocation(),
11290 Context.getBaseElementType(Ty),
11291 diag::err_typecheck_decl_incomplete_type)) {
11292 VD->setInvalidDecl();
11296 // Require a non-abstract type.
11297 if (RequireNonAbstractType(VD->getLocation(), Ty,
11298 diag::err_abstract_type_in_decl,
11299 AbstractVariableType)) {
11300 VD->setInvalidDecl();
11304 // Don't bother complaining about constructors or destructors,
11308 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11309 // If there is no declaration, there was an error parsing it. Just ignore it.
11313 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11314 QualType Type = Var->getType();
11316 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11317 if (isa<DecompositionDecl>(RealDecl)) {
11318 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11319 Var->setInvalidDecl();
11323 if (Type->isUndeducedType() &&
11324 DeduceVariableDeclarationType(Var, false, nullptr))
11327 // C++11 [class.static.data]p3: A static data member can be declared with
11328 // the constexpr specifier; if so, its declaration shall specify
11329 // a brace-or-equal-initializer.
11330 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11331 // the definition of a variable [...] or the declaration of a static data
11333 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11334 !Var->isThisDeclarationADemotedDefinition()) {
11335 if (Var->isStaticDataMember()) {
11336 // C++1z removes the relevant rule; the in-class declaration is always
11337 // a definition there.
11338 if (!getLangOpts().CPlusPlus17) {
11339 Diag(Var->getLocation(),
11340 diag::err_constexpr_static_mem_var_requires_init)
11341 << Var->getDeclName();
11342 Var->setInvalidDecl();
11346 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11347 Var->setInvalidDecl();
11352 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11354 if (!Var->isInvalidDecl() &&
11355 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11356 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11357 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11358 Var->setInvalidDecl();
11362 switch (Var->isThisDeclarationADefinition()) {
11363 case VarDecl::Definition:
11364 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11367 // We have an out-of-line definition of a static data member
11368 // that has an in-class initializer, so we type-check this like
11373 case VarDecl::DeclarationOnly:
11374 // It's only a declaration.
11376 // Block scope. C99 6.7p7: If an identifier for an object is
11377 // declared with no linkage (C99 6.2.2p6), the type for the
11378 // object shall be complete.
11379 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11380 !Var->hasLinkage() && !Var->isInvalidDecl() &&
11381 RequireCompleteType(Var->getLocation(), Type,
11382 diag::err_typecheck_decl_incomplete_type))
11383 Var->setInvalidDecl();
11385 // Make sure that the type is not abstract.
11386 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11387 RequireNonAbstractType(Var->getLocation(), Type,
11388 diag::err_abstract_type_in_decl,
11389 AbstractVariableType))
11390 Var->setInvalidDecl();
11391 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11392 Var->getStorageClass() == SC_PrivateExtern) {
11393 Diag(Var->getLocation(), diag::warn_private_extern);
11394 Diag(Var->getLocation(), diag::note_private_extern);
11399 case VarDecl::TentativeDefinition:
11400 // File scope. C99 6.9.2p2: A declaration of an identifier for an
11401 // object that has file scope without an initializer, and without a
11402 // storage-class specifier or with the storage-class specifier "static",
11403 // constitutes a tentative definition. Note: A tentative definition with
11404 // external linkage is valid (C99 6.2.2p5).
11405 if (!Var->isInvalidDecl()) {
11406 if (const IncompleteArrayType *ArrayT
11407 = Context.getAsIncompleteArrayType(Type)) {
11408 if (RequireCompleteType(Var->getLocation(),
11409 ArrayT->getElementType(),
11410 diag::err_illegal_decl_array_incomplete_type))
11411 Var->setInvalidDecl();
11412 } else if (Var->getStorageClass() == SC_Static) {
11413 // C99 6.9.2p3: If the declaration of an identifier for an object is
11414 // a tentative definition and has internal linkage (C99 6.2.2p3), the
11415 // declared type shall not be an incomplete type.
11416 // NOTE: code such as the following
11417 // static struct s;
11418 // struct s { int a; };
11419 // is accepted by gcc. Hence here we issue a warning instead of
11420 // an error and we do not invalidate the static declaration.
11421 // NOTE: to avoid multiple warnings, only check the first declaration.
11422 if (Var->isFirstDecl())
11423 RequireCompleteType(Var->getLocation(), Type,
11424 diag::ext_typecheck_decl_incomplete_type);
11428 // Record the tentative definition; we're done.
11429 if (!Var->isInvalidDecl())
11430 TentativeDefinitions.push_back(Var);
11434 // Provide a specific diagnostic for uninitialized variable
11435 // definitions with incomplete array type.
11436 if (Type->isIncompleteArrayType()) {
11437 Diag(Var->getLocation(),
11438 diag::err_typecheck_incomplete_array_needs_initializer);
11439 Var->setInvalidDecl();
11443 // Provide a specific diagnostic for uninitialized variable
11444 // definitions with reference type.
11445 if (Type->isReferenceType()) {
11446 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11447 << Var->getDeclName()
11448 << SourceRange(Var->getLocation(), Var->getLocation());
11449 Var->setInvalidDecl();
11453 // Do not attempt to type-check the default initializer for a
11454 // variable with dependent type.
11455 if (Type->isDependentType())
11458 if (Var->isInvalidDecl())
11461 if (!Var->hasAttr<AliasAttr>()) {
11462 if (RequireCompleteType(Var->getLocation(),
11463 Context.getBaseElementType(Type),
11464 diag::err_typecheck_decl_incomplete_type)) {
11465 Var->setInvalidDecl();
11472 // The variable can not have an abstract class type.
11473 if (RequireNonAbstractType(Var->getLocation(), Type,
11474 diag::err_abstract_type_in_decl,
11475 AbstractVariableType)) {
11476 Var->setInvalidDecl();
11480 // Check for jumps past the implicit initializer. C++0x
11481 // clarifies that this applies to a "variable with automatic
11482 // storage duration", not a "local variable".
11483 // C++11 [stmt.dcl]p3
11484 // A program that jumps from a point where a variable with automatic
11485 // storage duration is not in scope to a point where it is in scope is
11486 // ill-formed unless the variable has scalar type, class type with a
11487 // trivial default constructor and a trivial destructor, a cv-qualified
11488 // version of one of these types, or an array of one of the preceding
11489 // types and is declared without an initializer.
11490 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11491 if (const RecordType *Record
11492 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11493 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11494 // Mark the function (if we're in one) for further checking even if the
11495 // looser rules of C++11 do not require such checks, so that we can
11496 // diagnose incompatibilities with C++98.
11497 if (!CXXRecord->isPOD())
11498 setFunctionHasBranchProtectedScope();
11502 // C++03 [dcl.init]p9:
11503 // If no initializer is specified for an object, and the
11504 // object is of (possibly cv-qualified) non-POD class type (or
11505 // array thereof), the object shall be default-initialized; if
11506 // the object is of const-qualified type, the underlying class
11507 // type shall have a user-declared default
11508 // constructor. Otherwise, if no initializer is specified for
11509 // a non- static object, the object and its subobjects, if
11510 // any, have an indeterminate initial value); if the object
11511 // or any of its subobjects are of const-qualified type, the
11512 // program is ill-formed.
11513 // C++0x [dcl.init]p11:
11514 // If no initializer is specified for an object, the object is
11515 // default-initialized; [...].
11516 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11517 InitializationKind Kind
11518 = InitializationKind::CreateDefault(Var->getLocation());
11520 InitializationSequence InitSeq(*this, Entity, Kind, None);
11521 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11522 if (Init.isInvalid())
11523 Var->setInvalidDecl();
11524 else if (Init.get()) {
11525 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11526 // This is important for template substitution.
11527 Var->setInitStyle(VarDecl::CallInit);
11530 CheckCompleteVariableDeclaration(Var);
11534 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11535 // If there is no declaration, there was an error parsing it. Ignore it.
11539 VarDecl *VD = dyn_cast<VarDecl>(D);
11541 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11542 D->setInvalidDecl();
11546 VD->setCXXForRangeDecl(true);
11548 // for-range-declaration cannot be given a storage class specifier.
11550 switch (VD->getStorageClass()) {
11559 case SC_PrivateExtern:
11570 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11571 << VD->getDeclName() << Error;
11572 D->setInvalidDecl();
11577 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11578 IdentifierInfo *Ident,
11579 ParsedAttributes &Attrs,
11580 SourceLocation AttrEnd) {
11581 // C++1y [stmt.iter]p1:
11582 // A range-based for statement of the form
11583 // for ( for-range-identifier : for-range-initializer ) statement
11584 // is equivalent to
11585 // for ( auto&& for-range-identifier : for-range-initializer ) statement
11586 DeclSpec DS(Attrs.getPool().getFactory());
11588 const char *PrevSpec;
11590 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11591 getPrintingPolicy());
11593 Declarator D(DS, DeclaratorContext::ForContext);
11594 D.SetIdentifier(Ident, IdentLoc);
11595 D.takeAttributes(Attrs, AttrEnd);
11597 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11598 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11600 Decl *Var = ActOnDeclarator(S, D);
11601 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11602 FinalizeDeclaration(Var);
11603 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11604 AttrEnd.isValid() ? AttrEnd : IdentLoc);
11607 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11608 if (var->isInvalidDecl()) return;
11610 if (getLangOpts().OpenCL) {
11611 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11613 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11615 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11617 var->setInvalidDecl();
11622 // In Objective-C, don't allow jumps past the implicit initialization of a
11623 // local retaining variable.
11624 if (getLangOpts().ObjC1 &&
11625 var->hasLocalStorage()) {
11626 switch (var->getType().getObjCLifetime()) {
11627 case Qualifiers::OCL_None:
11628 case Qualifiers::OCL_ExplicitNone:
11629 case Qualifiers::OCL_Autoreleasing:
11632 case Qualifiers::OCL_Weak:
11633 case Qualifiers::OCL_Strong:
11634 setFunctionHasBranchProtectedScope();
11639 if (var->hasLocalStorage() &&
11640 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11641 setFunctionHasBranchProtectedScope();
11643 // Warn about externally-visible variables being defined without a
11644 // prior declaration. We only want to do this for global
11645 // declarations, but we also specifically need to avoid doing it for
11646 // class members because the linkage of an anonymous class can
11647 // change if it's later given a typedef name.
11648 if (var->isThisDeclarationADefinition() &&
11649 var->getDeclContext()->getRedeclContext()->isFileContext() &&
11650 var->isExternallyVisible() && var->hasLinkage() &&
11651 !var->isInline() && !var->getDescribedVarTemplate() &&
11652 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11653 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11654 var->getLocation())) {
11655 // Find a previous declaration that's not a definition.
11656 VarDecl *prev = var->getPreviousDecl();
11657 while (prev && prev->isThisDeclarationADefinition())
11658 prev = prev->getPreviousDecl();
11661 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11664 // Cache the result of checking for constant initialization.
11665 Optional<bool> CacheHasConstInit;
11666 const Expr *CacheCulprit;
11667 auto checkConstInit = [&]() mutable {
11668 if (!CacheHasConstInit)
11669 CacheHasConstInit = var->getInit()->isConstantInitializer(
11670 Context, var->getType()->isReferenceType(), &CacheCulprit);
11671 return *CacheHasConstInit;
11674 if (var->getTLSKind() == VarDecl::TLS_Static) {
11675 if (var->getType().isDestructedType()) {
11676 // GNU C++98 edits for __thread, [basic.start.term]p3:
11677 // The type of an object with thread storage duration shall not
11678 // have a non-trivial destructor.
11679 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11680 if (getLangOpts().CPlusPlus11)
11681 Diag(var->getLocation(), diag::note_use_thread_local);
11682 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11683 if (!checkConstInit()) {
11684 // GNU C++98 edits for __thread, [basic.start.init]p4:
11685 // An object of thread storage duration shall not require dynamic
11687 // FIXME: Need strict checking here.
11688 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11689 << CacheCulprit->getSourceRange();
11690 if (getLangOpts().CPlusPlus11)
11691 Diag(var->getLocation(), diag::note_use_thread_local);
11696 // Apply section attributes and pragmas to global variables.
11697 bool GlobalStorage = var->hasGlobalStorage();
11698 if (GlobalStorage && var->isThisDeclarationADefinition() &&
11699 !inTemplateInstantiation()) {
11700 PragmaStack<StringLiteral *> *Stack = nullptr;
11701 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11702 if (var->getType().isConstQualified())
11703 Stack = &ConstSegStack;
11704 else if (!var->getInit()) {
11705 Stack = &BSSSegStack;
11706 SectionFlags |= ASTContext::PSF_Write;
11708 Stack = &DataSegStack;
11709 SectionFlags |= ASTContext::PSF_Write;
11711 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11712 var->addAttr(SectionAttr::CreateImplicit(
11713 Context, SectionAttr::Declspec_allocate,
11714 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11716 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11717 if (UnifySection(SA->getName(), SectionFlags, var))
11718 var->dropAttr<SectionAttr>();
11720 // Apply the init_seg attribute if this has an initializer. If the
11721 // initializer turns out to not be dynamic, we'll end up ignoring this
11723 if (CurInitSeg && var->getInit())
11724 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11728 // All the following checks are C++ only.
11729 if (!getLangOpts().CPlusPlus) {
11730 // If this variable must be emitted, add it as an initializer for the
11732 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11733 Context.addModuleInitializer(ModuleScopes.back().Module, var);
11737 if (auto *DD = dyn_cast<DecompositionDecl>(var))
11738 CheckCompleteDecompositionDeclaration(DD);
11740 QualType type = var->getType();
11741 if (type->isDependentType()) return;
11743 // __block variables might require us to capture a copy-initializer.
11744 if (var->hasAttr<BlocksAttr>()) {
11745 // It's currently invalid to ever have a __block variable with an
11746 // array type; should we diagnose that here?
11748 // Regardless, we don't want to ignore array nesting when
11749 // constructing this copy.
11750 if (type->isStructureOrClassType()) {
11751 EnterExpressionEvaluationContext scope(
11752 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11753 SourceLocation poi = var->getLocation();
11754 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11756 = PerformMoveOrCopyInitialization(
11757 InitializedEntity::InitializeBlock(poi, type, false),
11758 var, var->getType(), varRef, /*AllowNRVO=*/true);
11759 if (!result.isInvalid()) {
11760 result = MaybeCreateExprWithCleanups(result);
11761 Expr *init = result.getAs<Expr>();
11762 Context.setBlockVarCopyInits(var, init);
11767 Expr *Init = var->getInit();
11768 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11769 QualType baseType = Context.getBaseElementType(type);
11771 if (Init && !Init->isValueDependent()) {
11772 if (var->isConstexpr()) {
11773 SmallVector<PartialDiagnosticAt, 8> Notes;
11774 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11775 SourceLocation DiagLoc = var->getLocation();
11776 // If the note doesn't add any useful information other than a source
11777 // location, fold it into the primary diagnostic.
11778 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11779 diag::note_invalid_subexpr_in_const_expr) {
11780 DiagLoc = Notes[0].first;
11783 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11784 << var << Init->getSourceRange();
11785 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11786 Diag(Notes[I].first, Notes[I].second);
11788 } else if (var->isUsableInConstantExpressions(Context)) {
11789 // Check whether the initializer of a const variable of integral or
11790 // enumeration type is an ICE now, since we can't tell whether it was
11791 // initialized by a constant expression if we check later.
11792 var->checkInitIsICE();
11795 // Don't emit further diagnostics about constexpr globals since they
11796 // were just diagnosed.
11797 if (!var->isConstexpr() && GlobalStorage &&
11798 var->hasAttr<RequireConstantInitAttr>()) {
11799 // FIXME: Need strict checking in C++03 here.
11800 bool DiagErr = getLangOpts().CPlusPlus11
11801 ? !var->checkInitIsICE() : !checkConstInit();
11803 auto attr = var->getAttr<RequireConstantInitAttr>();
11804 Diag(var->getLocation(), diag::err_require_constant_init_failed)
11805 << Init->getSourceRange();
11806 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11807 << attr->getRange();
11808 if (getLangOpts().CPlusPlus11) {
11810 SmallVector<PartialDiagnosticAt, 8> Notes;
11811 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11812 for (auto &it : Notes)
11813 Diag(it.first, it.second);
11815 Diag(CacheCulprit->getExprLoc(),
11816 diag::note_invalid_subexpr_in_const_expr)
11817 << CacheCulprit->getSourceRange();
11821 else if (!var->isConstexpr() && IsGlobal &&
11822 !getDiagnostics().isIgnored(diag::warn_global_constructor,
11823 var->getLocation())) {
11824 // Warn about globals which don't have a constant initializer. Don't
11825 // warn about globals with a non-trivial destructor because we already
11826 // warned about them.
11827 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11828 if (!(RD && !RD->hasTrivialDestructor())) {
11829 if (!checkConstInit())
11830 Diag(var->getLocation(), diag::warn_global_constructor)
11831 << Init->getSourceRange();
11836 // Require the destructor.
11837 if (const RecordType *recordType = baseType->getAs<RecordType>())
11838 FinalizeVarWithDestructor(var, recordType);
11840 // If this variable must be emitted, add it as an initializer for the current
11842 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11843 Context.addModuleInitializer(ModuleScopes.back().Module, var);
11846 /// Determines if a variable's alignment is dependent.
11847 static bool hasDependentAlignment(VarDecl *VD) {
11848 if (VD->getType()->isDependentType())
11850 for (auto *I : VD->specific_attrs<AlignedAttr>())
11851 if (I->isAlignmentDependent())
11856 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11857 /// any semantic actions necessary after any initializer has been attached.
11858 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11859 // Note that we are no longer parsing the initializer for this declaration.
11860 ParsingInitForAutoVars.erase(ThisDecl);
11862 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11866 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11867 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11868 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11869 if (PragmaClangBSSSection.Valid)
11870 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11871 PragmaClangBSSSection.SectionName,
11872 PragmaClangBSSSection.PragmaLocation));
11873 if (PragmaClangDataSection.Valid)
11874 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11875 PragmaClangDataSection.SectionName,
11876 PragmaClangDataSection.PragmaLocation));
11877 if (PragmaClangRodataSection.Valid)
11878 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11879 PragmaClangRodataSection.SectionName,
11880 PragmaClangRodataSection.PragmaLocation));
11883 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11884 for (auto *BD : DD->bindings()) {
11885 FinalizeDeclaration(BD);
11889 checkAttributesAfterMerging(*this, *VD);
11891 // Perform TLS alignment check here after attributes attached to the variable
11892 // which may affect the alignment have been processed. Only perform the check
11893 // if the target has a maximum TLS alignment (zero means no constraints).
11894 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11895 // Protect the check so that it's not performed on dependent types and
11896 // dependent alignments (we can't determine the alignment in that case).
11897 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11898 !VD->isInvalidDecl()) {
11899 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11900 if (Context.getDeclAlign(VD) > MaxAlignChars) {
11901 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11902 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11903 << (unsigned)MaxAlignChars.getQuantity();
11908 if (VD->isStaticLocal()) {
11909 if (FunctionDecl *FD =
11910 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11911 // Static locals inherit dll attributes from their function.
11912 if (Attr *A = getDLLAttr(FD)) {
11913 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11914 NewAttr->setInherited(true);
11915 VD->addAttr(NewAttr);
11917 // CUDA E.2.9.4: Within the body of a __device__ or __global__
11918 // function, only __shared__ variables may be declared with
11919 // static storage class.
11920 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11921 CUDADiagIfDeviceCode(VD->getLocation(),
11922 diag::err_device_static_local_var)
11923 << CurrentCUDATarget())
11924 VD->setInvalidDecl();
11928 // Perform check for initializers of device-side global variables.
11929 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11930 // 7.5). We must also apply the same checks to all __shared__
11931 // variables whether they are local or not. CUDA also allows
11932 // constant initializers for __constant__ and __device__ variables.
11933 if (getLangOpts().CUDA)
11934 checkAllowedCUDAInitializer(VD);
11936 // Grab the dllimport or dllexport attribute off of the VarDecl.
11937 const InheritableAttr *DLLAttr = getDLLAttr(VD);
11939 // Imported static data members cannot be defined out-of-line.
11940 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11941 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11942 VD->isThisDeclarationADefinition()) {
11943 // We allow definitions of dllimport class template static data members
11945 CXXRecordDecl *Context =
11946 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11947 bool IsClassTemplateMember =
11948 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11949 Context->getDescribedClassTemplate();
11951 Diag(VD->getLocation(),
11952 IsClassTemplateMember
11953 ? diag::warn_attribute_dllimport_static_field_definition
11954 : diag::err_attribute_dllimport_static_field_definition);
11955 Diag(IA->getLocation(), diag::note_attribute);
11956 if (!IsClassTemplateMember)
11957 VD->setInvalidDecl();
11961 // dllimport/dllexport variables cannot be thread local, their TLS index
11962 // isn't exported with the variable.
11963 if (DLLAttr && VD->getTLSKind()) {
11964 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11965 if (F && getDLLAttr(F)) {
11966 assert(VD->isStaticLocal());
11967 // But if this is a static local in a dlimport/dllexport function, the
11968 // function will never be inlined, which means the var would never be
11969 // imported, so having it marked import/export is safe.
11971 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11973 VD->setInvalidDecl();
11977 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11978 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11979 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11980 VD->dropAttr<UsedAttr>();
11984 const DeclContext *DC = VD->getDeclContext();
11985 // If there's a #pragma GCC visibility in scope, and this isn't a class
11986 // member, set the visibility of this variable.
11987 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11988 AddPushedVisibilityAttribute(VD);
11990 // FIXME: Warn on unused var template partial specializations.
11991 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11992 MarkUnusedFileScopedDecl(VD);
11994 // Now we have parsed the initializer and can update the table of magic
11996 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11997 !VD->getType()->isIntegralOrEnumerationType())
12000 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12001 const Expr *MagicValueExpr = VD->getInit();
12002 if (!MagicValueExpr) {
12005 llvm::APSInt MagicValueInt;
12006 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12007 Diag(I->getRange().getBegin(),
12008 diag::err_type_tag_for_datatype_not_ice)
12009 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12012 if (MagicValueInt.getActiveBits() > 64) {
12013 Diag(I->getRange().getBegin(),
12014 diag::err_type_tag_for_datatype_too_large)
12015 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12018 uint64_t MagicValue = MagicValueInt.getZExtValue();
12019 RegisterTypeTagForDatatype(I->getArgumentKind(),
12021 I->getMatchingCType(),
12022 I->getLayoutCompatible(),
12023 I->getMustBeNull());
12027 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12028 auto *VD = dyn_cast<VarDecl>(DD);
12029 return VD && !VD->getType()->hasAutoForTrailingReturnType();
12032 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12033 ArrayRef<Decl *> Group) {
12034 SmallVector<Decl*, 8> Decls;
12036 if (DS.isTypeSpecOwned())
12037 Decls.push_back(DS.getRepAsDecl());
12039 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12040 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12041 bool DiagnosedMultipleDecomps = false;
12042 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12043 bool DiagnosedNonDeducedAuto = false;
12045 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12046 if (Decl *D = Group[i]) {
12047 // For declarators, there are some additional syntactic-ish checks we need
12049 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12050 if (!FirstDeclaratorInGroup)
12051 FirstDeclaratorInGroup = DD;
12052 if (!FirstDecompDeclaratorInGroup)
12053 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12054 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12055 !hasDeducedAuto(DD))
12056 FirstNonDeducedAutoInGroup = DD;
12058 if (FirstDeclaratorInGroup != DD) {
12059 // A decomposition declaration cannot be combined with any other
12060 // declaration in the same group.
12061 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12062 Diag(FirstDecompDeclaratorInGroup->getLocation(),
12063 diag::err_decomp_decl_not_alone)
12064 << FirstDeclaratorInGroup->getSourceRange()
12065 << DD->getSourceRange();
12066 DiagnosedMultipleDecomps = true;
12069 // A declarator that uses 'auto' in any way other than to declare a
12070 // variable with a deduced type cannot be combined with any other
12071 // declarator in the same group.
12072 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12073 Diag(FirstNonDeducedAutoInGroup->getLocation(),
12074 diag::err_auto_non_deduced_not_alone)
12075 << FirstNonDeducedAutoInGroup->getType()
12076 ->hasAutoForTrailingReturnType()
12077 << FirstDeclaratorInGroup->getSourceRange()
12078 << DD->getSourceRange();
12079 DiagnosedNonDeducedAuto = true;
12084 Decls.push_back(D);
12088 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12089 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12090 handleTagNumbering(Tag, S);
12091 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12092 getLangOpts().CPlusPlus)
12093 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12097 return BuildDeclaratorGroup(Decls);
12100 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12101 /// group, performing any necessary semantic checking.
12102 Sema::DeclGroupPtrTy
12103 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12104 // C++14 [dcl.spec.auto]p7: (DR1347)
12105 // If the type that replaces the placeholder type is not the same in each
12106 // deduction, the program is ill-formed.
12107 if (Group.size() > 1) {
12109 VarDecl *DeducedDecl = nullptr;
12110 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12111 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12112 if (!D || D->isInvalidDecl())
12114 DeducedType *DT = D->getType()->getContainedDeducedType();
12115 if (!DT || DT->getDeducedType().isNull())
12117 if (Deduced.isNull()) {
12118 Deduced = DT->getDeducedType();
12120 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12121 auto *AT = dyn_cast<AutoType>(DT);
12122 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12123 diag::err_auto_different_deductions)
12124 << (AT ? (unsigned)AT->getKeyword() : 3)
12125 << Deduced << DeducedDecl->getDeclName()
12126 << DT->getDeducedType() << D->getDeclName()
12127 << DeducedDecl->getInit()->getSourceRange()
12128 << D->getInit()->getSourceRange();
12129 D->setInvalidDecl();
12135 ActOnDocumentableDecls(Group);
12137 return DeclGroupPtrTy::make(
12138 DeclGroupRef::Create(Context, Group.data(), Group.size()));
12141 void Sema::ActOnDocumentableDecl(Decl *D) {
12142 ActOnDocumentableDecls(D);
12145 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12146 // Don't parse the comment if Doxygen diagnostics are ignored.
12147 if (Group.empty() || !Group[0])
12150 if (Diags.isIgnored(diag::warn_doc_param_not_found,
12151 Group[0]->getLocation()) &&
12152 Diags.isIgnored(diag::warn_unknown_comment_command_name,
12153 Group[0]->getLocation()))
12156 if (Group.size() >= 2) {
12157 // This is a decl group. Normally it will contain only declarations
12158 // produced from declarator list. But in case we have any definitions or
12159 // additional declaration references:
12160 // 'typedef struct S {} S;'
12161 // 'typedef struct S *S;'
12163 // FinalizeDeclaratorGroup adds these as separate declarations.
12164 Decl *MaybeTagDecl = Group[0];
12165 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12166 Group = Group.slice(1);
12170 // See if there are any new comments that are not attached to a decl.
12171 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12172 if (!Comments.empty() &&
12173 !Comments.back()->isAttached()) {
12174 // There is at least one comment that not attached to a decl.
12175 // Maybe it should be attached to one of these decls?
12177 // Note that this way we pick up not only comments that precede the
12178 // declaration, but also comments that *follow* the declaration -- thanks to
12179 // the lookahead in the lexer: we've consumed the semicolon and looked
12180 // ahead through comments.
12181 for (unsigned i = 0, e = Group.size(); i != e; ++i)
12182 Context.getCommentForDecl(Group[i], &PP);
12186 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12187 /// to introduce parameters into function prototype scope.
12188 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12189 const DeclSpec &DS = D.getDeclSpec();
12191 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12193 // C++03 [dcl.stc]p2 also permits 'auto'.
12194 StorageClass SC = SC_None;
12195 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12197 // In C++11, the 'register' storage class specifier is deprecated.
12198 // In C++17, it is not allowed, but we tolerate it as an extension.
12199 if (getLangOpts().CPlusPlus11) {
12200 Diag(DS.getStorageClassSpecLoc(),
12201 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12202 : diag::warn_deprecated_register)
12203 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12205 } else if (getLangOpts().CPlusPlus &&
12206 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12208 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12209 Diag(DS.getStorageClassSpecLoc(),
12210 diag::err_invalid_storage_class_in_func_decl);
12211 D.getMutableDeclSpec().ClearStorageClassSpecs();
12214 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12215 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12216 << DeclSpec::getSpecifierName(TSCS);
12217 if (DS.isInlineSpecified())
12218 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12219 << getLangOpts().CPlusPlus17;
12220 if (DS.isConstexprSpecified())
12221 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12224 DiagnoseFunctionSpecifiers(DS);
12226 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12227 QualType parmDeclType = TInfo->getType();
12229 if (getLangOpts().CPlusPlus) {
12230 // Check that there are no default arguments inside the type of this
12232 CheckExtraCXXDefaultArguments(D);
12234 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12235 if (D.getCXXScopeSpec().isSet()) {
12236 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12237 << D.getCXXScopeSpec().getRange();
12238 D.getCXXScopeSpec().clear();
12242 // Ensure we have a valid name
12243 IdentifierInfo *II = nullptr;
12245 II = D.getIdentifier();
12247 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12248 << GetNameForDeclarator(D).getName();
12249 D.setInvalidType(true);
12253 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12255 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12256 ForVisibleRedeclaration);
12258 if (R.isSingleResult()) {
12259 NamedDecl *PrevDecl = R.getFoundDecl();
12260 if (PrevDecl->isTemplateParameter()) {
12261 // Maybe we will complain about the shadowed template parameter.
12262 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12263 // Just pretend that we didn't see the previous declaration.
12264 PrevDecl = nullptr;
12265 } else if (S->isDeclScope(PrevDecl)) {
12266 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12267 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12269 // Recover by removing the name
12271 D.SetIdentifier(nullptr, D.getIdentifierLoc());
12272 D.setInvalidType(true);
12277 // Temporarily put parameter variables in the translation unit, not
12278 // the enclosing context. This prevents them from accidentally
12279 // looking like class members in C++.
12280 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
12282 D.getIdentifierLoc(), II,
12283 parmDeclType, TInfo,
12286 if (D.isInvalidType())
12287 New->setInvalidDecl();
12289 assert(S->isFunctionPrototypeScope());
12290 assert(S->getFunctionPrototypeDepth() >= 1);
12291 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12292 S->getNextFunctionPrototypeIndex());
12294 // Add the parameter declaration into this scope.
12297 IdResolver.AddDecl(New);
12299 ProcessDeclAttributes(S, New, D);
12301 if (D.getDeclSpec().isModulePrivateSpecified())
12302 Diag(New->getLocation(), diag::err_module_private_local)
12303 << 1 << New->getDeclName()
12304 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12305 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12307 if (New->hasAttr<BlocksAttr>()) {
12308 Diag(New->getLocation(), diag::err_block_on_nonlocal);
12313 /// Synthesizes a variable for a parameter arising from a
12315 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12316 SourceLocation Loc,
12318 /* FIXME: setting StartLoc == Loc.
12319 Would it be worth to modify callers so as to provide proper source
12320 location for the unnamed parameters, embedding the parameter's type? */
12321 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12322 T, Context.getTrivialTypeSourceInfo(T, Loc),
12324 Param->setImplicit();
12328 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12329 // Don't diagnose unused-parameter errors in template instantiations; we
12330 // will already have done so in the template itself.
12331 if (inTemplateInstantiation())
12334 for (const ParmVarDecl *Parameter : Parameters) {
12335 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12336 !Parameter->hasAttr<UnusedAttr>()) {
12337 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12338 << Parameter->getDeclName();
12343 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12344 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12345 if (LangOpts.NumLargeByValueCopy == 0) // No check.
12348 // Warn if the return value is pass-by-value and larger than the specified
12350 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12351 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12352 if (Size > LangOpts.NumLargeByValueCopy)
12353 Diag(D->getLocation(), diag::warn_return_value_size)
12354 << D->getDeclName() << Size;
12357 // Warn if any parameter is pass-by-value and larger than the specified
12359 for (const ParmVarDecl *Parameter : Parameters) {
12360 QualType T = Parameter->getType();
12361 if (T->isDependentType() || !T.isPODType(Context))
12363 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12364 if (Size > LangOpts.NumLargeByValueCopy)
12365 Diag(Parameter->getLocation(), diag::warn_parameter_size)
12366 << Parameter->getDeclName() << Size;
12370 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12371 SourceLocation NameLoc, IdentifierInfo *Name,
12372 QualType T, TypeSourceInfo *TSInfo,
12374 // In ARC, infer a lifetime qualifier for appropriate parameter types.
12375 if (getLangOpts().ObjCAutoRefCount &&
12376 T.getObjCLifetime() == Qualifiers::OCL_None &&
12377 T->isObjCLifetimeType()) {
12379 Qualifiers::ObjCLifetime lifetime;
12381 // Special cases for arrays:
12382 // - if it's const, use __unsafe_unretained
12383 // - otherwise, it's an error
12384 if (T->isArrayType()) {
12385 if (!T.isConstQualified()) {
12386 DelayedDiagnostics.add(
12387 sema::DelayedDiagnostic::makeForbiddenType(
12388 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12390 lifetime = Qualifiers::OCL_ExplicitNone;
12392 lifetime = T->getObjCARCImplicitLifetime();
12394 T = Context.getLifetimeQualifiedType(T, lifetime);
12397 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12398 Context.getAdjustedParameterType(T),
12399 TSInfo, SC, nullptr);
12401 // Parameters can not be abstract class types.
12402 // For record types, this is done by the AbstractClassUsageDiagnoser once
12403 // the class has been completely parsed.
12404 if (!CurContext->isRecord() &&
12405 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12406 AbstractParamType))
12407 New->setInvalidDecl();
12409 // Parameter declarators cannot be interface types. All ObjC objects are
12410 // passed by reference.
12411 if (T->isObjCObjectType()) {
12412 SourceLocation TypeEndLoc =
12413 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
12415 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12416 << FixItHint::CreateInsertion(TypeEndLoc, "*");
12417 T = Context.getObjCObjectPointerType(T);
12421 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12422 // duration shall not be qualified by an address-space qualifier."
12423 // Since all parameters have automatic store duration, they can not have
12424 // an address space.
12425 if (T.getAddressSpace() != LangAS::Default &&
12426 // OpenCL allows function arguments declared to be an array of a type
12427 // to be qualified with an address space.
12428 !(getLangOpts().OpenCL &&
12429 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12430 Diag(NameLoc, diag::err_arg_with_address_space);
12431 New->setInvalidDecl();
12437 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12438 SourceLocation LocAfterDecls) {
12439 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12441 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12442 // for a K&R function.
12443 if (!FTI.hasPrototype) {
12444 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12446 if (FTI.Params[i].Param == nullptr) {
12447 SmallString<256> Code;
12448 llvm::raw_svector_ostream(Code)
12449 << " int " << FTI.Params[i].Ident->getName() << ";\n";
12450 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12451 << FTI.Params[i].Ident
12452 << FixItHint::CreateInsertion(LocAfterDecls, Code);
12454 // Implicitly declare the argument as type 'int' for lack of a better
12456 AttributeFactory attrs;
12457 DeclSpec DS(attrs);
12458 const char* PrevSpec; // unused
12459 unsigned DiagID; // unused
12460 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12461 DiagID, Context.getPrintingPolicy());
12462 // Use the identifier location for the type source range.
12463 DS.SetRangeStart(FTI.Params[i].IdentLoc);
12464 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12465 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12466 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12467 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12474 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12475 MultiTemplateParamsArg TemplateParameterLists,
12476 SkipBodyInfo *SkipBody) {
12477 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12478 assert(D.isFunctionDeclarator() && "Not a function declarator!");
12479 Scope *ParentScope = FnBodyScope->getParent();
12481 D.setFunctionDefinitionKind(FDK_Definition);
12482 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12483 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12486 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12487 Consumer.HandleInlineFunctionDefinition(D);
12490 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12491 const FunctionDecl*& PossibleZeroParamPrototype) {
12492 // Don't warn about invalid declarations.
12493 if (FD->isInvalidDecl())
12496 // Or declarations that aren't global.
12497 if (!FD->isGlobal())
12500 // Don't warn about C++ member functions.
12501 if (isa<CXXMethodDecl>(FD))
12504 // Don't warn about 'main'.
12508 // Don't warn about inline functions.
12509 if (FD->isInlined())
12512 // Don't warn about function templates.
12513 if (FD->getDescribedFunctionTemplate())
12516 // Don't warn about function template specializations.
12517 if (FD->isFunctionTemplateSpecialization())
12520 // Don't warn for OpenCL kernels.
12521 if (FD->hasAttr<OpenCLKernelAttr>())
12524 // Don't warn on explicitly deleted functions.
12525 if (FD->isDeleted())
12528 bool MissingPrototype = true;
12529 for (const FunctionDecl *Prev = FD->getPreviousDecl();
12530 Prev; Prev = Prev->getPreviousDecl()) {
12531 // Ignore any declarations that occur in function or method
12532 // scope, because they aren't visible from the header.
12533 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12536 MissingPrototype = !Prev->getType()->isFunctionProtoType();
12537 if (FD->getNumParams() == 0)
12538 PossibleZeroParamPrototype = Prev;
12542 return MissingPrototype;
12546 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12547 const FunctionDecl *EffectiveDefinition,
12548 SkipBodyInfo *SkipBody) {
12549 const FunctionDecl *Definition = EffectiveDefinition;
12550 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12551 // If this is a friend function defined in a class template, it does not
12552 // have a body until it is used, nevertheless it is a definition, see
12555 // ... for the purpose of determining whether an instantiated redeclaration
12556 // is valid according to [basic.def.odr] and [class.mem], a declaration that
12557 // corresponds to a definition in the template is considered to be a
12560 // The following code must produce redefinition error:
12562 // template<typename T> struct C20 { friend void func_20() {} };
12564 // void func_20() {}
12566 for (auto I : FD->redecls()) {
12567 if (I != FD && !I->isInvalidDecl() &&
12568 I->getFriendObjectKind() != Decl::FOK_None) {
12569 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12570 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12571 // A merged copy of the same function, instantiated as a member of
12572 // the same class, is OK.
12573 if (declaresSameEntity(OrigFD, Original) &&
12574 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12575 cast<Decl>(FD->getLexicalDeclContext())))
12579 if (Original->isThisDeclarationADefinition()) {
12590 if (canRedefineFunction(Definition, getLangOpts()))
12593 // Don't emit an error when this is redefinition of a typo-corrected
12595 if (TypoCorrectedFunctionDefinitions.count(Definition))
12598 // If we don't have a visible definition of the function, and it's inline or
12599 // a template, skip the new definition.
12600 if (SkipBody && !hasVisibleDefinition(Definition) &&
12601 (Definition->getFormalLinkage() == InternalLinkage ||
12602 Definition->isInlined() ||
12603 Definition->getDescribedFunctionTemplate() ||
12604 Definition->getNumTemplateParameterLists())) {
12605 SkipBody->ShouldSkip = true;
12606 if (auto *TD = Definition->getDescribedFunctionTemplate())
12607 makeMergedDefinitionVisible(TD);
12608 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12612 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12613 Definition->getStorageClass() == SC_Extern)
12614 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12615 << FD->getDeclName() << getLangOpts().CPlusPlus;
12617 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12619 Diag(Definition->getLocation(), diag::note_previous_definition);
12620 FD->setInvalidDecl();
12623 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12625 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12627 LambdaScopeInfo *LSI = S.PushLambdaScope();
12628 LSI->CallOperator = CallOperator;
12629 LSI->Lambda = LambdaClass;
12630 LSI->ReturnType = CallOperator->getReturnType();
12631 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12633 if (LCD == LCD_None)
12634 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12635 else if (LCD == LCD_ByCopy)
12636 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12637 else if (LCD == LCD_ByRef)
12638 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12639 DeclarationNameInfo DNI = CallOperator->getNameInfo();
12641 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12642 LSI->Mutable = !CallOperator->isConst();
12644 // Add the captures to the LSI so they can be noted as already
12645 // captured within tryCaptureVar.
12646 auto I = LambdaClass->field_begin();
12647 for (const auto &C : LambdaClass->captures()) {
12648 if (C.capturesVariable()) {
12649 VarDecl *VD = C.getCapturedVar();
12650 if (VD->isInitCapture())
12651 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12652 QualType CaptureType = VD->getType();
12653 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12654 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12655 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12656 /*EllipsisLoc*/C.isPackExpansion()
12657 ? C.getEllipsisLoc() : SourceLocation(),
12658 CaptureType, /*Expr*/ nullptr);
12660 } else if (C.capturesThis()) {
12661 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12663 C.getCaptureKind() == LCK_StarThis);
12665 LSI->addVLATypeCapture(C.getLocation(), I->getType());
12671 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12672 SkipBodyInfo *SkipBody) {
12674 // Parsing the function declaration failed in some way. Push on a fake scope
12675 // anyway so we can try to parse the function body.
12676 PushFunctionScope();
12680 FunctionDecl *FD = nullptr;
12682 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12683 FD = FunTmpl->getTemplatedDecl();
12685 FD = cast<FunctionDecl>(D);
12687 // Check for defining attributes before the check for redefinition.
12688 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12689 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12690 FD->dropAttr<AliasAttr>();
12691 FD->setInvalidDecl();
12693 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12694 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12695 FD->dropAttr<IFuncAttr>();
12696 FD->setInvalidDecl();
12699 // See if this is a redefinition. If 'will have body' is already set, then
12700 // these checks were already performed when it was set.
12701 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12702 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12704 // If we're skipping the body, we're done. Don't enter the scope.
12705 if (SkipBody && SkipBody->ShouldSkip)
12709 // Mark this function as "will have a body eventually". This lets users to
12710 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12712 FD->setWillHaveBody();
12714 // If we are instantiating a generic lambda call operator, push
12715 // a LambdaScopeInfo onto the function stack. But use the information
12716 // that's already been calculated (ActOnLambdaExpr) to prime the current
12717 // LambdaScopeInfo.
12718 // When the template operator is being specialized, the LambdaScopeInfo,
12719 // has to be properly restored so that tryCaptureVariable doesn't try
12720 // and capture any new variables. In addition when calculating potential
12721 // captures during transformation of nested lambdas, it is necessary to
12722 // have the LSI properly restored.
12723 if (isGenericLambdaCallOperatorSpecialization(FD)) {
12724 assert(inTemplateInstantiation() &&
12725 "There should be an active template instantiation on the stack "
12726 "when instantiating a generic lambda!");
12727 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12729 // Enter a new function scope
12730 PushFunctionScope();
12733 // Builtin functions cannot be defined.
12734 if (unsigned BuiltinID = FD->getBuiltinID()) {
12735 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12736 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12737 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12738 FD->setInvalidDecl();
12742 // The return type of a function definition must be complete
12743 // (C99 6.9.1p3, C++ [dcl.fct]p6).
12744 QualType ResultType = FD->getReturnType();
12745 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12746 !FD->isInvalidDecl() &&
12747 RequireCompleteType(FD->getLocation(), ResultType,
12748 diag::err_func_def_incomplete_result))
12749 FD->setInvalidDecl();
12752 PushDeclContext(FnBodyScope, FD);
12754 // Check the validity of our function parameters
12755 CheckParmsForFunctionDef(FD->parameters(),
12756 /*CheckParameterNames=*/true);
12758 // Add non-parameter declarations already in the function to the current
12761 for (Decl *NPD : FD->decls()) {
12762 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12765 assert(!isa<ParmVarDecl>(NonParmDecl) &&
12766 "parameters should not be in newly created FD yet");
12768 // If the decl has a name, make it accessible in the current scope.
12769 if (NonParmDecl->getDeclName())
12770 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12772 // Similarly, dive into enums and fish their constants out, making them
12773 // accessible in this scope.
12774 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12775 for (auto *EI : ED->enumerators())
12776 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12781 // Introduce our parameters into the function scope
12782 for (auto Param : FD->parameters()) {
12783 Param->setOwningFunction(FD);
12785 // If this has an identifier, add it to the scope stack.
12786 if (Param->getIdentifier() && FnBodyScope) {
12787 CheckShadow(FnBodyScope, Param);
12789 PushOnScopeChains(Param, FnBodyScope);
12793 // Ensure that the function's exception specification is instantiated.
12794 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12795 ResolveExceptionSpec(D->getLocation(), FPT);
12797 // dllimport cannot be applied to non-inline function definitions.
12798 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12799 !FD->isTemplateInstantiation()) {
12800 assert(!FD->hasAttr<DLLExportAttr>());
12801 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12802 FD->setInvalidDecl();
12805 // We want to attach documentation to original Decl (which might be
12806 // a function template).
12807 ActOnDocumentableDecl(D);
12808 if (getCurLexicalContext()->isObjCContainer() &&
12809 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12810 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12811 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12816 /// Given the set of return statements within a function body,
12817 /// compute the variables that are subject to the named return value
12820 /// Each of the variables that is subject to the named return value
12821 /// optimization will be marked as NRVO variables in the AST, and any
12822 /// return statement that has a marked NRVO variable as its NRVO candidate can
12823 /// use the named return value optimization.
12825 /// This function applies a very simplistic algorithm for NRVO: if every return
12826 /// statement in the scope of a variable has the same NRVO candidate, that
12827 /// candidate is an NRVO variable.
12828 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12829 ReturnStmt **Returns = Scope->Returns.data();
12831 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12832 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12833 if (!NRVOCandidate->isNRVOVariable())
12834 Returns[I]->setNRVOCandidate(nullptr);
12839 bool Sema::canDelayFunctionBody(const Declarator &D) {
12840 // We can't delay parsing the body of a constexpr function template (yet).
12841 if (D.getDeclSpec().isConstexprSpecified())
12844 // We can't delay parsing the body of a function template with a deduced
12845 // return type (yet).
12846 if (D.getDeclSpec().hasAutoTypeSpec()) {
12847 // If the placeholder introduces a non-deduced trailing return type,
12848 // we can still delay parsing it.
12849 if (D.getNumTypeObjects()) {
12850 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12851 if (Outer.Kind == DeclaratorChunk::Function &&
12852 Outer.Fun.hasTrailingReturnType()) {
12853 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12854 return Ty.isNull() || !Ty->isUndeducedType();
12863 bool Sema::canSkipFunctionBody(Decl *D) {
12864 // We cannot skip the body of a function (or function template) which is
12865 // constexpr, since we may need to evaluate its body in order to parse the
12866 // rest of the file.
12867 // We cannot skip the body of a function with an undeduced return type,
12868 // because any callers of that function need to know the type.
12869 if (const FunctionDecl *FD = D->getAsFunction()) {
12870 if (FD->isConstexpr())
12872 // We can't simply call Type::isUndeducedType here, because inside template
12873 // auto can be deduced to a dependent type, which is not considered
12875 if (FD->getReturnType()->getContainedDeducedType())
12878 return Consumer.shouldSkipFunctionBody(D);
12881 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12884 if (FunctionDecl *FD = Decl->getAsFunction())
12885 FD->setHasSkippedBody();
12886 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
12887 MD->setHasSkippedBody();
12891 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12892 return ActOnFinishFunctionBody(D, BodyArg, false);
12895 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12896 bool IsInstantiation) {
12897 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12899 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12900 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12902 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12903 CheckCompletedCoroutineBody(FD, Body);
12907 FD->setWillHaveBody(false);
12909 if (getLangOpts().CPlusPlus14) {
12910 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12911 FD->getReturnType()->isUndeducedType()) {
12912 // If the function has a deduced result type but contains no 'return'
12913 // statements, the result type as written must be exactly 'auto', and
12914 // the deduced result type is 'void'.
12915 if (!FD->getReturnType()->getAs<AutoType>()) {
12916 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12917 << FD->getReturnType();
12918 FD->setInvalidDecl();
12920 // Substitute 'void' for the 'auto' in the type.
12921 TypeLoc ResultType = getReturnTypeLoc(FD);
12922 Context.adjustDeducedFunctionResultType(
12923 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12926 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12927 // In C++11, we don't use 'auto' deduction rules for lambda call
12928 // operators because we don't support return type deduction.
12929 auto *LSI = getCurLambda();
12930 if (LSI->HasImplicitReturnType) {
12931 deduceClosureReturnType(*LSI);
12933 // C++11 [expr.prim.lambda]p4:
12934 // [...] if there are no return statements in the compound-statement
12935 // [the deduced type is] the type void
12937 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12939 // Update the return type to the deduced type.
12940 const FunctionProtoType *Proto =
12941 FD->getType()->getAs<FunctionProtoType>();
12942 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12943 Proto->getExtProtoInfo()));
12947 // If the function implicitly returns zero (like 'main') or is naked,
12948 // don't complain about missing return statements.
12949 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12950 WP.disableCheckFallThrough();
12952 // MSVC permits the use of pure specifier (=0) on function definition,
12953 // defined at class scope, warn about this non-standard construct.
12954 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12955 Diag(FD->getLocation(), diag::ext_pure_function_definition);
12957 if (!FD->isInvalidDecl()) {
12958 // Don't diagnose unused parameters of defaulted or deleted functions.
12959 if (!FD->isDeleted() && !FD->isDefaulted())
12960 DiagnoseUnusedParameters(FD->parameters());
12961 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12962 FD->getReturnType(), FD);
12964 // If this is a structor, we need a vtable.
12965 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12966 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12967 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12968 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12970 // Try to apply the named return value optimization. We have to check
12971 // if we can do this here because lambdas keep return statements around
12972 // to deduce an implicit return type.
12973 if (FD->getReturnType()->isRecordType() &&
12974 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
12975 computeNRVO(Body, getCurFunction());
12978 // GNU warning -Wmissing-prototypes:
12979 // Warn if a global function is defined without a previous
12980 // prototype declaration. This warning is issued even if the
12981 // definition itself provides a prototype. The aim is to detect
12982 // global functions that fail to be declared in header files.
12983 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12984 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12985 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12987 if (PossibleZeroParamPrototype) {
12988 // We found a declaration that is not a prototype,
12989 // but that could be a zero-parameter prototype
12990 if (TypeSourceInfo *TI =
12991 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12992 TypeLoc TL = TI->getTypeLoc();
12993 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12994 Diag(PossibleZeroParamPrototype->getLocation(),
12995 diag::note_declaration_not_a_prototype)
12996 << PossibleZeroParamPrototype
12997 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13001 // GNU warning -Wstrict-prototypes
13002 // Warn if K&R function is defined without a previous declaration.
13003 // This warning is issued only if the definition itself does not provide
13004 // a prototype. Only K&R definitions do not provide a prototype.
13005 // An empty list in a function declarator that is part of a definition
13006 // of that function specifies that the function has no parameters
13007 // (C99 6.7.5.3p14)
13008 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13009 !LangOpts.CPlusPlus) {
13010 TypeSourceInfo *TI = FD->getTypeSourceInfo();
13011 TypeLoc TL = TI->getTypeLoc();
13012 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13013 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13017 // Warn on CPUDispatch with an actual body.
13018 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13019 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13020 if (!CmpndBody->body_empty())
13021 Diag(CmpndBody->body_front()->getLocStart(),
13022 diag::warn_dispatch_body_ignored);
13024 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13025 const CXXMethodDecl *KeyFunction;
13026 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13028 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13029 MD == KeyFunction->getCanonicalDecl()) {
13030 // Update the key-function state if necessary for this ABI.
13031 if (FD->isInlined() &&
13032 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13033 Context.setNonKeyFunction(MD);
13035 // If the newly-chosen key function is already defined, then we
13036 // need to mark the vtable as used retroactively.
13037 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13038 const FunctionDecl *Definition;
13039 if (KeyFunction && KeyFunction->isDefined(Definition))
13040 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13042 // We just defined they key function; mark the vtable as used.
13043 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13048 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13049 "Function parsing confused");
13050 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13051 assert(MD == getCurMethodDecl() && "Method parsing confused");
13053 if (!MD->isInvalidDecl()) {
13054 DiagnoseUnusedParameters(MD->parameters());
13055 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13056 MD->getReturnType(), MD);
13059 computeNRVO(Body, getCurFunction());
13061 if (getCurFunction()->ObjCShouldCallSuper) {
13062 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
13063 << MD->getSelector().getAsString();
13064 getCurFunction()->ObjCShouldCallSuper = false;
13066 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13067 const ObjCMethodDecl *InitMethod = nullptr;
13068 bool isDesignated =
13069 MD->isDesignatedInitializerForTheInterface(&InitMethod);
13070 assert(isDesignated && InitMethod);
13071 (void)isDesignated;
13073 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13074 auto IFace = MD->getClassInterface();
13077 auto SuperD = IFace->getSuperClass();
13080 return SuperD->getIdentifier() ==
13081 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13083 // Don't issue this warning for unavailable inits or direct subclasses
13085 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13086 Diag(MD->getLocation(),
13087 diag::warn_objc_designated_init_missing_super_call);
13088 Diag(InitMethod->getLocation(),
13089 diag::note_objc_designated_init_marked_here);
13091 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13093 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13094 // Don't issue this warning for unavaialable inits.
13095 if (!MD->isUnavailable())
13096 Diag(MD->getLocation(),
13097 diag::warn_objc_secondary_init_missing_init_call);
13098 getCurFunction()->ObjCWarnForNoInitDelegation = false;
13101 // Parsing the function declaration failed in some way. Pop the fake scope
13103 PopFunctionScopeInfo(ActivePolicy, dcl);
13107 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13108 DiagnoseUnguardedAvailabilityViolations(dcl);
13110 assert(!getCurFunction()->ObjCShouldCallSuper &&
13111 "This should only be set for ObjC methods, which should have been "
13112 "handled in the block above.");
13114 // Verify and clean out per-function state.
13115 if (Body && (!FD || !FD->isDefaulted())) {
13116 // C++ constructors that have function-try-blocks can't have return
13117 // statements in the handlers of that block. (C++ [except.handle]p14)
13119 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13120 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13122 // Verify that gotos and switch cases don't jump into scopes illegally.
13123 if (getCurFunction()->NeedsScopeChecking() &&
13124 !PP.isCodeCompletionEnabled())
13125 DiagnoseInvalidJumps(Body);
13127 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13128 if (!Destructor->getParent()->isDependentType())
13129 CheckDestructor(Destructor);
13131 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13132 Destructor->getParent());
13135 // If any errors have occurred, clear out any temporaries that may have
13136 // been leftover. This ensures that these temporaries won't be picked up for
13137 // deletion in some later function.
13138 if (getDiagnostics().hasErrorOccurred() ||
13139 getDiagnostics().getSuppressAllDiagnostics()) {
13140 DiscardCleanupsInEvaluationContext();
13142 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13143 !isa<FunctionTemplateDecl>(dcl)) {
13144 // Since the body is valid, issue any analysis-based warnings that are
13146 ActivePolicy = &WP;
13149 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13150 (!CheckConstexprFunctionDecl(FD) ||
13151 !CheckConstexprFunctionBody(FD, Body)))
13152 FD->setInvalidDecl();
13154 if (FD && FD->hasAttr<NakedAttr>()) {
13155 for (const Stmt *S : Body->children()) {
13156 // Allow local register variables without initializer as they don't
13157 // require prologue.
13158 bool RegisterVariables = false;
13159 if (auto *DS = dyn_cast<DeclStmt>(S)) {
13160 for (const auto *Decl : DS->decls()) {
13161 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13162 RegisterVariables =
13163 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13164 if (!RegisterVariables)
13169 if (RegisterVariables)
13171 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13172 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
13173 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13174 FD->setInvalidDecl();
13180 assert(ExprCleanupObjects.size() ==
13181 ExprEvalContexts.back().NumCleanupObjects &&
13182 "Leftover temporaries in function");
13183 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13184 assert(MaybeODRUseExprs.empty() &&
13185 "Leftover expressions for odr-use checking");
13188 if (!IsInstantiation)
13191 PopFunctionScopeInfo(ActivePolicy, dcl);
13192 // If any errors have occurred, clear out any temporaries that may have
13193 // been leftover. This ensures that these temporaries won't be picked up for
13194 // deletion in some later function.
13195 if (getDiagnostics().hasErrorOccurred()) {
13196 DiscardCleanupsInEvaluationContext();
13202 /// When we finish delayed parsing of an attribute, we must attach it to the
13204 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13205 ParsedAttributes &Attrs) {
13206 // Always attach attributes to the underlying decl.
13207 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13208 D = TD->getTemplatedDecl();
13209 ProcessDeclAttributeList(S, D, Attrs);
13211 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13212 if (Method->isStatic())
13213 checkThisInStaticMemberFunctionAttributes(Method);
13216 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13217 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13218 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13219 IdentifierInfo &II, Scope *S) {
13220 // Find the scope in which the identifier is injected and the corresponding
13222 // FIXME: C89 does not say what happens if there is no enclosing block scope.
13223 // In that case, we inject the declaration into the translation unit scope
13225 Scope *BlockScope = S;
13226 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13227 BlockScope = BlockScope->getParent();
13229 Scope *ContextScope = BlockScope;
13230 while (!ContextScope->getEntity())
13231 ContextScope = ContextScope->getParent();
13232 ContextRAII SavedContext(*this, ContextScope->getEntity());
13234 // Before we produce a declaration for an implicitly defined
13235 // function, see whether there was a locally-scoped declaration of
13236 // this name as a function or variable. If so, use that
13237 // (non-visible) declaration, and complain about it.
13238 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13240 // We still need to inject the function into the enclosing block scope so
13241 // that later (non-call) uses can see it.
13242 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13244 // C89 footnote 38:
13245 // If in fact it is not defined as having type "function returning int",
13246 // the behavior is undefined.
13247 if (!isa<FunctionDecl>(ExternCPrev) ||
13248 !Context.typesAreCompatible(
13249 cast<FunctionDecl>(ExternCPrev)->getType(),
13250 Context.getFunctionNoProtoType(Context.IntTy))) {
13251 Diag(Loc, diag::ext_use_out_of_scope_declaration)
13252 << ExternCPrev << !getLangOpts().C99;
13253 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13254 return ExternCPrev;
13258 // Extension in C99. Legal in C90, but warn about it.
13259 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13261 if (II.getName().startswith("__builtin_"))
13262 diag_id = diag::warn_builtin_unknown;
13263 else if (getLangOpts().C99 || getLangOpts().OpenCL)
13264 diag_id = diag::ext_implicit_function_decl;
13266 diag_id = diag::warn_implicit_function_decl;
13267 Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
13269 // If we found a prior declaration of this function, don't bother building
13270 // another one. We've already pushed that one into scope, so there's nothing
13273 return ExternCPrev;
13275 // Because typo correction is expensive, only do it if the implicit
13276 // function declaration is going to be treated as an error.
13277 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13278 TypoCorrection Corrected;
13280 (Corrected = CorrectTypo(
13281 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13282 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13283 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13284 /*ErrorRecovery*/false);
13287 // Set a Declarator for the implicit definition: int foo();
13289 AttributeFactory attrFactory;
13290 DeclSpec DS(attrFactory);
13292 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13293 Context.getPrintingPolicy());
13294 (void)Error; // Silence warning.
13295 assert(!Error && "Error setting up implicit decl!");
13296 SourceLocation NoLoc;
13297 Declarator D(DS, DeclaratorContext::BlockContext);
13298 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13299 /*IsAmbiguous=*/false,
13300 /*LParenLoc=*/NoLoc,
13301 /*Params=*/nullptr,
13303 /*EllipsisLoc=*/NoLoc,
13304 /*RParenLoc=*/NoLoc,
13306 /*RefQualifierIsLvalueRef=*/true,
13307 /*RefQualifierLoc=*/NoLoc,
13308 /*ConstQualifierLoc=*/NoLoc,
13309 /*VolatileQualifierLoc=*/NoLoc,
13310 /*RestrictQualifierLoc=*/NoLoc,
13311 /*MutableLoc=*/NoLoc, EST_None,
13312 /*ESpecRange=*/SourceRange(),
13313 /*Exceptions=*/nullptr,
13314 /*ExceptionRanges=*/nullptr,
13315 /*NumExceptions=*/0,
13316 /*NoexceptExpr=*/nullptr,
13317 /*ExceptionSpecTokens=*/nullptr,
13318 /*DeclsInPrototype=*/None, Loc,
13320 std::move(DS.getAttributes()), SourceLocation());
13321 D.SetIdentifier(&II, Loc);
13323 // Insert this function into the enclosing block scope.
13324 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13327 AddKnownFunctionAttributes(FD);
13332 /// Adds any function attributes that we know a priori based on
13333 /// the declaration of this function.
13335 /// These attributes can apply both to implicitly-declared builtins
13336 /// (like __builtin___printf_chk) or to library-declared functions
13337 /// like NSLog or printf.
13339 /// We need to check for duplicate attributes both here and where user-written
13340 /// attributes are applied to declarations.
13341 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13342 if (FD->isInvalidDecl())
13345 // If this is a built-in function, map its builtin attributes to
13346 // actual attributes.
13347 if (unsigned BuiltinID = FD->getBuiltinID()) {
13348 // Handle printf-formatting attributes.
13349 unsigned FormatIdx;
13351 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13352 if (!FD->hasAttr<FormatAttr>()) {
13353 const char *fmt = "printf";
13354 unsigned int NumParams = FD->getNumParams();
13355 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13356 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13358 FD->addAttr(FormatAttr::CreateImplicit(Context,
13359 &Context.Idents.get(fmt),
13361 HasVAListArg ? 0 : FormatIdx+2,
13362 FD->getLocation()));
13365 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13367 if (!FD->hasAttr<FormatAttr>())
13368 FD->addAttr(FormatAttr::CreateImplicit(Context,
13369 &Context.Idents.get("scanf"),
13371 HasVAListArg ? 0 : FormatIdx+2,
13372 FD->getLocation()));
13375 // Mark const if we don't care about errno and that is the only thing
13376 // preventing the function from being const. This allows IRgen to use LLVM
13377 // intrinsics for such functions.
13378 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13379 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13380 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13382 // We make "fma" on some platforms const because we know it does not set
13383 // errno in those environments even though it could set errno based on the
13385 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13386 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13387 !FD->hasAttr<ConstAttr>()) {
13388 switch (BuiltinID) {
13389 case Builtin::BI__builtin_fma:
13390 case Builtin::BI__builtin_fmaf:
13391 case Builtin::BI__builtin_fmal:
13392 case Builtin::BIfma:
13393 case Builtin::BIfmaf:
13394 case Builtin::BIfmal:
13395 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13402 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13403 !FD->hasAttr<ReturnsTwiceAttr>())
13404 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13405 FD->getLocation()));
13406 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13407 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13408 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13409 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13410 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13411 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13412 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13413 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13414 // Add the appropriate attribute, depending on the CUDA compilation mode
13415 // and which target the builtin belongs to. For example, during host
13416 // compilation, aux builtins are __device__, while the rest are __host__.
13417 if (getLangOpts().CUDAIsDevice !=
13418 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13419 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13421 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13425 // If C++ exceptions are enabled but we are told extern "C" functions cannot
13426 // throw, add an implicit nothrow attribute to any extern "C" function we come
13428 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13429 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13430 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13431 if (!FPT || FPT->getExceptionSpecType() == EST_None)
13432 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13435 IdentifierInfo *Name = FD->getIdentifier();
13438 if ((!getLangOpts().CPlusPlus &&
13439 FD->getDeclContext()->isTranslationUnit()) ||
13440 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13441 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13442 LinkageSpecDecl::lang_c)) {
13443 // Okay: this could be a libc/libm/Objective-C function we know
13448 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13449 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13450 // target-specific builtins, perhaps?
13451 if (!FD->hasAttr<FormatAttr>())
13452 FD->addAttr(FormatAttr::CreateImplicit(Context,
13453 &Context.Idents.get("printf"), 2,
13454 Name->isStr("vasprintf") ? 0 : 3,
13455 FD->getLocation()));
13458 if (Name->isStr("__CFStringMakeConstantString")) {
13459 // We already have a __builtin___CFStringMakeConstantString,
13460 // but builds that use -fno-constant-cfstrings don't go through that.
13461 if (!FD->hasAttr<FormatArgAttr>())
13462 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13463 FD->getLocation()));
13467 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13468 TypeSourceInfo *TInfo) {
13469 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13470 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13473 assert(D.isInvalidType() && "no declarator info for valid type");
13474 TInfo = Context.getTrivialTypeSourceInfo(T);
13477 // Scope manipulation handled by caller.
13478 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
13480 D.getIdentifierLoc(),
13484 // Bail out immediately if we have an invalid declaration.
13485 if (D.isInvalidType()) {
13486 NewTD->setInvalidDecl();
13490 if (D.getDeclSpec().isModulePrivateSpecified()) {
13491 if (CurContext->isFunctionOrMethod())
13492 Diag(NewTD->getLocation(), diag::err_module_private_local)
13493 << 2 << NewTD->getDeclName()
13494 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13495 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13497 NewTD->setModulePrivate();
13500 // C++ [dcl.typedef]p8:
13501 // If the typedef declaration defines an unnamed class (or
13502 // enum), the first typedef-name declared by the declaration
13503 // to be that class type (or enum type) is used to denote the
13504 // class type (or enum type) for linkage purposes only.
13505 // We need to check whether the type was declared in the declaration.
13506 switch (D.getDeclSpec().getTypeSpecType()) {
13509 case TST_interface:
13512 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13513 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13524 /// Check that this is a valid underlying type for an enum declaration.
13525 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13526 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13527 QualType T = TI->getType();
13529 if (T->isDependentType())
13532 if (const BuiltinType *BT = T->getAs<BuiltinType>())
13533 if (BT->isInteger())
13536 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13540 /// Check whether this is a valid redeclaration of a previous enumeration.
13541 /// \return true if the redeclaration was invalid.
13542 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13543 QualType EnumUnderlyingTy, bool IsFixed,
13544 const EnumDecl *Prev) {
13545 if (IsScoped != Prev->isScoped()) {
13546 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13547 << Prev->isScoped();
13548 Diag(Prev->getLocation(), diag::note_previous_declaration);
13552 if (IsFixed && Prev->isFixed()) {
13553 if (!EnumUnderlyingTy->isDependentType() &&
13554 !Prev->getIntegerType()->isDependentType() &&
13555 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13556 Prev->getIntegerType())) {
13557 // TODO: Highlight the underlying type of the redeclaration.
13558 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13559 << EnumUnderlyingTy << Prev->getIntegerType();
13560 Diag(Prev->getLocation(), diag::note_previous_declaration)
13561 << Prev->getIntegerTypeRange();
13564 } else if (IsFixed != Prev->isFixed()) {
13565 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13566 << Prev->isFixed();
13567 Diag(Prev->getLocation(), diag::note_previous_declaration);
13574 /// Get diagnostic %select index for tag kind for
13575 /// redeclaration diagnostic message.
13576 /// WARNING: Indexes apply to particular diagnostics only!
13578 /// \returns diagnostic %select index.
13579 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13581 case TTK_Struct: return 0;
13582 case TTK_Interface: return 1;
13583 case TTK_Class: return 2;
13584 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13588 /// Determine if tag kind is a class-key compatible with
13589 /// class for redeclaration (class, struct, or __interface).
13591 /// \returns true iff the tag kind is compatible.
13592 static bool isClassCompatTagKind(TagTypeKind Tag)
13594 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13597 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13599 if (isa<TypedefDecl>(PrevDecl))
13600 return NTK_Typedef;
13601 else if (isa<TypeAliasDecl>(PrevDecl))
13602 return NTK_TypeAlias;
13603 else if (isa<ClassTemplateDecl>(PrevDecl))
13604 return NTK_Template;
13605 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13606 return NTK_TypeAliasTemplate;
13607 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13608 return NTK_TemplateTemplateArgument;
13611 case TTK_Interface:
13613 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13615 return NTK_NonUnion;
13617 return NTK_NonEnum;
13619 llvm_unreachable("invalid TTK");
13622 /// Determine whether a tag with a given kind is acceptable
13623 /// as a redeclaration of the given tag declaration.
13625 /// \returns true if the new tag kind is acceptable, false otherwise.
13626 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13627 TagTypeKind NewTag, bool isDefinition,
13628 SourceLocation NewTagLoc,
13629 const IdentifierInfo *Name) {
13630 // C++ [dcl.type.elab]p3:
13631 // The class-key or enum keyword present in the
13632 // elaborated-type-specifier shall agree in kind with the
13633 // declaration to which the name in the elaborated-type-specifier
13634 // refers. This rule also applies to the form of
13635 // elaborated-type-specifier that declares a class-name or
13636 // friend class since it can be construed as referring to the
13637 // definition of the class. Thus, in any
13638 // elaborated-type-specifier, the enum keyword shall be used to
13639 // refer to an enumeration (7.2), the union class-key shall be
13640 // used to refer to a union (clause 9), and either the class or
13641 // struct class-key shall be used to refer to a class (clause 9)
13642 // declared using the class or struct class-key.
13643 TagTypeKind OldTag = Previous->getTagKind();
13644 if (!isDefinition || !isClassCompatTagKind(NewTag))
13645 if (OldTag == NewTag)
13648 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13649 // Warn about the struct/class tag mismatch.
13650 bool isTemplate = false;
13651 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13652 isTemplate = Record->getDescribedClassTemplate();
13654 if (inTemplateInstantiation()) {
13655 // In a template instantiation, do not offer fix-its for tag mismatches
13656 // since they usually mess up the template instead of fixing the problem.
13657 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13658 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13659 << getRedeclDiagFromTagKind(OldTag);
13663 if (isDefinition) {
13664 // On definitions, check previous tags and issue a fix-it for each
13665 // one that doesn't match the current tag.
13666 if (Previous->getDefinition()) {
13667 // Don't suggest fix-its for redefinitions.
13671 bool previousMismatch = false;
13672 for (auto I : Previous->redecls()) {
13673 if (I->getTagKind() != NewTag) {
13674 if (!previousMismatch) {
13675 previousMismatch = true;
13676 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13677 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13678 << getRedeclDiagFromTagKind(I->getTagKind());
13680 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13681 << getRedeclDiagFromTagKind(NewTag)
13682 << FixItHint::CreateReplacement(I->getInnerLocStart(),
13683 TypeWithKeyword::getTagTypeKindName(NewTag));
13689 // Check for a previous definition. If current tag and definition
13690 // are same type, do nothing. If no definition, but disagree with
13691 // with previous tag type, give a warning, but no fix-it.
13692 const TagDecl *Redecl = Previous->getDefinition() ?
13693 Previous->getDefinition() : Previous;
13694 if (Redecl->getTagKind() == NewTag) {
13698 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13699 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13700 << getRedeclDiagFromTagKind(OldTag);
13701 Diag(Redecl->getLocation(), diag::note_previous_use);
13703 // If there is a previous definition, suggest a fix-it.
13704 if (Previous->getDefinition()) {
13705 Diag(NewTagLoc, diag::note_struct_class_suggestion)
13706 << getRedeclDiagFromTagKind(Redecl->getTagKind())
13707 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13708 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13716 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13717 /// from an outer enclosing namespace or file scope inside a friend declaration.
13718 /// This should provide the commented out code in the following snippet:
13722 /// struct Y { friend struct /*N::*/ X; };
13725 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13726 SourceLocation NameLoc) {
13727 // While the decl is in a namespace, do repeated lookup of that name and see
13728 // if we get the same namespace back. If we do not, continue until
13729 // translation unit scope, at which point we have a fully qualified NNS.
13730 SmallVector<IdentifierInfo *, 4> Namespaces;
13731 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13732 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13733 // This tag should be declared in a namespace, which can only be enclosed by
13734 // other namespaces. Bail if there's an anonymous namespace in the chain.
13735 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13736 if (!Namespace || Namespace->isAnonymousNamespace())
13737 return FixItHint();
13738 IdentifierInfo *II = Namespace->getIdentifier();
13739 Namespaces.push_back(II);
13740 NamedDecl *Lookup = SemaRef.LookupSingleName(
13741 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13742 if (Lookup == Namespace)
13746 // Once we have all the namespaces, reverse them to go outermost first, and
13748 SmallString<64> Insertion;
13749 llvm::raw_svector_ostream OS(Insertion);
13750 if (DC->isTranslationUnit())
13752 std::reverse(Namespaces.begin(), Namespaces.end());
13753 for (auto *II : Namespaces)
13754 OS << II->getName() << "::";
13755 return FixItHint::CreateInsertion(NameLoc, Insertion);
13758 /// Determine whether a tag originally declared in context \p OldDC can
13759 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
13760 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13761 /// using-declaration).
13762 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13763 DeclContext *NewDC) {
13764 OldDC = OldDC->getRedeclContext();
13765 NewDC = NewDC->getRedeclContext();
13767 if (OldDC->Equals(NewDC))
13770 // In MSVC mode, we allow a redeclaration if the contexts are related (either
13771 // encloses the other).
13772 if (S.getLangOpts().MSVCCompat &&
13773 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13779 /// This is invoked when we see 'struct foo' or 'struct {'. In the
13780 /// former case, Name will be non-null. In the later case, Name will be null.
13781 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13782 /// reference/declaration/definition of a tag.
13784 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13785 /// trailing-type-specifier) other than one in an alias-declaration.
13787 /// \param SkipBody If non-null, will be set to indicate if the caller should
13788 /// skip the definition of this tag and treat it as if it were a declaration.
13789 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13790 SourceLocation KWLoc, CXXScopeSpec &SS,
13791 IdentifierInfo *Name, SourceLocation NameLoc,
13792 const ParsedAttributesView &Attrs, AccessSpecifier AS,
13793 SourceLocation ModulePrivateLoc,
13794 MultiTemplateParamsArg TemplateParameterLists,
13795 bool &OwnedDecl, bool &IsDependent,
13796 SourceLocation ScopedEnumKWLoc,
13797 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
13798 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13799 SkipBodyInfo *SkipBody) {
13800 // If this is not a definition, it must have a name.
13801 IdentifierInfo *OrigName = Name;
13802 assert((Name != nullptr || TUK == TUK_Definition) &&
13803 "Nameless record must be a definition!");
13804 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13807 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13808 bool ScopedEnum = ScopedEnumKWLoc.isValid();
13810 // FIXME: Check member specializations more carefully.
13811 bool isMemberSpecialization = false;
13812 bool Invalid = false;
13814 // We only need to do this matching if we have template parameters
13815 // or a scope specifier, which also conveniently avoids this work
13816 // for non-C++ cases.
13817 if (TemplateParameterLists.size() > 0 ||
13818 (SS.isNotEmpty() && TUK != TUK_Reference)) {
13819 if (TemplateParameterList *TemplateParams =
13820 MatchTemplateParametersToScopeSpecifier(
13821 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13822 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13823 if (Kind == TTK_Enum) {
13824 Diag(KWLoc, diag::err_enum_template);
13828 if (TemplateParams->size() > 0) {
13829 // This is a declaration or definition of a class template (which may
13830 // be a member of another template).
13836 DeclResult Result = CheckClassTemplate(
13837 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
13838 AS, ModulePrivateLoc,
13839 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
13840 TemplateParameterLists.data(), SkipBody);
13841 return Result.get();
13843 // The "template<>" header is extraneous.
13844 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13845 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13846 isMemberSpecialization = true;
13851 // Figure out the underlying type if this a enum declaration. We need to do
13852 // this early, because it's needed to detect if this is an incompatible
13854 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13855 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
13857 if (Kind == TTK_Enum) {
13858 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
13859 // No underlying type explicitly specified, or we failed to parse the
13860 // type, default to int.
13861 EnumUnderlying = Context.IntTy.getTypePtr();
13862 } else if (UnderlyingType.get()) {
13863 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13864 // integral type; any cv-qualification is ignored.
13865 TypeSourceInfo *TI = nullptr;
13866 GetTypeFromParser(UnderlyingType.get(), &TI);
13867 EnumUnderlying = TI;
13869 if (CheckEnumUnderlyingType(TI))
13870 // Recover by falling back to int.
13871 EnumUnderlying = Context.IntTy.getTypePtr();
13873 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13874 UPPC_FixedUnderlyingType))
13875 EnumUnderlying = Context.IntTy.getTypePtr();
13877 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13878 // For MSVC ABI compatibility, unfixed enums must use an underlying type
13879 // of 'int'. However, if this is an unfixed forward declaration, don't set
13880 // the underlying type unless the user enables -fms-compatibility. This
13881 // makes unfixed forward declared enums incomplete and is more conforming.
13882 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
13883 EnumUnderlying = Context.IntTy.getTypePtr();
13887 DeclContext *SearchDC = CurContext;
13888 DeclContext *DC = CurContext;
13889 bool isStdBadAlloc = false;
13890 bool isStdAlignValT = false;
13892 RedeclarationKind Redecl = forRedeclarationInCurContext();
13893 if (TUK == TUK_Friend || TUK == TUK_Reference)
13894 Redecl = NotForRedeclaration;
13896 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13897 /// implemented asks for structural equivalence checking, the returned decl
13898 /// here is passed back to the parser, allowing the tag body to be parsed.
13899 auto createTagFromNewDecl = [&]() -> TagDecl * {
13900 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13901 // If there is an identifier, use the location of the identifier as the
13902 // location of the decl, otherwise use the location of the struct/union
13904 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13905 TagDecl *New = nullptr;
13907 if (Kind == TTK_Enum) {
13908 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13909 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
13910 // If this is an undefined enum, bail.
13911 if (TUK != TUK_Definition && !Invalid)
13913 if (EnumUnderlying) {
13914 EnumDecl *ED = cast<EnumDecl>(New);
13915 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13916 ED->setIntegerTypeSourceInfo(TI);
13918 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13919 ED->setPromotionType(ED->getIntegerType());
13921 } else { // struct/union
13922 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13926 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13927 // Add alignment attributes if necessary; these attributes are checked
13928 // when the ASTContext lays out the structure.
13930 // It is important for implementing the correct semantics that this
13931 // happen here (in ActOnTag). The #pragma pack stack is
13932 // maintained as a result of parser callbacks which can occur at
13933 // many points during the parsing of a struct declaration (because
13934 // the #pragma tokens are effectively skipped over during the
13935 // parsing of the struct).
13936 if (TUK == TUK_Definition) {
13937 AddAlignmentAttributesForRecord(RD);
13938 AddMsStructLayoutForRecord(RD);
13941 New->setLexicalDeclContext(CurContext);
13945 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13946 if (Name && SS.isNotEmpty()) {
13947 // We have a nested-name tag ('struct foo::bar').
13949 // Check for invalid 'foo::'.
13950 if (SS.isInvalid()) {
13952 goto CreateNewDecl;
13955 // If this is a friend or a reference to a class in a dependent
13956 // context, don't try to make a decl for it.
13957 if (TUK == TUK_Friend || TUK == TUK_Reference) {
13958 DC = computeDeclContext(SS, false);
13960 IsDependent = true;
13964 DC = computeDeclContext(SS, true);
13966 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13972 if (RequireCompleteDeclContext(SS, DC))
13976 // Look-up name inside 'foo::'.
13977 LookupQualifiedName(Previous, DC);
13979 if (Previous.isAmbiguous())
13982 if (Previous.empty()) {
13983 // Name lookup did not find anything. However, if the
13984 // nested-name-specifier refers to the current instantiation,
13985 // and that current instantiation has any dependent base
13986 // classes, we might find something at instantiation time: treat
13987 // this as a dependent elaborated-type-specifier.
13988 // But this only makes any sense for reference-like lookups.
13989 if (Previous.wasNotFoundInCurrentInstantiation() &&
13990 (TUK == TUK_Reference || TUK == TUK_Friend)) {
13991 IsDependent = true;
13995 // A tag 'foo::bar' must already exist.
13996 Diag(NameLoc, diag::err_not_tag_in_scope)
13997 << Kind << Name << DC << SS.getRange();
14000 goto CreateNewDecl;
14003 // C++14 [class.mem]p14:
14004 // If T is the name of a class, then each of the following shall have a
14005 // name different from T:
14006 // -- every member of class T that is itself a type
14007 if (TUK != TUK_Reference && TUK != TUK_Friend &&
14008 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14011 // If this is a named struct, check to see if there was a previous forward
14012 // declaration or definition.
14013 // FIXME: We're looking into outer scopes here, even when we
14014 // shouldn't be. Doing so can result in ambiguities that we
14015 // shouldn't be diagnosing.
14016 LookupName(Previous, S);
14018 // When declaring or defining a tag, ignore ambiguities introduced
14019 // by types using'ed into this scope.
14020 if (Previous.isAmbiguous() &&
14021 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14022 LookupResult::Filter F = Previous.makeFilter();
14023 while (F.hasNext()) {
14024 NamedDecl *ND = F.next();
14025 if (!ND->getDeclContext()->getRedeclContext()->Equals(
14026 SearchDC->getRedeclContext()))
14032 // C++11 [namespace.memdef]p3:
14033 // If the name in a friend declaration is neither qualified nor
14034 // a template-id and the declaration is a function or an
14035 // elaborated-type-specifier, the lookup to determine whether
14036 // the entity has been previously declared shall not consider
14037 // any scopes outside the innermost enclosing namespace.
14039 // MSVC doesn't implement the above rule for types, so a friend tag
14040 // declaration may be a redeclaration of a type declared in an enclosing
14041 // scope. They do implement this rule for friend functions.
14043 // Does it matter that this should be by scope instead of by
14044 // semantic context?
14045 if (!Previous.empty() && TUK == TUK_Friend) {
14046 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14047 LookupResult::Filter F = Previous.makeFilter();
14048 bool FriendSawTagOutsideEnclosingNamespace = false;
14049 while (F.hasNext()) {
14050 NamedDecl *ND = F.next();
14051 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14052 if (DC->isFileContext() &&
14053 !EnclosingNS->Encloses(ND->getDeclContext())) {
14054 if (getLangOpts().MSVCCompat)
14055 FriendSawTagOutsideEnclosingNamespace = true;
14062 // Diagnose this MSVC extension in the easy case where lookup would have
14063 // unambiguously found something outside the enclosing namespace.
14064 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14065 NamedDecl *ND = Previous.getFoundDecl();
14066 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14067 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14071 // Note: there used to be some attempt at recovery here.
14072 if (Previous.isAmbiguous())
14075 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14076 // FIXME: This makes sure that we ignore the contexts associated
14077 // with C structs, unions, and enums when looking for a matching
14078 // tag declaration or definition. See the similar lookup tweak
14079 // in Sema::LookupName; is there a better way to deal with this?
14080 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14081 SearchDC = SearchDC->getParent();
14085 if (Previous.isSingleResult() &&
14086 Previous.getFoundDecl()->isTemplateParameter()) {
14087 // Maybe we will complain about the shadowed template parameter.
14088 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14089 // Just pretend that we didn't see the previous declaration.
14093 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14094 DC->Equals(getStdNamespace())) {
14095 if (Name->isStr("bad_alloc")) {
14096 // This is a declaration of or a reference to "std::bad_alloc".
14097 isStdBadAlloc = true;
14099 // If std::bad_alloc has been implicitly declared (but made invisible to
14100 // name lookup), fill in this implicit declaration as the previous
14101 // declaration, so that the declarations get chained appropriately.
14102 if (Previous.empty() && StdBadAlloc)
14103 Previous.addDecl(getStdBadAlloc());
14104 } else if (Name->isStr("align_val_t")) {
14105 isStdAlignValT = true;
14106 if (Previous.empty() && StdAlignValT)
14107 Previous.addDecl(getStdAlignValT());
14111 // If we didn't find a previous declaration, and this is a reference
14112 // (or friend reference), move to the correct scope. In C++, we
14113 // also need to do a redeclaration lookup there, just in case
14114 // there's a shadow friend decl.
14115 if (Name && Previous.empty() &&
14116 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14117 if (Invalid) goto CreateNewDecl;
14118 assert(SS.isEmpty());
14120 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14121 // C++ [basic.scope.pdecl]p5:
14122 // -- for an elaborated-type-specifier of the form
14124 // class-key identifier
14126 // if the elaborated-type-specifier is used in the
14127 // decl-specifier-seq or parameter-declaration-clause of a
14128 // function defined in namespace scope, the identifier is
14129 // declared as a class-name in the namespace that contains
14130 // the declaration; otherwise, except as a friend
14131 // declaration, the identifier is declared in the smallest
14132 // non-class, non-function-prototype scope that contains the
14135 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14136 // C structs and unions.
14138 // It is an error in C++ to declare (rather than define) an enum
14139 // type, including via an elaborated type specifier. We'll
14140 // diagnose that later; for now, declare the enum in the same
14141 // scope as we would have picked for any other tag type.
14143 // GNU C also supports this behavior as part of its incomplete
14144 // enum types extension, while GNU C++ does not.
14146 // Find the context where we'll be declaring the tag.
14147 // FIXME: We would like to maintain the current DeclContext as the
14148 // lexical context,
14149 SearchDC = getTagInjectionContext(SearchDC);
14151 // Find the scope where we'll be declaring the tag.
14152 S = getTagInjectionScope(S, getLangOpts());
14154 assert(TUK == TUK_Friend);
14155 // C++ [namespace.memdef]p3:
14156 // If a friend declaration in a non-local class first declares a
14157 // class or function, the friend class or function is a member of
14158 // the innermost enclosing namespace.
14159 SearchDC = SearchDC->getEnclosingNamespaceContext();
14162 // In C++, we need to do a redeclaration lookup to properly
14163 // diagnose some problems.
14164 // FIXME: redeclaration lookup is also used (with and without C++) to find a
14165 // hidden declaration so that we don't get ambiguity errors when using a
14166 // type declared by an elaborated-type-specifier. In C that is not correct
14167 // and we should instead merge compatible types found by lookup.
14168 if (getLangOpts().CPlusPlus) {
14169 Previous.setRedeclarationKind(forRedeclarationInCurContext());
14170 LookupQualifiedName(Previous, SearchDC);
14172 Previous.setRedeclarationKind(forRedeclarationInCurContext());
14173 LookupName(Previous, S);
14177 // If we have a known previous declaration to use, then use it.
14178 if (Previous.empty() && SkipBody && SkipBody->Previous)
14179 Previous.addDecl(SkipBody->Previous);
14181 if (!Previous.empty()) {
14182 NamedDecl *PrevDecl = Previous.getFoundDecl();
14183 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14185 // It's okay to have a tag decl in the same scope as a typedef
14186 // which hides a tag decl in the same scope. Finding this
14187 // insanity with a redeclaration lookup can only actually happen
14190 // This is also okay for elaborated-type-specifiers, which is
14191 // technically forbidden by the current standard but which is
14192 // okay according to the likely resolution of an open issue;
14193 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14194 if (getLangOpts().CPlusPlus) {
14195 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14196 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14197 TagDecl *Tag = TT->getDecl();
14198 if (Tag->getDeclName() == Name &&
14199 Tag->getDeclContext()->getRedeclContext()
14200 ->Equals(TD->getDeclContext()->getRedeclContext())) {
14203 Previous.addDecl(Tag);
14204 Previous.resolveKind();
14210 // If this is a redeclaration of a using shadow declaration, it must
14211 // declare a tag in the same context. In MSVC mode, we allow a
14212 // redefinition if either context is within the other.
14213 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14214 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14215 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14216 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14217 !(OldTag && isAcceptableTagRedeclContext(
14218 *this, OldTag->getDeclContext(), SearchDC))) {
14219 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14220 Diag(Shadow->getTargetDecl()->getLocation(),
14221 diag::note_using_decl_target);
14222 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14224 // Recover by ignoring the old declaration.
14226 goto CreateNewDecl;
14230 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14231 // If this is a use of a previous tag, or if the tag is already declared
14232 // in the same scope (so that the definition/declaration completes or
14233 // rementions the tag), reuse the decl.
14234 if (TUK == TUK_Reference || TUK == TUK_Friend ||
14235 isDeclInScope(DirectPrevDecl, SearchDC, S,
14236 SS.isNotEmpty() || isMemberSpecialization)) {
14237 // Make sure that this wasn't declared as an enum and now used as a
14238 // struct or something similar.
14239 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14240 TUK == TUK_Definition, KWLoc,
14242 bool SafeToContinue
14243 = (PrevTagDecl->getTagKind() != TTK_Enum &&
14245 if (SafeToContinue)
14246 Diag(KWLoc, diag::err_use_with_wrong_tag)
14248 << FixItHint::CreateReplacement(SourceRange(KWLoc),
14249 PrevTagDecl->getKindName());
14251 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14252 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14254 if (SafeToContinue)
14255 Kind = PrevTagDecl->getTagKind();
14257 // Recover by making this an anonymous redefinition.
14264 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14265 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14267 // If this is an elaborated-type-specifier for a scoped enumeration,
14268 // the 'class' keyword is not necessary and not permitted.
14269 if (TUK == TUK_Reference || TUK == TUK_Friend) {
14271 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14272 << PrevEnum->isScoped()
14273 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14274 return PrevTagDecl;
14277 QualType EnumUnderlyingTy;
14278 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14279 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14280 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14281 EnumUnderlyingTy = QualType(T, 0);
14283 // All conflicts with previous declarations are recovered by
14284 // returning the previous declaration, unless this is a definition,
14285 // in which case we want the caller to bail out.
14286 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14287 ScopedEnum, EnumUnderlyingTy,
14288 IsFixed, PrevEnum))
14289 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14292 // C++11 [class.mem]p1:
14293 // A member shall not be declared twice in the member-specification,
14294 // except that a nested class or member class template can be declared
14295 // and then later defined.
14296 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14297 S->isDeclScope(PrevDecl)) {
14298 Diag(NameLoc, diag::ext_member_redeclared);
14299 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14303 // If this is a use, just return the declaration we found, unless
14304 // we have attributes.
14305 if (TUK == TUK_Reference || TUK == TUK_Friend) {
14306 if (!Attrs.empty()) {
14307 // FIXME: Diagnose these attributes. For now, we create a new
14308 // declaration to hold them.
14309 } else if (TUK == TUK_Reference &&
14310 (PrevTagDecl->getFriendObjectKind() ==
14311 Decl::FOK_Undeclared ||
14312 PrevDecl->getOwningModule() != getCurrentModule()) &&
14314 // This declaration is a reference to an existing entity, but
14315 // has different visibility from that entity: it either makes
14316 // a friend visible or it makes a type visible in a new module.
14317 // In either case, create a new declaration. We only do this if
14318 // the declaration would have meant the same thing if no prior
14319 // declaration were found, that is, if it was found in the same
14320 // scope where we would have injected a declaration.
14321 if (!getTagInjectionContext(CurContext)->getRedeclContext()
14322 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14323 return PrevTagDecl;
14324 // This is in the injected scope, create a new declaration in
14326 S = getTagInjectionScope(S, getLangOpts());
14328 return PrevTagDecl;
14332 // Diagnose attempts to redefine a tag.
14333 if (TUK == TUK_Definition) {
14334 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14335 // If we're defining a specialization and the previous definition
14336 // is from an implicit instantiation, don't emit an error
14337 // here; we'll catch this in the general case below.
14338 bool IsExplicitSpecializationAfterInstantiation = false;
14339 if (isMemberSpecialization) {
14340 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14341 IsExplicitSpecializationAfterInstantiation =
14342 RD->getTemplateSpecializationKind() !=
14343 TSK_ExplicitSpecialization;
14344 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14345 IsExplicitSpecializationAfterInstantiation =
14346 ED->getTemplateSpecializationKind() !=
14347 TSK_ExplicitSpecialization;
14350 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14351 // not keep more that one definition around (merge them). However,
14352 // ensure the decl passes the structural compatibility check in
14353 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14354 NamedDecl *Hidden = nullptr;
14355 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14356 // There is a definition of this tag, but it is not visible. We
14357 // explicitly make use of C++'s one definition rule here, and
14358 // assume that this definition is identical to the hidden one
14359 // we already have. Make the existing definition visible and
14360 // use it in place of this one.
14361 if (!getLangOpts().CPlusPlus) {
14362 // Postpone making the old definition visible until after we
14363 // complete parsing the new one and do the structural
14365 SkipBody->CheckSameAsPrevious = true;
14366 SkipBody->New = createTagFromNewDecl();
14367 SkipBody->Previous = Hidden;
14369 SkipBody->ShouldSkip = true;
14370 makeMergedDefinitionVisible(Hidden);
14373 } else if (!IsExplicitSpecializationAfterInstantiation) {
14374 // A redeclaration in function prototype scope in C isn't
14375 // visible elsewhere, so merely issue a warning.
14376 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14377 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14379 Diag(NameLoc, diag::err_redefinition) << Name;
14380 notePreviousDefinition(Def,
14381 NameLoc.isValid() ? NameLoc : KWLoc);
14382 // If this is a redefinition, recover by making this
14383 // struct be anonymous, which will make any later
14384 // references get the previous definition.
14390 // If the type is currently being defined, complain
14391 // about a nested redefinition.
14392 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14393 if (TD->isBeingDefined()) {
14394 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14395 Diag(PrevTagDecl->getLocation(),
14396 diag::note_previous_definition);
14403 // Okay, this is definition of a previously declared or referenced
14404 // tag. We're going to create a new Decl for it.
14407 // Okay, we're going to make a redeclaration. If this is some kind
14408 // of reference, make sure we build the redeclaration in the same DC
14409 // as the original, and ignore the current access specifier.
14410 if (TUK == TUK_Friend || TUK == TUK_Reference) {
14411 SearchDC = PrevTagDecl->getDeclContext();
14415 // If we get here we have (another) forward declaration or we
14416 // have a definition. Just create a new decl.
14419 // If we get here, this is a definition of a new tag type in a nested
14420 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14421 // new decl/type. We set PrevDecl to NULL so that the entities
14422 // have distinct types.
14425 // If we get here, we're going to create a new Decl. If PrevDecl
14426 // is non-NULL, it's a definition of the tag declared by
14427 // PrevDecl. If it's NULL, we have a new definition.
14429 // Otherwise, PrevDecl is not a tag, but was found with tag
14430 // lookup. This is only actually possible in C++, where a few
14431 // things like templates still live in the tag namespace.
14433 // Use a better diagnostic if an elaborated-type-specifier
14434 // found the wrong kind of type on the first
14435 // (non-redeclaration) lookup.
14436 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14437 !Previous.isForRedeclaration()) {
14438 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14439 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14441 Diag(PrevDecl->getLocation(), diag::note_declared_at);
14444 // Otherwise, only diagnose if the declaration is in scope.
14445 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14446 SS.isNotEmpty() || isMemberSpecialization)) {
14449 // Diagnose implicit declarations introduced by elaborated types.
14450 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14451 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14452 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14453 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14456 // Otherwise it's a declaration. Call out a particularly common
14458 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14460 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14461 Diag(NameLoc, diag::err_tag_definition_of_typedef)
14462 << Name << Kind << TND->getUnderlyingType();
14463 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14466 // Otherwise, diagnose.
14468 // The tag name clashes with something else in the target scope,
14469 // issue an error and recover by making this tag be anonymous.
14470 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14471 notePreviousDefinition(PrevDecl, NameLoc);
14476 // The existing declaration isn't relevant to us; we're in a
14477 // new scope, so clear out the previous declaration.
14484 TagDecl *PrevDecl = nullptr;
14485 if (Previous.isSingleResult())
14486 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14488 // If there is an identifier, use the location of the identifier as the
14489 // location of the decl, otherwise use the location of the struct/union
14491 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14493 // Otherwise, create a new declaration. If there is a previous
14494 // declaration of the same entity, the two will be linked via
14498 if (Kind == TTK_Enum) {
14499 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14500 // enum X { A, B, C } D; D should chain to X.
14501 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14502 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14503 ScopedEnumUsesClassTag, IsFixed);
14505 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14506 StdAlignValT = cast<EnumDecl>(New);
14508 // If this is an undefined enum, warn.
14509 if (TUK != TUK_Definition && !Invalid) {
14511 if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
14512 cast<EnumDecl>(New)->isFixed()) {
14513 // C++0x: 7.2p2: opaque-enum-declaration.
14514 // Conflicts are diagnosed above. Do nothing.
14516 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14517 Diag(Loc, diag::ext_forward_ref_enum_def)
14519 Diag(Def->getLocation(), diag::note_previous_definition);
14521 unsigned DiagID = diag::ext_forward_ref_enum;
14522 if (getLangOpts().MSVCCompat)
14523 DiagID = diag::ext_ms_forward_ref_enum;
14524 else if (getLangOpts().CPlusPlus)
14525 DiagID = diag::err_forward_ref_enum;
14530 if (EnumUnderlying) {
14531 EnumDecl *ED = cast<EnumDecl>(New);
14532 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14533 ED->setIntegerTypeSourceInfo(TI);
14535 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14536 ED->setPromotionType(ED->getIntegerType());
14537 assert(ED->isComplete() && "enum with type should be complete");
14540 // struct/union/class
14542 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14543 // struct X { int A; } D; D should chain to X.
14544 if (getLangOpts().CPlusPlus) {
14545 // FIXME: Look for a way to use RecordDecl for simple structs.
14546 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14547 cast_or_null<CXXRecordDecl>(PrevDecl));
14549 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14550 StdBadAlloc = cast<CXXRecordDecl>(New);
14552 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14553 cast_or_null<RecordDecl>(PrevDecl));
14556 // C++11 [dcl.type]p3:
14557 // A type-specifier-seq shall not define a class or enumeration [...].
14558 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14559 TUK == TUK_Definition) {
14560 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14561 << Context.getTagDeclType(New);
14565 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14566 DC->getDeclKind() == Decl::Enum) {
14567 Diag(New->getLocation(), diag::err_type_defined_in_enum)
14568 << Context.getTagDeclType(New);
14572 // Maybe add qualifier info.
14573 if (SS.isNotEmpty()) {
14575 // If this is either a declaration or a definition, check the
14576 // nested-name-specifier against the current context.
14577 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14578 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14579 isMemberSpecialization))
14582 New->setQualifierInfo(SS.getWithLocInContext(Context));
14583 if (TemplateParameterLists.size() > 0) {
14584 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14591 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14592 // Add alignment attributes if necessary; these attributes are checked when
14593 // the ASTContext lays out the structure.
14595 // It is important for implementing the correct semantics that this
14596 // happen here (in ActOnTag). The #pragma pack stack is
14597 // maintained as a result of parser callbacks which can occur at
14598 // many points during the parsing of a struct declaration (because
14599 // the #pragma tokens are effectively skipped over during the
14600 // parsing of the struct).
14601 if (TUK == TUK_Definition) {
14602 AddAlignmentAttributesForRecord(RD);
14603 AddMsStructLayoutForRecord(RD);
14607 if (ModulePrivateLoc.isValid()) {
14608 if (isMemberSpecialization)
14609 Diag(New->getLocation(), diag::err_module_private_specialization)
14611 << FixItHint::CreateRemoval(ModulePrivateLoc);
14612 // __module_private__ does not apply to local classes. However, we only
14613 // diagnose this as an error when the declaration specifiers are
14614 // freestanding. Here, we just ignore the __module_private__.
14615 else if (!SearchDC->isFunctionOrMethod())
14616 New->setModulePrivate();
14619 // If this is a specialization of a member class (of a class template),
14620 // check the specialization.
14621 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14624 // If we're declaring or defining a tag in function prototype scope in C,
14625 // note that this type can only be used within the function and add it to
14626 // the list of decls to inject into the function definition scope.
14627 if ((Name || Kind == TTK_Enum) &&
14628 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14629 if (getLangOpts().CPlusPlus) {
14630 // C++ [dcl.fct]p6:
14631 // Types shall not be defined in return or parameter types.
14632 if (TUK == TUK_Definition && !IsTypeSpecifier) {
14633 Diag(Loc, diag::err_type_defined_in_param_type)
14637 } else if (!PrevDecl) {
14638 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14643 New->setInvalidDecl();
14645 // Set the lexical context. If the tag has a C++ scope specifier, the
14646 // lexical context will be different from the semantic context.
14647 New->setLexicalDeclContext(CurContext);
14649 // Mark this as a friend decl if applicable.
14650 // In Microsoft mode, a friend declaration also acts as a forward
14651 // declaration so we always pass true to setObjectOfFriendDecl to make
14652 // the tag name visible.
14653 if (TUK == TUK_Friend)
14654 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14656 // Set the access specifier.
14657 if (!Invalid && SearchDC->isRecord())
14658 SetMemberAccessSpecifier(New, PrevDecl, AS);
14661 CheckRedeclarationModuleOwnership(New, PrevDecl);
14663 if (TUK == TUK_Definition)
14664 New->startDefinition();
14666 ProcessDeclAttributeList(S, New, Attrs);
14667 AddPragmaAttributes(S, New);
14669 // If this has an identifier, add it to the scope stack.
14670 if (TUK == TUK_Friend) {
14671 // We might be replacing an existing declaration in the lookup tables;
14672 // if so, borrow its access specifier.
14674 New->setAccess(PrevDecl->getAccess());
14676 DeclContext *DC = New->getDeclContext()->getRedeclContext();
14677 DC->makeDeclVisibleInContext(New);
14678 if (Name) // can be null along some error paths
14679 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14680 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14682 S = getNonFieldDeclScope(S);
14683 PushOnScopeChains(New, S, true);
14685 CurContext->addDecl(New);
14688 // If this is the C FILE type, notify the AST context.
14689 if (IdentifierInfo *II = New->getIdentifier())
14690 if (!New->isInvalidDecl() &&
14691 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14693 Context.setFILEDecl(New);
14696 mergeDeclAttributes(New, PrevDecl);
14698 // If there's a #pragma GCC visibility in scope, set the visibility of this
14700 AddPushedVisibilityAttribute(New);
14702 if (isMemberSpecialization && !New->isInvalidDecl())
14703 CompleteMemberSpecialization(New, Previous);
14706 // In C++, don't return an invalid declaration. We can't recover well from
14707 // the cases where we make the type anonymous.
14708 if (Invalid && getLangOpts().CPlusPlus) {
14709 if (New->isBeingDefined())
14710 if (auto RD = dyn_cast<RecordDecl>(New))
14711 RD->completeDefinition();
14718 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14719 AdjustDeclIfTemplate(TagD);
14720 TagDecl *Tag = cast<TagDecl>(TagD);
14722 // Enter the tag context.
14723 PushDeclContext(S, Tag);
14725 ActOnDocumentableDecl(TagD);
14727 // If there's a #pragma GCC visibility in scope, set the visibility of this
14729 AddPushedVisibilityAttribute(Tag);
14732 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14733 SkipBodyInfo &SkipBody) {
14734 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14737 // Make the previous decl visible.
14738 makeMergedDefinitionVisible(SkipBody.Previous);
14742 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14743 assert(isa<ObjCContainerDecl>(IDecl) &&
14744 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14745 DeclContext *OCD = cast<DeclContext>(IDecl);
14746 assert(getContainingDC(OCD) == CurContext &&
14747 "The next DeclContext should be lexically contained in the current one.");
14752 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14753 SourceLocation FinalLoc,
14754 bool IsFinalSpelledSealed,
14755 SourceLocation LBraceLoc) {
14756 AdjustDeclIfTemplate(TagD);
14757 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14759 FieldCollector->StartClass();
14761 if (!Record->getIdentifier())
14764 if (FinalLoc.isValid())
14765 Record->addAttr(new (Context)
14766 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14769 // [...] The class-name is also inserted into the scope of the
14770 // class itself; this is known as the injected-class-name. For
14771 // purposes of access checking, the injected-class-name is treated
14772 // as if it were a public member name.
14773 CXXRecordDecl *InjectedClassName
14774 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14775 Record->getLocStart(), Record->getLocation(),
14776 Record->getIdentifier(),
14777 /*PrevDecl=*/nullptr,
14778 /*DelayTypeCreation=*/true);
14779 Context.getTypeDeclType(InjectedClassName, Record);
14780 InjectedClassName->setImplicit();
14781 InjectedClassName->setAccess(AS_public);
14782 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14783 InjectedClassName->setDescribedClassTemplate(Template);
14784 PushOnScopeChains(InjectedClassName, S);
14785 assert(InjectedClassName->isInjectedClassName() &&
14786 "Broken injected-class-name");
14789 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14790 SourceRange BraceRange) {
14791 AdjustDeclIfTemplate(TagD);
14792 TagDecl *Tag = cast<TagDecl>(TagD);
14793 Tag->setBraceRange(BraceRange);
14795 // Make sure we "complete" the definition even it is invalid.
14796 if (Tag->isBeingDefined()) {
14797 assert(Tag->isInvalidDecl() && "We should already have completed it");
14798 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14799 RD->completeDefinition();
14802 if (isa<CXXRecordDecl>(Tag)) {
14803 FieldCollector->FinishClass();
14806 // Exit this scope of this tag's definition.
14809 if (getCurLexicalContext()->isObjCContainer() &&
14810 Tag->getDeclContext()->isFileContext())
14811 Tag->setTopLevelDeclInObjCContainer();
14813 // Notify the consumer that we've defined a tag.
14814 if (!Tag->isInvalidDecl())
14815 Consumer.HandleTagDeclDefinition(Tag);
14818 void Sema::ActOnObjCContainerFinishDefinition() {
14819 // Exit this scope of this interface definition.
14823 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14824 assert(DC == CurContext && "Mismatch of container contexts");
14825 OriginalLexicalContext = DC;
14826 ActOnObjCContainerFinishDefinition();
14829 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14830 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14831 OriginalLexicalContext = nullptr;
14834 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14835 AdjustDeclIfTemplate(TagD);
14836 TagDecl *Tag = cast<TagDecl>(TagD);
14837 Tag->setInvalidDecl();
14839 // Make sure we "complete" the definition even it is invalid.
14840 if (Tag->isBeingDefined()) {
14841 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14842 RD->completeDefinition();
14845 // We're undoing ActOnTagStartDefinition here, not
14846 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14847 // the FieldCollector.
14852 // Note that FieldName may be null for anonymous bitfields.
14853 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14854 IdentifierInfo *FieldName,
14855 QualType FieldTy, bool IsMsStruct,
14856 Expr *BitWidth, bool *ZeroWidth) {
14857 // Default to true; that shouldn't confuse checks for emptiness
14861 // C99 6.7.2.1p4 - verify the field type.
14862 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14863 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14864 // Handle incomplete types with specific error.
14865 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14866 return ExprError();
14868 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14869 << FieldName << FieldTy << BitWidth->getSourceRange();
14870 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14871 << FieldTy << BitWidth->getSourceRange();
14872 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14873 UPPC_BitFieldWidth))
14874 return ExprError();
14876 // If the bit-width is type- or value-dependent, don't try to check
14878 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14881 llvm::APSInt Value;
14882 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14883 if (ICE.isInvalid())
14885 BitWidth = ICE.get();
14887 if (Value != 0 && ZeroWidth)
14888 *ZeroWidth = false;
14890 // Zero-width bitfield is ok for anonymous field.
14891 if (Value == 0 && FieldName)
14892 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14894 if (Value.isSigned() && Value.isNegative()) {
14896 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14897 << FieldName << Value.toString(10);
14898 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14899 << Value.toString(10);
14902 if (!FieldTy->isDependentType()) {
14903 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14904 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14905 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14907 // Over-wide bitfields are an error in C or when using the MSVC bitfield
14909 bool CStdConstraintViolation =
14910 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14911 bool MSBitfieldViolation =
14912 Value.ugt(TypeStorageSize) &&
14913 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14914 if (CStdConstraintViolation || MSBitfieldViolation) {
14915 unsigned DiagWidth =
14916 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14918 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14919 << FieldName << (unsigned)Value.getZExtValue()
14920 << !CStdConstraintViolation << DiagWidth;
14922 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14923 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14927 // Warn on types where the user might conceivably expect to get all
14928 // specified bits as value bits: that's all integral types other than
14930 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14932 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14933 << FieldName << (unsigned)Value.getZExtValue()
14934 << (unsigned)TypeWidth;
14936 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14937 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14944 /// ActOnField - Each field of a C struct/union is passed into this in order
14945 /// to create a FieldDecl object for it.
14946 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14947 Declarator &D, Expr *BitfieldWidth) {
14948 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14949 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14950 /*InitStyle=*/ICIS_NoInit, AS_public);
14954 /// HandleField - Analyze a field of a C struct or a C++ data member.
14956 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14957 SourceLocation DeclStart,
14958 Declarator &D, Expr *BitWidth,
14959 InClassInitStyle InitStyle,
14960 AccessSpecifier AS) {
14961 if (D.isDecompositionDeclarator()) {
14962 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14963 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14964 << Decomp.getSourceRange();
14968 IdentifierInfo *II = D.getIdentifier();
14969 SourceLocation Loc = DeclStart;
14970 if (II) Loc = D.getIdentifierLoc();
14972 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14973 QualType T = TInfo->getType();
14974 if (getLangOpts().CPlusPlus) {
14975 CheckExtraCXXDefaultArguments(D);
14977 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14978 UPPC_DataMemberType)) {
14979 D.setInvalidType();
14981 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14985 // TR 18037 does not allow fields to be declared with address spaces.
14986 if (T.getQualifiers().hasAddressSpace() ||
14987 T->isDependentAddressSpaceType() ||
14988 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
14989 Diag(Loc, diag::err_field_with_address_space);
14990 D.setInvalidType();
14993 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14994 // used as structure or union field: image, sampler, event or block types.
14995 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14996 T->isSamplerT() || T->isBlockPointerType())) {
14997 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14998 D.setInvalidType();
15001 DiagnoseFunctionSpecifiers(D.getDeclSpec());
15003 if (D.getDeclSpec().isInlineSpecified())
15004 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15005 << getLangOpts().CPlusPlus17;
15006 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15007 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15008 diag::err_invalid_thread)
15009 << DeclSpec::getSpecifierName(TSCS);
15011 // Check to see if this name was declared as a member previously
15012 NamedDecl *PrevDecl = nullptr;
15013 LookupResult Previous(*this, II, Loc, LookupMemberName,
15014 ForVisibleRedeclaration);
15015 LookupName(Previous, S);
15016 switch (Previous.getResultKind()) {
15017 case LookupResult::Found:
15018 case LookupResult::FoundUnresolvedValue:
15019 PrevDecl = Previous.getAsSingle<NamedDecl>();
15022 case LookupResult::FoundOverloaded:
15023 PrevDecl = Previous.getRepresentativeDecl();
15026 case LookupResult::NotFound:
15027 case LookupResult::NotFoundInCurrentInstantiation:
15028 case LookupResult::Ambiguous:
15031 Previous.suppressDiagnostics();
15033 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15034 // Maybe we will complain about the shadowed template parameter.
15035 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15036 // Just pretend that we didn't see the previous declaration.
15037 PrevDecl = nullptr;
15040 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15041 PrevDecl = nullptr;
15044 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15045 SourceLocation TSSL = D.getLocStart();
15047 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15048 TSSL, AS, PrevDecl, &D);
15050 if (NewFD->isInvalidDecl())
15051 Record->setInvalidDecl();
15053 if (D.getDeclSpec().isModulePrivateSpecified())
15054 NewFD->setModulePrivate();
15056 if (NewFD->isInvalidDecl() && PrevDecl) {
15057 // Don't introduce NewFD into scope; there's already something
15058 // with the same name in the same scope.
15060 PushOnScopeChains(NewFD, S);
15062 Record->addDecl(NewFD);
15067 /// Build a new FieldDecl and check its well-formedness.
15069 /// This routine builds a new FieldDecl given the fields name, type,
15070 /// record, etc. \p PrevDecl should refer to any previous declaration
15071 /// with the same name and in the same scope as the field to be
15074 /// \returns a new FieldDecl.
15076 /// \todo The Declarator argument is a hack. It will be removed once
15077 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15078 TypeSourceInfo *TInfo,
15079 RecordDecl *Record, SourceLocation Loc,
15080 bool Mutable, Expr *BitWidth,
15081 InClassInitStyle InitStyle,
15082 SourceLocation TSSL,
15083 AccessSpecifier AS, NamedDecl *PrevDecl,
15085 IdentifierInfo *II = Name.getAsIdentifierInfo();
15086 bool InvalidDecl = false;
15087 if (D) InvalidDecl = D->isInvalidType();
15089 // If we receive a broken type, recover by assuming 'int' and
15090 // marking this declaration as invalid.
15092 InvalidDecl = true;
15096 QualType EltTy = Context.getBaseElementType(T);
15097 if (!EltTy->isDependentType()) {
15098 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15099 // Fields of incomplete type force their record to be invalid.
15100 Record->setInvalidDecl();
15101 InvalidDecl = true;
15104 EltTy->isIncompleteType(&Def);
15105 if (Def && Def->isInvalidDecl()) {
15106 Record->setInvalidDecl();
15107 InvalidDecl = true;
15112 // OpenCL v1.2 s6.9.c: bitfields are not supported.
15113 if (BitWidth && getLangOpts().OpenCL) {
15114 Diag(Loc, diag::err_opencl_bitfields);
15115 InvalidDecl = true;
15118 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15119 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15120 T.hasQualifiers()) {
15121 InvalidDecl = true;
15122 Diag(Loc, diag::err_anon_bitfield_qualifiers);
15125 // C99 6.7.2.1p8: A member of a structure or union may have any type other
15126 // than a variably modified type.
15127 if (!InvalidDecl && T->isVariablyModifiedType()) {
15128 bool SizeIsNegative;
15129 llvm::APSInt Oversized;
15131 TypeSourceInfo *FixedTInfo =
15132 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15136 Diag(Loc, diag::warn_illegal_constant_array_size);
15137 TInfo = FixedTInfo;
15138 T = FixedTInfo->getType();
15140 if (SizeIsNegative)
15141 Diag(Loc, diag::err_typecheck_negative_array_size);
15142 else if (Oversized.getBoolValue())
15143 Diag(Loc, diag::err_array_too_large)
15144 << Oversized.toString(10);
15146 Diag(Loc, diag::err_typecheck_field_variable_size);
15147 InvalidDecl = true;
15151 // Fields can not have abstract class types
15152 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15153 diag::err_abstract_type_in_decl,
15154 AbstractFieldType))
15155 InvalidDecl = true;
15157 bool ZeroWidth = false;
15159 BitWidth = nullptr;
15160 // If this is declared as a bit-field, check the bit-field.
15162 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15165 InvalidDecl = true;
15166 BitWidth = nullptr;
15171 // Check that 'mutable' is consistent with the type of the declaration.
15172 if (!InvalidDecl && Mutable) {
15173 unsigned DiagID = 0;
15174 if (T->isReferenceType())
15175 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15176 : diag::err_mutable_reference;
15177 else if (T.isConstQualified())
15178 DiagID = diag::err_mutable_const;
15181 SourceLocation ErrLoc = Loc;
15182 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15183 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15184 Diag(ErrLoc, DiagID);
15185 if (DiagID != diag::ext_mutable_reference) {
15187 InvalidDecl = true;
15192 // C++11 [class.union]p8 (DR1460):
15193 // At most one variant member of a union may have a
15194 // brace-or-equal-initializer.
15195 if (InitStyle != ICIS_NoInit)
15196 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15198 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15199 BitWidth, Mutable, InitStyle);
15201 NewFD->setInvalidDecl();
15203 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15204 Diag(Loc, diag::err_duplicate_member) << II;
15205 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15206 NewFD->setInvalidDecl();
15209 if (!InvalidDecl && getLangOpts().CPlusPlus) {
15210 if (Record->isUnion()) {
15211 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15212 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15213 if (RDecl->getDefinition()) {
15214 // C++ [class.union]p1: An object of a class with a non-trivial
15215 // constructor, a non-trivial copy constructor, a non-trivial
15216 // destructor, or a non-trivial copy assignment operator
15217 // cannot be a member of a union, nor can an array of such
15219 if (CheckNontrivialField(NewFD))
15220 NewFD->setInvalidDecl();
15224 // C++ [class.union]p1: If a union contains a member of reference type,
15225 // the program is ill-formed, except when compiling with MSVC extensions
15227 if (EltTy->isReferenceType()) {
15228 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15229 diag::ext_union_member_of_reference_type :
15230 diag::err_union_member_of_reference_type)
15231 << NewFD->getDeclName() << EltTy;
15232 if (!getLangOpts().MicrosoftExt)
15233 NewFD->setInvalidDecl();
15238 // FIXME: We need to pass in the attributes given an AST
15239 // representation, not a parser representation.
15241 // FIXME: The current scope is almost... but not entirely... correct here.
15242 ProcessDeclAttributes(getCurScope(), NewFD, *D);
15244 if (NewFD->hasAttrs())
15245 CheckAlignasUnderalignment(NewFD);
15248 // In auto-retain/release, infer strong retension for fields of
15249 // retainable type.
15250 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15251 NewFD->setInvalidDecl();
15253 if (T.isObjCGCWeak())
15254 Diag(Loc, diag::warn_attribute_weak_on_field);
15256 NewFD->setAccess(AS);
15260 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15262 assert(getLangOpts().CPlusPlus && "valid check only for C++");
15264 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15267 QualType EltTy = Context.getBaseElementType(FD->getType());
15268 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15269 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15270 if (RDecl->getDefinition()) {
15271 // We check for copy constructors before constructors
15272 // because otherwise we'll never get complaints about
15273 // copy constructors.
15275 CXXSpecialMember member = CXXInvalid;
15276 // We're required to check for any non-trivial constructors. Since the
15277 // implicit default constructor is suppressed if there are any
15278 // user-declared constructors, we just need to check that there is a
15279 // trivial default constructor and a trivial copy constructor. (We don't
15280 // worry about move constructors here, since this is a C++98 check.)
15281 if (RDecl->hasNonTrivialCopyConstructor())
15282 member = CXXCopyConstructor;
15283 else if (!RDecl->hasTrivialDefaultConstructor())
15284 member = CXXDefaultConstructor;
15285 else if (RDecl->hasNonTrivialCopyAssignment())
15286 member = CXXCopyAssignment;
15287 else if (RDecl->hasNonTrivialDestructor())
15288 member = CXXDestructor;
15290 if (member != CXXInvalid) {
15291 if (!getLangOpts().CPlusPlus11 &&
15292 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15293 // Objective-C++ ARC: it is an error to have a non-trivial field of
15294 // a union. However, system headers in Objective-C programs
15295 // occasionally have Objective-C lifetime objects within unions,
15296 // and rather than cause the program to fail, we make those
15297 // members unavailable.
15298 SourceLocation Loc = FD->getLocation();
15299 if (getSourceManager().isInSystemHeader(Loc)) {
15300 if (!FD->hasAttr<UnavailableAttr>())
15301 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15302 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15307 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15308 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15309 diag::err_illegal_union_or_anon_struct_member)
15310 << FD->getParent()->isUnion() << FD->getDeclName() << member;
15311 DiagnoseNontrivial(RDecl, member);
15312 return !getLangOpts().CPlusPlus11;
15320 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15321 /// AST enum value.
15322 static ObjCIvarDecl::AccessControl
15323 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15324 switch (ivarVisibility) {
15325 default: llvm_unreachable("Unknown visitibility kind");
15326 case tok::objc_private: return ObjCIvarDecl::Private;
15327 case tok::objc_public: return ObjCIvarDecl::Public;
15328 case tok::objc_protected: return ObjCIvarDecl::Protected;
15329 case tok::objc_package: return ObjCIvarDecl::Package;
15333 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15334 /// in order to create an IvarDecl object for it.
15335 Decl *Sema::ActOnIvar(Scope *S,
15336 SourceLocation DeclStart,
15337 Declarator &D, Expr *BitfieldWidth,
15338 tok::ObjCKeywordKind Visibility) {
15340 IdentifierInfo *II = D.getIdentifier();
15341 Expr *BitWidth = (Expr*)BitfieldWidth;
15342 SourceLocation Loc = DeclStart;
15343 if (II) Loc = D.getIdentifierLoc();
15345 // FIXME: Unnamed fields can be handled in various different ways, for
15346 // example, unnamed unions inject all members into the struct namespace!
15348 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15349 QualType T = TInfo->getType();
15352 // 6.7.2.1p3, 6.7.2.1p4
15353 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15355 D.setInvalidType();
15362 if (T->isReferenceType()) {
15363 Diag(Loc, diag::err_ivar_reference_type);
15364 D.setInvalidType();
15366 // C99 6.7.2.1p8: A member of a structure or union may have any type other
15367 // than a variably modified type.
15368 else if (T->isVariablyModifiedType()) {
15369 Diag(Loc, diag::err_typecheck_ivar_variable_size);
15370 D.setInvalidType();
15373 // Get the visibility (access control) for this ivar.
15374 ObjCIvarDecl::AccessControl ac =
15375 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15376 : ObjCIvarDecl::None;
15377 // Must set ivar's DeclContext to its enclosing interface.
15378 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15379 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15381 ObjCContainerDecl *EnclosingContext;
15382 if (ObjCImplementationDecl *IMPDecl =
15383 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15384 if (LangOpts.ObjCRuntime.isFragile()) {
15385 // Case of ivar declared in an implementation. Context is that of its class.
15386 EnclosingContext = IMPDecl->getClassInterface();
15387 assert(EnclosingContext && "Implementation has no class interface!");
15390 EnclosingContext = EnclosingDecl;
15392 if (ObjCCategoryDecl *CDecl =
15393 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15394 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15395 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15399 EnclosingContext = EnclosingDecl;
15402 // Construct the decl.
15403 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15404 DeclStart, Loc, II, T,
15405 TInfo, ac, (Expr *)BitfieldWidth);
15408 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15409 ForVisibleRedeclaration);
15410 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15411 && !isa<TagDecl>(PrevDecl)) {
15412 Diag(Loc, diag::err_duplicate_member) << II;
15413 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15414 NewID->setInvalidDecl();
15418 // Process attributes attached to the ivar.
15419 ProcessDeclAttributes(S, NewID, D);
15421 if (D.isInvalidType())
15422 NewID->setInvalidDecl();
15424 // In ARC, infer 'retaining' for ivars of retainable type.
15425 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15426 NewID->setInvalidDecl();
15428 if (D.getDeclSpec().isModulePrivateSpecified())
15429 NewID->setModulePrivate();
15432 // FIXME: When interfaces are DeclContexts, we'll need to add
15433 // these to the interface.
15435 IdResolver.AddDecl(NewID);
15438 if (LangOpts.ObjCRuntime.isNonFragile() &&
15439 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15440 Diag(Loc, diag::warn_ivars_in_interface);
15445 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15446 /// class and class extensions. For every class \@interface and class
15447 /// extension \@interface, if the last ivar is a bitfield of any type,
15448 /// then add an implicit `char :0` ivar to the end of that interface.
15449 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15450 SmallVectorImpl<Decl *> &AllIvarDecls) {
15451 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15454 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15455 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15457 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15459 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15461 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15462 if (!CD->IsClassExtension())
15465 // No need to add this to end of @implementation.
15469 // All conditions are met. Add a new bitfield to the tail end of ivars.
15470 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15471 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15473 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15474 DeclLoc, DeclLoc, nullptr,
15476 Context.getTrivialTypeSourceInfo(Context.CharTy,
15478 ObjCIvarDecl::Private, BW,
15480 AllIvarDecls.push_back(Ivar);
15483 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15484 ArrayRef<Decl *> Fields, SourceLocation LBrac,
15485 SourceLocation RBrac,
15486 const ParsedAttributesView &Attrs) {
15487 assert(EnclosingDecl && "missing record or interface decl");
15489 // If this is an Objective-C @implementation or category and we have
15490 // new fields here we should reset the layout of the interface since
15491 // it will now change.
15492 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15493 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15494 switch (DC->getKind()) {
15496 case Decl::ObjCCategory:
15497 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15499 case Decl::ObjCImplementation:
15501 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15506 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15508 // Start counting up the number of named members; make sure to include
15509 // members of anonymous structs and unions in the total.
15510 unsigned NumNamedMembers = 0;
15512 for (const auto *I : Record->decls()) {
15513 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15514 if (IFD->getDeclName())
15519 // Verify that all the fields are okay.
15520 SmallVector<FieldDecl*, 32> RecFields;
15522 bool ObjCFieldLifetimeErrReported = false;
15523 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15525 FieldDecl *FD = cast<FieldDecl>(*i);
15527 // Get the type for the field.
15528 const Type *FDTy = FD->getType().getTypePtr();
15530 if (!FD->isAnonymousStructOrUnion()) {
15531 // Remember all fields written by the user.
15532 RecFields.push_back(FD);
15535 // If the field is already invalid for some reason, don't emit more
15536 // diagnostics about it.
15537 if (FD->isInvalidDecl()) {
15538 EnclosingDecl->setInvalidDecl();
15543 // A structure or union shall not contain a member with
15544 // incomplete or function type (hence, a structure shall not
15545 // contain an instance of itself, but may contain a pointer to
15546 // an instance of itself), except that the last member of a
15547 // structure with more than one named member may have incomplete
15548 // array type; such a structure (and any union containing,
15549 // possibly recursively, a member that is such a structure)
15550 // shall not be a member of a structure or an element of an
15552 bool IsLastField = (i + 1 == Fields.end());
15553 if (FDTy->isFunctionType()) {
15554 // Field declared as a function.
15555 Diag(FD->getLocation(), diag::err_field_declared_as_function)
15556 << FD->getDeclName();
15557 FD->setInvalidDecl();
15558 EnclosingDecl->setInvalidDecl();
15560 } else if (FDTy->isIncompleteArrayType() &&
15561 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15563 // Flexible array member.
15564 // Microsoft and g++ is more permissive regarding flexible array.
15565 // It will accept flexible array in union and also
15566 // as the sole element of a struct/class.
15567 unsigned DiagID = 0;
15568 if (!Record->isUnion() && !IsLastField) {
15569 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15570 << FD->getDeclName() << FD->getType() << Record->getTagKind();
15571 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15572 FD->setInvalidDecl();
15573 EnclosingDecl->setInvalidDecl();
15575 } else if (Record->isUnion())
15576 DiagID = getLangOpts().MicrosoftExt
15577 ? diag::ext_flexible_array_union_ms
15578 : getLangOpts().CPlusPlus
15579 ? diag::ext_flexible_array_union_gnu
15580 : diag::err_flexible_array_union;
15581 else if (NumNamedMembers < 1)
15582 DiagID = getLangOpts().MicrosoftExt
15583 ? diag::ext_flexible_array_empty_aggregate_ms
15584 : getLangOpts().CPlusPlus
15585 ? diag::ext_flexible_array_empty_aggregate_gnu
15586 : diag::err_flexible_array_empty_aggregate;
15589 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15590 << Record->getTagKind();
15591 // While the layout of types that contain virtual bases is not specified
15592 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15593 // virtual bases after the derived members. This would make a flexible
15594 // array member declared at the end of an object not adjacent to the end
15596 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
15597 if (RD->getNumVBases() != 0)
15598 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15599 << FD->getDeclName() << Record->getTagKind();
15600 if (!getLangOpts().C99)
15601 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15602 << FD->getDeclName() << Record->getTagKind();
15604 // If the element type has a non-trivial destructor, we would not
15605 // implicitly destroy the elements, so disallow it for now.
15607 // FIXME: GCC allows this. We should probably either implicitly delete
15608 // the destructor of the containing class, or just allow this.
15609 QualType BaseElem = Context.getBaseElementType(FD->getType());
15610 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15611 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15612 << FD->getDeclName() << FD->getType();
15613 FD->setInvalidDecl();
15614 EnclosingDecl->setInvalidDecl();
15617 // Okay, we have a legal flexible array member at the end of the struct.
15618 Record->setHasFlexibleArrayMember(true);
15620 // In ObjCContainerDecl ivars with incomplete array type are accepted,
15621 // unless they are followed by another ivar. That check is done
15622 // elsewhere, after synthesized ivars are known.
15624 } else if (!FDTy->isDependentType() &&
15625 RequireCompleteType(FD->getLocation(), FD->getType(),
15626 diag::err_field_incomplete)) {
15628 FD->setInvalidDecl();
15629 EnclosingDecl->setInvalidDecl();
15631 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15632 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15633 // A type which contains a flexible array member is considered to be a
15634 // flexible array member.
15635 Record->setHasFlexibleArrayMember(true);
15636 if (!Record->isUnion()) {
15637 // If this is a struct/class and this is not the last element, reject
15638 // it. Note that GCC supports variable sized arrays in the middle of
15641 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15642 << FD->getDeclName() << FD->getType();
15644 // We support flexible arrays at the end of structs in
15645 // other structs as an extension.
15646 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15647 << FD->getDeclName();
15651 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15652 RequireNonAbstractType(FD->getLocation(), FD->getType(),
15653 diag::err_abstract_type_in_decl,
15654 AbstractIvarType)) {
15655 // Ivars can not have abstract class types
15656 FD->setInvalidDecl();
15658 if (Record && FDTTy->getDecl()->hasObjectMember())
15659 Record->setHasObjectMember(true);
15660 if (Record && FDTTy->getDecl()->hasVolatileMember())
15661 Record->setHasVolatileMember(true);
15662 } else if (FDTy->isObjCObjectType()) {
15663 /// A field cannot be an Objective-c object
15664 Diag(FD->getLocation(), diag::err_statically_allocated_object)
15665 << FixItHint::CreateInsertion(FD->getLocation(), "*");
15666 QualType T = Context.getObjCObjectPointerType(FD->getType());
15668 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15669 Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
15670 // It's an error in ARC or Weak if a field has lifetime.
15671 // We don't want to report this in a system header, though,
15672 // so we just make the field unavailable.
15673 // FIXME: that's really not sufficient; we need to make the type
15674 // itself invalid to, say, initialize or copy.
15675 QualType T = FD->getType();
15676 if (T.hasNonTrivialObjCLifetime()) {
15677 SourceLocation loc = FD->getLocation();
15678 if (getSourceManager().isInSystemHeader(loc)) {
15679 if (!FD->hasAttr<UnavailableAttr>()) {
15680 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15681 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15684 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15685 << T->isBlockPointerType() << Record->getTagKind();
15687 ObjCFieldLifetimeErrReported = true;
15689 } else if (getLangOpts().ObjC1 &&
15690 getLangOpts().getGC() != LangOptions::NonGC &&
15691 Record && !Record->hasObjectMember()) {
15692 if (FD->getType()->isObjCObjectPointerType() ||
15693 FD->getType().isObjCGCStrong())
15694 Record->setHasObjectMember(true);
15695 else if (Context.getAsArrayType(FD->getType())) {
15696 QualType BaseType = Context.getBaseElementType(FD->getType());
15697 if (BaseType->isRecordType() &&
15698 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15699 Record->setHasObjectMember(true);
15700 else if (BaseType->isObjCObjectPointerType() ||
15701 BaseType.isObjCGCStrong())
15702 Record->setHasObjectMember(true);
15706 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15707 QualType FT = FD->getType();
15708 if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15709 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15710 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15711 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15712 Record->setNonTrivialToPrimitiveCopy(true);
15713 if (FT.isDestructedType()) {
15714 Record->setNonTrivialToPrimitiveDestroy(true);
15715 Record->setParamDestroyedInCallee(true);
15718 if (const auto *RT = FT->getAs<RecordType>()) {
15719 if (RT->getDecl()->getArgPassingRestrictions() ==
15720 RecordDecl::APK_CanNeverPassInRegs)
15721 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15722 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
15723 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15726 if (Record && FD->getType().isVolatileQualified())
15727 Record->setHasVolatileMember(true);
15728 // Keep track of the number of named members.
15729 if (FD->getIdentifier())
15733 // Okay, we successfully defined 'Record'.
15735 bool Completed = false;
15736 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15737 if (!CXXRecord->isInvalidDecl()) {
15738 // Set access bits correctly on the directly-declared conversions.
15739 for (CXXRecordDecl::conversion_iterator
15740 I = CXXRecord->conversion_begin(),
15741 E = CXXRecord->conversion_end(); I != E; ++I)
15742 I.setAccess((*I)->getAccess());
15745 if (!CXXRecord->isDependentType()) {
15746 if (CXXRecord->hasUserDeclaredDestructor()) {
15747 // Adjust user-defined destructor exception spec.
15748 if (getLangOpts().CPlusPlus11)
15749 AdjustDestructorExceptionSpec(CXXRecord,
15750 CXXRecord->getDestructor());
15753 // Add any implicitly-declared members to this class.
15754 AddImplicitlyDeclaredMembersToClass(CXXRecord);
15756 if (!CXXRecord->isInvalidDecl()) {
15757 // If we have virtual base classes, we may end up finding multiple
15758 // final overriders for a given virtual function. Check for this
15760 if (CXXRecord->getNumVBases()) {
15761 CXXFinalOverriderMap FinalOverriders;
15762 CXXRecord->getFinalOverriders(FinalOverriders);
15764 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15765 MEnd = FinalOverriders.end();
15767 for (OverridingMethods::iterator SO = M->second.begin(),
15768 SOEnd = M->second.end();
15769 SO != SOEnd; ++SO) {
15770 assert(SO->second.size() > 0 &&
15771 "Virtual function without overriding functions?");
15772 if (SO->second.size() == 1)
15775 // C++ [class.virtual]p2:
15776 // In a derived class, if a virtual member function of a base
15777 // class subobject has more than one final overrider the
15778 // program is ill-formed.
15779 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15780 << (const NamedDecl *)M->first << Record;
15781 Diag(M->first->getLocation(),
15782 diag::note_overridden_virtual_function);
15783 for (OverridingMethods::overriding_iterator
15784 OM = SO->second.begin(),
15785 OMEnd = SO->second.end();
15787 Diag(OM->Method->getLocation(), diag::note_final_overrider)
15788 << (const NamedDecl *)M->first << OM->Method->getParent();
15790 Record->setInvalidDecl();
15793 CXXRecord->completeDefinition(&FinalOverriders);
15801 Record->completeDefinition();
15803 // Handle attributes before checking the layout.
15804 ProcessDeclAttributeList(S, Record, Attrs);
15806 // We may have deferred checking for a deleted destructor. Check now.
15807 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15808 auto *Dtor = CXXRecord->getDestructor();
15809 if (Dtor && Dtor->isImplicit() &&
15810 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15811 CXXRecord->setImplicitDestructorIsDeleted();
15812 SetDeclDeleted(Dtor, CXXRecord->getLocation());
15816 if (Record->hasAttrs()) {
15817 CheckAlignasUnderalignment(Record);
15819 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15820 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15821 IA->getRange(), IA->getBestCase(),
15822 IA->getSemanticSpelling());
15825 // Check if the structure/union declaration is a type that can have zero
15826 // size in C. For C this is a language extension, for C++ it may cause
15827 // compatibility problems.
15828 bool CheckForZeroSize;
15829 if (!getLangOpts().CPlusPlus) {
15830 CheckForZeroSize = true;
15832 // For C++ filter out types that cannot be referenced in C code.
15833 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15835 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15836 !CXXRecord->isDependentType() &&
15837 CXXRecord->isCLike();
15839 if (CheckForZeroSize) {
15840 bool ZeroSize = true;
15841 bool IsEmpty = true;
15842 unsigned NonBitFields = 0;
15843 for (RecordDecl::field_iterator I = Record->field_begin(),
15844 E = Record->field_end();
15845 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15847 if (I->isUnnamedBitfield()) {
15848 if (!I->isZeroLengthBitField(Context))
15852 QualType FieldType = I->getType();
15853 if (FieldType->isIncompleteType() ||
15854 !Context.getTypeSizeInChars(FieldType).isZero())
15859 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15860 // allowed in C++, but warn if its declaration is inside
15861 // extern "C" block.
15863 Diag(RecLoc, getLangOpts().CPlusPlus ?
15864 diag::warn_zero_size_struct_union_in_extern_c :
15865 diag::warn_zero_size_struct_union_compat)
15866 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15869 // Structs without named members are extension in C (C99 6.7.2.1p7),
15870 // but are accepted by GCC.
15871 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15872 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15873 diag::ext_no_named_members_in_struct_union)
15874 << Record->isUnion();
15878 ObjCIvarDecl **ClsFields =
15879 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15880 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15881 ID->setEndOfDefinitionLoc(RBrac);
15882 // Add ivar's to class's DeclContext.
15883 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15884 ClsFields[i]->setLexicalDeclContext(ID);
15885 ID->addDecl(ClsFields[i]);
15887 // Must enforce the rule that ivars in the base classes may not be
15889 if (ID->getSuperClass())
15890 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15891 } else if (ObjCImplementationDecl *IMPDecl =
15892 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15893 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15894 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15895 // Ivar declared in @implementation never belongs to the implementation.
15896 // Only it is in implementation's lexical context.
15897 ClsFields[I]->setLexicalDeclContext(IMPDecl);
15898 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15899 IMPDecl->setIvarLBraceLoc(LBrac);
15900 IMPDecl->setIvarRBraceLoc(RBrac);
15901 } else if (ObjCCategoryDecl *CDecl =
15902 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15903 // case of ivars in class extension; all other cases have been
15904 // reported as errors elsewhere.
15905 // FIXME. Class extension does not have a LocEnd field.
15906 // CDecl->setLocEnd(RBrac);
15907 // Add ivar's to class extension's DeclContext.
15908 // Diagnose redeclaration of private ivars.
15909 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15910 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15912 if (const ObjCIvarDecl *ClsIvar =
15913 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15914 Diag(ClsFields[i]->getLocation(),
15915 diag::err_duplicate_ivar_declaration);
15916 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15919 for (const auto *Ext : IDecl->known_extensions()) {
15920 if (const ObjCIvarDecl *ClsExtIvar
15921 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15922 Diag(ClsFields[i]->getLocation(),
15923 diag::err_duplicate_ivar_declaration);
15924 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15929 ClsFields[i]->setLexicalDeclContext(CDecl);
15930 CDecl->addDecl(ClsFields[i]);
15932 CDecl->setIvarLBraceLoc(LBrac);
15933 CDecl->setIvarRBraceLoc(RBrac);
15938 /// Determine whether the given integral value is representable within
15939 /// the given type T.
15940 static bool isRepresentableIntegerValue(ASTContext &Context,
15941 llvm::APSInt &Value,
15943 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
15944 "Integral type required!");
15945 unsigned BitWidth = Context.getIntWidth(T);
15947 if (Value.isUnsigned() || Value.isNonNegative()) {
15948 if (T->isSignedIntegerOrEnumerationType())
15950 return Value.getActiveBits() <= BitWidth;
15952 return Value.getMinSignedBits() <= BitWidth;
15955 // Given an integral type, return the next larger integral type
15956 // (or a NULL type of no such type exists).
15957 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15958 // FIXME: Int128/UInt128 support, which also needs to be introduced into
15959 // enum checking below.
15960 assert((T->isIntegralType(Context) ||
15961 T->isEnumeralType()) && "Integral type required!");
15962 const unsigned NumTypes = 4;
15963 QualType SignedIntegralTypes[NumTypes] = {
15964 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15966 QualType UnsignedIntegralTypes[NumTypes] = {
15967 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15968 Context.UnsignedLongLongTy
15971 unsigned BitWidth = Context.getTypeSize(T);
15972 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15973 : UnsignedIntegralTypes;
15974 for (unsigned I = 0; I != NumTypes; ++I)
15975 if (Context.getTypeSize(Types[I]) > BitWidth)
15981 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15982 EnumConstantDecl *LastEnumConst,
15983 SourceLocation IdLoc,
15984 IdentifierInfo *Id,
15986 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15987 llvm::APSInt EnumVal(IntWidth);
15990 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15994 Val = DefaultLvalueConversion(Val).get();
15997 if (Enum->isDependentType() || Val->isTypeDependent())
15998 EltTy = Context.DependentTy;
16000 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16001 !getLangOpts().MSVCCompat) {
16002 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16003 // constant-expression in the enumerator-definition shall be a converted
16004 // constant expression of the underlying type.
16005 EltTy = Enum->getIntegerType();
16006 ExprResult Converted =
16007 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16009 if (Converted.isInvalid())
16012 Val = Converted.get();
16013 } else if (!Val->isValueDependent() &&
16014 !(Val = VerifyIntegerConstantExpression(Val,
16015 &EnumVal).get())) {
16016 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16018 if (Enum->isComplete()) {
16019 EltTy = Enum->getIntegerType();
16021 // In Obj-C and Microsoft mode, require the enumeration value to be
16022 // representable in the underlying type of the enumeration. In C++11,
16023 // we perform a non-narrowing conversion as part of converted constant
16024 // expression checking.
16025 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16026 if (getLangOpts().MSVCCompat) {
16027 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16028 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16030 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16032 Val = ImpCastExprToType(Val, EltTy,
16033 EltTy->isBooleanType() ?
16034 CK_IntegralToBoolean : CK_IntegralCast)
16036 } else if (getLangOpts().CPlusPlus) {
16037 // C++11 [dcl.enum]p5:
16038 // If the underlying type is not fixed, the type of each enumerator
16039 // is the type of its initializing value:
16040 // - If an initializer is specified for an enumerator, the
16041 // initializing value has the same type as the expression.
16042 EltTy = Val->getType();
16045 // The expression that defines the value of an enumeration constant
16046 // shall be an integer constant expression that has a value
16047 // representable as an int.
16049 // Complain if the value is not representable in an int.
16050 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16051 Diag(IdLoc, diag::ext_enum_value_not_int)
16052 << EnumVal.toString(10) << Val->getSourceRange()
16053 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16054 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16055 // Force the type of the expression to 'int'.
16056 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16058 EltTy = Val->getType();
16065 if (Enum->isDependentType())
16066 EltTy = Context.DependentTy;
16067 else if (!LastEnumConst) {
16068 // C++0x [dcl.enum]p5:
16069 // If the underlying type is not fixed, the type of each enumerator
16070 // is the type of its initializing value:
16071 // - If no initializer is specified for the first enumerator, the
16072 // initializing value has an unspecified integral type.
16074 // GCC uses 'int' for its unspecified integral type, as does
16076 if (Enum->isFixed()) {
16077 EltTy = Enum->getIntegerType();
16080 EltTy = Context.IntTy;
16083 // Assign the last value + 1.
16084 EnumVal = LastEnumConst->getInitVal();
16086 EltTy = LastEnumConst->getType();
16088 // Check for overflow on increment.
16089 if (EnumVal < LastEnumConst->getInitVal()) {
16090 // C++0x [dcl.enum]p5:
16091 // If the underlying type is not fixed, the type of each enumerator
16092 // is the type of its initializing value:
16094 // - Otherwise the type of the initializing value is the same as
16095 // the type of the initializing value of the preceding enumerator
16096 // unless the incremented value is not representable in that type,
16097 // in which case the type is an unspecified integral type
16098 // sufficient to contain the incremented value. If no such type
16099 // exists, the program is ill-formed.
16100 QualType T = getNextLargerIntegralType(Context, EltTy);
16101 if (T.isNull() || Enum->isFixed()) {
16102 // There is no integral type larger enough to represent this
16103 // value. Complain, then allow the value to wrap around.
16104 EnumVal = LastEnumConst->getInitVal();
16105 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16107 if (Enum->isFixed())
16108 // When the underlying type is fixed, this is ill-formed.
16109 Diag(IdLoc, diag::err_enumerator_wrapped)
16110 << EnumVal.toString(10)
16113 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16114 << EnumVal.toString(10);
16119 // Retrieve the last enumerator's value, extent that type to the
16120 // type that is supposed to be large enough to represent the incremented
16121 // value, then increment.
16122 EnumVal = LastEnumConst->getInitVal();
16123 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16124 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16127 // If we're not in C++, diagnose the overflow of enumerator values,
16128 // which in C99 means that the enumerator value is not representable in
16129 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16130 // permits enumerator values that are representable in some larger
16132 if (!getLangOpts().CPlusPlus && !T.isNull())
16133 Diag(IdLoc, diag::warn_enum_value_overflow);
16134 } else if (!getLangOpts().CPlusPlus &&
16135 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16136 // Enforce C99 6.7.2.2p2 even when we compute the next value.
16137 Diag(IdLoc, diag::ext_enum_value_not_int)
16138 << EnumVal.toString(10) << 1;
16143 if (!EltTy->isDependentType()) {
16144 // Make the enumerator value match the signedness and size of the
16145 // enumerator's type.
16146 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16147 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16150 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16154 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16155 SourceLocation IILoc) {
16156 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16157 !getLangOpts().CPlusPlus)
16158 return SkipBodyInfo();
16160 // We have an anonymous enum definition. Look up the first enumerator to
16161 // determine if we should merge the definition with an existing one and
16163 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16164 forRedeclarationInCurContext());
16165 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16167 return SkipBodyInfo();
16169 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16171 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16173 Skip.Previous = Hidden;
16177 return SkipBodyInfo();
16180 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16181 SourceLocation IdLoc, IdentifierInfo *Id,
16182 const ParsedAttributesView &Attrs,
16183 SourceLocation EqualLoc, Expr *Val) {
16184 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16185 EnumConstantDecl *LastEnumConst =
16186 cast_or_null<EnumConstantDecl>(lastEnumConst);
16188 // The scope passed in may not be a decl scope. Zip up the scope tree until
16189 // we find one that is.
16190 S = getNonFieldDeclScope(S);
16192 // Verify that there isn't already something declared with this name in this
16194 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
16195 ForVisibleRedeclaration);
16196 if (PrevDecl && PrevDecl->isTemplateParameter()) {
16197 // Maybe we will complain about the shadowed template parameter.
16198 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16199 // Just pretend that we didn't see the previous declaration.
16200 PrevDecl = nullptr;
16203 // C++ [class.mem]p15:
16204 // If T is the name of a class, then each of the following shall have a name
16205 // different from T:
16206 // - every enumerator of every member of class T that is an unscoped
16208 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16209 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16210 DeclarationNameInfo(Id, IdLoc));
16212 EnumConstantDecl *New =
16213 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16218 // When in C++, we may get a TagDecl with the same name; in this case the
16219 // enum constant will 'hide' the tag.
16220 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16221 "Received TagDecl when not in C++!");
16222 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16223 if (isa<EnumConstantDecl>(PrevDecl))
16224 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16226 Diag(IdLoc, diag::err_redefinition) << Id;
16227 notePreviousDefinition(PrevDecl, IdLoc);
16232 // Process attributes.
16233 ProcessDeclAttributeList(S, New, Attrs);
16234 AddPragmaAttributes(S, New);
16236 // Register this decl in the current scope stack.
16237 New->setAccess(TheEnumDecl->getAccess());
16238 PushOnScopeChains(New, S);
16240 ActOnDocumentableDecl(New);
16245 // Returns true when the enum initial expression does not trigger the
16246 // duplicate enum warning. A few common cases are exempted as follows:
16247 // Element2 = Element1
16248 // Element2 = Element1 + 1
16249 // Element2 = Element1 - 1
16250 // Where Element2 and Element1 are from the same enum.
16251 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16252 Expr *InitExpr = ECD->getInitExpr();
16255 InitExpr = InitExpr->IgnoreImpCasts();
16257 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16258 if (!BO->isAdditiveOp())
16260 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16263 if (IL->getValue() != 1)
16266 InitExpr = BO->getLHS();
16269 // This checks if the elements are from the same enum.
16270 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16274 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16278 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16285 // Emits a warning when an element is implicitly set a value that
16286 // a previous element has already been set to.
16287 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16288 EnumDecl *Enum, QualType EnumType) {
16289 // Avoid anonymous enums
16290 if (!Enum->getIdentifier())
16293 // Only check for small enums.
16294 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16297 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16300 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16301 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16303 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16304 typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap;
16306 // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16307 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16308 llvm::APSInt Val = D->getInitVal();
16309 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16312 DuplicatesVector DupVector;
16313 ValueToVectorMap EnumMap;
16315 // Populate the EnumMap with all values represented by enum constants without
16317 for (auto *Element : Elements) {
16318 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16320 // Null EnumConstantDecl means a previous diagnostic has been emitted for
16321 // this constant. Skip this enum since it may be ill-formed.
16326 // Constants with initalizers are handled in the next loop.
16327 if (ECD->getInitExpr())
16330 // Duplicate values are handled in the next loop.
16331 EnumMap.insert({EnumConstantToKey(ECD), ECD});
16334 if (EnumMap.size() == 0)
16337 // Create vectors for any values that has duplicates.
16338 for (auto *Element : Elements) {
16339 // The last loop returned if any constant was null.
16340 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16341 if (!ValidDuplicateEnum(ECD, Enum))
16344 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16345 if (Iter == EnumMap.end())
16348 DeclOrVector& Entry = Iter->second;
16349 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16350 // Ensure constants are different.
16354 // Create new vector and push values onto it.
16355 auto Vec = llvm::make_unique<ECDVector>();
16357 Vec->push_back(ECD);
16359 // Update entry to point to the duplicates vector.
16362 // Store the vector somewhere we can consult later for quick emission of
16364 DupVector.emplace_back(std::move(Vec));
16368 ECDVector *Vec = Entry.get<ECDVector*>();
16369 // Make sure constants are not added more than once.
16370 if (*Vec->begin() == ECD)
16373 Vec->push_back(ECD);
16376 // Emit diagnostics.
16377 for (const auto &Vec : DupVector) {
16378 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16380 // Emit warning for one enum constant.
16381 auto *FirstECD = Vec->front();
16382 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16383 << FirstECD << FirstECD->getInitVal().toString(10)
16384 << FirstECD->getSourceRange();
16386 // Emit one note for each of the remaining enum constants with
16388 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16389 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16390 << ECD << ECD->getInitVal().toString(10)
16391 << ECD->getSourceRange();
16395 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16396 bool AllowMask) const {
16397 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16398 assert(ED->isCompleteDefinition() && "expected enum definition");
16400 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16401 llvm::APInt &FlagBits = R.first->second;
16404 for (auto *E : ED->enumerators()) {
16405 const auto &EVal = E->getInitVal();
16406 // Only single-bit enumerators introduce new flag values.
16407 if (EVal.isPowerOf2())
16408 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16412 // A value is in a flag enum if either its bits are a subset of the enum's
16413 // flag bits (the first condition) or we are allowing masks and the same is
16414 // true of its complement (the second condition). When masks are allowed, we
16415 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16417 // While it's true that any value could be used as a mask, the assumption is
16418 // that a mask will have all of the insignificant bits set. Anything else is
16419 // likely a logic error.
16420 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16421 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16424 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16425 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16426 const ParsedAttributesView &Attrs) {
16427 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16428 QualType EnumType = Context.getTypeDeclType(Enum);
16430 ProcessDeclAttributeList(S, Enum, Attrs);
16432 if (Enum->isDependentType()) {
16433 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16434 EnumConstantDecl *ECD =
16435 cast_or_null<EnumConstantDecl>(Elements[i]);
16436 if (!ECD) continue;
16438 ECD->setType(EnumType);
16441 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16445 // TODO: If the result value doesn't fit in an int, it must be a long or long
16446 // long value. ISO C does not support this, but GCC does as an extension,
16448 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16449 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16450 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16452 // Verify that all the values are okay, compute the size of the values, and
16453 // reverse the list.
16454 unsigned NumNegativeBits = 0;
16455 unsigned NumPositiveBits = 0;
16457 // Keep track of whether all elements have type int.
16458 bool AllElementsInt = true;
16460 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16461 EnumConstantDecl *ECD =
16462 cast_or_null<EnumConstantDecl>(Elements[i]);
16463 if (!ECD) continue; // Already issued a diagnostic.
16465 const llvm::APSInt &InitVal = ECD->getInitVal();
16467 // Keep track of the size of positive and negative values.
16468 if (InitVal.isUnsigned() || InitVal.isNonNegative())
16469 NumPositiveBits = std::max(NumPositiveBits,
16470 (unsigned)InitVal.getActiveBits());
16472 NumNegativeBits = std::max(NumNegativeBits,
16473 (unsigned)InitVal.getMinSignedBits());
16475 // Keep track of whether every enum element has type int (very commmon).
16476 if (AllElementsInt)
16477 AllElementsInt = ECD->getType() == Context.IntTy;
16480 // Figure out the type that should be used for this enum.
16482 unsigned BestWidth;
16484 // C++0x N3000 [conv.prom]p3:
16485 // An rvalue of an unscoped enumeration type whose underlying
16486 // type is not fixed can be converted to an rvalue of the first
16487 // of the following types that can represent all the values of
16488 // the enumeration: int, unsigned int, long int, unsigned long
16489 // int, long long int, or unsigned long long int.
16491 // An identifier declared as an enumeration constant has type int.
16492 // The C99 rule is modified by a gcc extension
16493 QualType BestPromotionType;
16495 bool Packed = Enum->hasAttr<PackedAttr>();
16496 // -fshort-enums is the equivalent to specifying the packed attribute on all
16497 // enum definitions.
16498 if (LangOpts.ShortEnums)
16501 // If the enum already has a type because it is fixed or dictated by the
16502 // target, promote that type instead of analyzing the enumerators.
16503 if (Enum->isComplete()) {
16504 BestType = Enum->getIntegerType();
16505 if (BestType->isPromotableIntegerType())
16506 BestPromotionType = Context.getPromotedIntegerType(BestType);
16508 BestPromotionType = BestType;
16510 BestWidth = Context.getIntWidth(BestType);
16512 else if (NumNegativeBits) {
16513 // If there is a negative value, figure out the smallest integer type (of
16514 // int/long/longlong) that fits.
16515 // If it's packed, check also if it fits a char or a short.
16516 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16517 BestType = Context.SignedCharTy;
16518 BestWidth = CharWidth;
16519 } else if (Packed && NumNegativeBits <= ShortWidth &&
16520 NumPositiveBits < ShortWidth) {
16521 BestType = Context.ShortTy;
16522 BestWidth = ShortWidth;
16523 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16524 BestType = Context.IntTy;
16525 BestWidth = IntWidth;
16527 BestWidth = Context.getTargetInfo().getLongWidth();
16529 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16530 BestType = Context.LongTy;
16532 BestWidth = Context.getTargetInfo().getLongLongWidth();
16534 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16535 Diag(Enum->getLocation(), diag::ext_enum_too_large);
16536 BestType = Context.LongLongTy;
16539 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16541 // If there is no negative value, figure out the smallest type that fits
16542 // all of the enumerator values.
16543 // If it's packed, check also if it fits a char or a short.
16544 if (Packed && NumPositiveBits <= CharWidth) {
16545 BestType = Context.UnsignedCharTy;
16546 BestPromotionType = Context.IntTy;
16547 BestWidth = CharWidth;
16548 } else if (Packed && NumPositiveBits <= ShortWidth) {
16549 BestType = Context.UnsignedShortTy;
16550 BestPromotionType = Context.IntTy;
16551 BestWidth = ShortWidth;
16552 } else if (NumPositiveBits <= IntWidth) {
16553 BestType = Context.UnsignedIntTy;
16554 BestWidth = IntWidth;
16556 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16557 ? Context.UnsignedIntTy : Context.IntTy;
16558 } else if (NumPositiveBits <=
16559 (BestWidth = Context.getTargetInfo().getLongWidth())) {
16560 BestType = Context.UnsignedLongTy;
16562 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16563 ? Context.UnsignedLongTy : Context.LongTy;
16565 BestWidth = Context.getTargetInfo().getLongLongWidth();
16566 assert(NumPositiveBits <= BestWidth &&
16567 "How could an initializer get larger than ULL?");
16568 BestType = Context.UnsignedLongLongTy;
16570 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16571 ? Context.UnsignedLongLongTy : Context.LongLongTy;
16575 // Loop over all of the enumerator constants, changing their types to match
16576 // the type of the enum if needed.
16577 for (auto *D : Elements) {
16578 auto *ECD = cast_or_null<EnumConstantDecl>(D);
16579 if (!ECD) continue; // Already issued a diagnostic.
16581 // Standard C says the enumerators have int type, but we allow, as an
16582 // extension, the enumerators to be larger than int size. If each
16583 // enumerator value fits in an int, type it as an int, otherwise type it the
16584 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
16585 // that X has type 'int', not 'unsigned'.
16587 // Determine whether the value fits into an int.
16588 llvm::APSInt InitVal = ECD->getInitVal();
16590 // If it fits into an integer type, force it. Otherwise force it to match
16591 // the enum decl type.
16595 if (!getLangOpts().CPlusPlus &&
16596 !Enum->isFixed() &&
16597 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16598 NewTy = Context.IntTy;
16599 NewWidth = IntWidth;
16601 } else if (ECD->getType() == BestType) {
16602 // Already the right type!
16603 if (getLangOpts().CPlusPlus)
16604 // C++ [dcl.enum]p4: Following the closing brace of an
16605 // enum-specifier, each enumerator has the type of its
16607 ECD->setType(EnumType);
16611 NewWidth = BestWidth;
16612 NewSign = BestType->isSignedIntegerOrEnumerationType();
16615 // Adjust the APSInt value.
16616 InitVal = InitVal.extOrTrunc(NewWidth);
16617 InitVal.setIsSigned(NewSign);
16618 ECD->setInitVal(InitVal);
16620 // Adjust the Expr initializer and type.
16621 if (ECD->getInitExpr() &&
16622 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16623 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16625 ECD->getInitExpr(),
16626 /*base paths*/ nullptr,
16628 if (getLangOpts().CPlusPlus)
16629 // C++ [dcl.enum]p4: Following the closing brace of an
16630 // enum-specifier, each enumerator has the type of its
16632 ECD->setType(EnumType);
16634 ECD->setType(NewTy);
16637 Enum->completeDefinition(BestType, BestPromotionType,
16638 NumPositiveBits, NumNegativeBits);
16640 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16642 if (Enum->isClosedFlag()) {
16643 for (Decl *D : Elements) {
16644 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16645 if (!ECD) continue; // Already issued a diagnostic.
16647 llvm::APSInt InitVal = ECD->getInitVal();
16648 if (InitVal != 0 && !InitVal.isPowerOf2() &&
16649 !IsValueInFlagEnum(Enum, InitVal, true))
16650 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16655 // Now that the enum type is defined, ensure it's not been underaligned.
16656 if (Enum->hasAttrs())
16657 CheckAlignasUnderalignment(Enum);
16660 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16661 SourceLocation StartLoc,
16662 SourceLocation EndLoc) {
16663 StringLiteral *AsmString = cast<StringLiteral>(expr);
16665 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16666 AsmString, StartLoc,
16668 CurContext->addDecl(New);
16672 static void checkModuleImportContext(Sema &S, Module *M,
16673 SourceLocation ImportLoc, DeclContext *DC,
16674 bool FromInclude = false) {
16675 SourceLocation ExternCLoc;
16677 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16678 switch (LSD->getLanguage()) {
16679 case LinkageSpecDecl::lang_c:
16680 if (ExternCLoc.isInvalid())
16681 ExternCLoc = LSD->getLocStart();
16683 case LinkageSpecDecl::lang_cxx:
16686 DC = LSD->getParent();
16689 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16690 DC = DC->getParent();
16692 if (!isa<TranslationUnitDecl>(DC)) {
16693 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16694 ? diag::ext_module_import_not_at_top_level_noop
16695 : diag::err_module_import_not_at_top_level_fatal)
16696 << M->getFullModuleName() << DC;
16697 S.Diag(cast<Decl>(DC)->getLocStart(),
16698 diag::note_module_import_not_at_top_level) << DC;
16699 } else if (!M->IsExternC && ExternCLoc.isValid()) {
16700 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16701 << M->getFullModuleName();
16702 S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16706 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16707 SourceLocation ModuleLoc,
16708 ModuleDeclKind MDK,
16709 ModuleIdPath Path) {
16710 assert(getLangOpts().ModulesTS &&
16711 "should only have module decl in modules TS");
16713 // A module implementation unit requires that we are not compiling a module
16714 // of any kind. A module interface unit requires that we are not compiling a
16716 switch (getLangOpts().getCompilingModule()) {
16717 case LangOptions::CMK_None:
16718 // It's OK to compile a module interface as a normal translation unit.
16721 case LangOptions::CMK_ModuleInterface:
16722 if (MDK != ModuleDeclKind::Implementation)
16725 // We were asked to compile a module interface unit but this is a module
16726 // implementation unit. That indicates the 'export' is missing.
16727 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16728 << FixItHint::CreateInsertion(ModuleLoc, "export ");
16729 MDK = ModuleDeclKind::Interface;
16732 case LangOptions::CMK_ModuleMap:
16733 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16737 assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16739 // FIXME: Most of this work should be done by the preprocessor rather than
16740 // here, in order to support macro import.
16742 // Only one module-declaration is permitted per source file.
16743 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16744 Diag(ModuleLoc, diag::err_module_redeclaration);
16745 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16746 diag::note_prev_module_declaration);
16750 // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16751 // modules, the dots here are just another character that can appear in a
16753 std::string ModuleName;
16754 for (auto &Piece : Path) {
16755 if (!ModuleName.empty())
16757 ModuleName += Piece.first->getName();
16760 // If a module name was explicitly specified on the command line, it must be
16762 if (!getLangOpts().CurrentModule.empty() &&
16763 getLangOpts().CurrentModule != ModuleName) {
16764 Diag(Path.front().second, diag::err_current_module_name_mismatch)
16765 << SourceRange(Path.front().second, Path.back().second)
16766 << getLangOpts().CurrentModule;
16769 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16771 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16775 case ModuleDeclKind::Interface: {
16776 // We can't have parsed or imported a definition of this module or parsed a
16777 // module map defining it already.
16778 if (auto *M = Map.findModule(ModuleName)) {
16779 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16780 if (M->DefinitionLoc.isValid())
16781 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16782 else if (const auto *FE = M->getASTFile())
16783 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16789 // Create a Module for the module that we're defining.
16790 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16791 ModuleScopes.front().Module);
16792 assert(Mod && "module creation should not fail");
16796 case ModuleDeclKind::Partition:
16797 // FIXME: Check we are in a submodule of the named module.
16800 case ModuleDeclKind::Implementation:
16801 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16802 PP.getIdentifierInfo(ModuleName), Path[0].second);
16803 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16804 /*IsIncludeDirective=*/false);
16806 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16807 // Create an empty module interface unit for error recovery.
16808 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16809 ModuleScopes.front().Module);
16814 // Switch from the global module to the named module.
16815 ModuleScopes.back().Module = Mod;
16816 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16817 VisibleModules.setVisible(Mod, ModuleLoc);
16819 // From now on, we have an owning module for all declarations we see.
16820 // However, those declarations are module-private unless explicitly
16822 auto *TU = Context.getTranslationUnitDecl();
16823 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16824 TU->setLocalOwningModule(Mod);
16826 // FIXME: Create a ModuleDecl.
16830 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16831 SourceLocation ImportLoc,
16832 ModuleIdPath Path) {
16834 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16835 /*IsIncludeDirective=*/false);
16839 VisibleModules.setVisible(Mod, ImportLoc);
16841 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16843 // FIXME: we should support importing a submodule within a different submodule
16844 // of the same top-level module. Until we do, make it an error rather than
16845 // silently ignoring the import.
16846 // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16847 // warn on a redundant import of the current module?
16848 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16849 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16850 Diag(ImportLoc, getLangOpts().isCompilingModule()
16851 ? diag::err_module_self_import
16852 : diag::err_module_import_in_implementation)
16853 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16855 SmallVector<SourceLocation, 2> IdentifierLocs;
16856 Module *ModCheck = Mod;
16857 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16858 // If we've run out of module parents, just drop the remaining identifiers.
16859 // We need the length to be consistent.
16862 ModCheck = ModCheck->Parent;
16864 IdentifierLocs.push_back(Path[I].second);
16867 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
16868 Mod, IdentifierLocs);
16869 if (!ModuleScopes.empty())
16870 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16871 CurContext->addDecl(Import);
16873 // Re-export the module if needed.
16874 if (Import->isExported() &&
16875 !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
16876 getCurrentModule()->Exports.emplace_back(Mod, false);
16881 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16882 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16883 BuildModuleInclude(DirectiveLoc, Mod);
16886 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16887 // Determine whether we're in the #include buffer for a module. The #includes
16888 // in that buffer do not qualify as module imports; they're just an
16889 // implementation detail of us building the module.
16891 // FIXME: Should we even get ActOnModuleInclude calls for those?
16892 bool IsInModuleIncludes =
16893 TUKind == TU_Module &&
16894 getSourceManager().isWrittenInMainFile(DirectiveLoc);
16896 bool ShouldAddImport = !IsInModuleIncludes;
16898 // If this module import was due to an inclusion directive, create an
16899 // implicit import declaration to capture it in the AST.
16900 if (ShouldAddImport) {
16901 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16902 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16905 if (!ModuleScopes.empty())
16906 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16907 TU->addDecl(ImportD);
16908 Consumer.HandleImplicitImportDecl(ImportD);
16911 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16912 VisibleModules.setVisible(Mod, DirectiveLoc);
16915 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16916 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16918 ModuleScopes.push_back({});
16919 ModuleScopes.back().Module = Mod;
16920 if (getLangOpts().ModulesLocalVisibility)
16921 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16923 VisibleModules.setVisible(Mod, DirectiveLoc);
16925 // The enclosing context is now part of this module.
16926 // FIXME: Consider creating a child DeclContext to hold the entities
16927 // lexically within the module.
16928 if (getLangOpts().trackLocalOwningModule()) {
16929 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16930 cast<Decl>(DC)->setModuleOwnershipKind(
16931 getLangOpts().ModulesLocalVisibility
16932 ? Decl::ModuleOwnershipKind::VisibleWhenImported
16933 : Decl::ModuleOwnershipKind::Visible);
16934 cast<Decl>(DC)->setLocalOwningModule(Mod);
16939 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16940 if (getLangOpts().ModulesLocalVisibility) {
16941 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16942 // Leaving a module hides namespace names, so our visible namespace cache
16943 // is now out of date.
16944 VisibleNamespaceCache.clear();
16947 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16948 "left the wrong module scope");
16949 ModuleScopes.pop_back();
16951 // We got to the end of processing a local module. Create an
16952 // ImportDecl as we would for an imported module.
16953 FileID File = getSourceManager().getFileID(EomLoc);
16954 SourceLocation DirectiveLoc;
16955 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16956 // We reached the end of a #included module header. Use the #include loc.
16957 assert(File != getSourceManager().getMainFileID() &&
16958 "end of submodule in main source file");
16959 DirectiveLoc = getSourceManager().getIncludeLoc(File);
16961 // We reached an EOM pragma. Use the pragma location.
16962 DirectiveLoc = EomLoc;
16964 BuildModuleInclude(DirectiveLoc, Mod);
16966 // Any further declarations are in whatever module we returned to.
16967 if (getLangOpts().trackLocalOwningModule()) {
16968 // The parser guarantees that this is the same context that we entered
16969 // the module within.
16970 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16971 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16972 if (!getCurrentModule())
16973 cast<Decl>(DC)->setModuleOwnershipKind(
16974 Decl::ModuleOwnershipKind::Unowned);
16979 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16981 // Bail if we're not allowed to implicitly import a module here.
16982 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16983 VisibleModules.isVisible(Mod))
16986 // Create the implicit import declaration.
16987 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16988 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16990 TU->addDecl(ImportD);
16991 Consumer.HandleImplicitImportDecl(ImportD);
16993 // Make the module visible.
16994 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16995 VisibleModules.setVisible(Mod, Loc);
16998 /// We have parsed the start of an export declaration, including the '{'
17000 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
17001 SourceLocation LBraceLoc) {
17002 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
17004 // C++ Modules TS draft:
17005 // An export-declaration shall appear in the purview of a module other than
17006 // the global module.
17007 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
17008 Diag(ExportLoc, diag::err_export_not_in_module_interface);
17010 // An export-declaration [...] shall not contain more than one
17013 // The intent here is that an export-declaration cannot appear within another
17014 // export-declaration.
17015 if (D->isExported())
17016 Diag(ExportLoc, diag::err_export_within_export);
17018 CurContext->addDecl(D);
17019 PushDeclContext(S, D);
17020 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
17024 /// Complete the definition of an export declaration.
17025 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
17026 auto *ED = cast<ExportDecl>(D);
17027 if (RBraceLoc.isValid())
17028 ED->setRBraceLoc(RBraceLoc);
17030 // FIXME: Diagnose export of internal-linkage declaration (including
17031 // anonymous namespace).
17037 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17038 IdentifierInfo* AliasName,
17039 SourceLocation PragmaLoc,
17040 SourceLocation NameLoc,
17041 SourceLocation AliasNameLoc) {
17042 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17043 LookupOrdinaryName);
17044 AsmLabelAttr *Attr =
17045 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17047 // If a declaration that:
17048 // 1) declares a function or a variable
17049 // 2) has external linkage
17050 // already exists, add a label attribute to it.
17051 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17052 if (isDeclExternC(PrevDecl))
17053 PrevDecl->addAttr(Attr);
17055 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17056 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17057 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17059 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17062 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17063 SourceLocation PragmaLoc,
17064 SourceLocation NameLoc) {
17065 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17068 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17070 (void)WeakUndeclaredIdentifiers.insert(
17071 std::pair<IdentifierInfo*,WeakInfo>
17072 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17076 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17077 IdentifierInfo* AliasName,
17078 SourceLocation PragmaLoc,
17079 SourceLocation NameLoc,
17080 SourceLocation AliasNameLoc) {
17081 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17082 LookupOrdinaryName);
17083 WeakInfo W = WeakInfo(Name, NameLoc);
17085 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17086 if (!PrevDecl->hasAttr<AliasAttr>())
17087 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17088 DeclApplyPragmaWeak(TUScope, ND, W);
17090 (void)WeakUndeclaredIdentifiers.insert(
17091 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17095 Decl *Sema::getObjCDeclContext() const {
17096 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));