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 /// \brief 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___float128:
136 case tok::kw_wchar_t:
138 case tok::kw___underlying_type:
139 case tok::kw___auto_type:
142 case tok::annot_typename:
143 case tok::kw_char16_t:
144 case tok::kw_char32_t:
146 case tok::annot_decltype:
147 case tok::kw_decltype:
148 return getLangOpts().CPlusPlus;
158 enum class UnqualifiedTypeNameLookupResult {
163 } // end anonymous namespace
165 /// \brief Tries to perform unqualified lookup of the type decls in bases for
167 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
168 /// type decl, \a FoundType if only type decls are found.
169 static UnqualifiedTypeNameLookupResult
170 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
171 SourceLocation NameLoc,
172 const CXXRecordDecl *RD) {
173 if (!RD->hasDefinition())
174 return UnqualifiedTypeNameLookupResult::NotFound;
175 // Look for type decls in base classes.
176 UnqualifiedTypeNameLookupResult FoundTypeDecl =
177 UnqualifiedTypeNameLookupResult::NotFound;
178 for (const auto &Base : RD->bases()) {
179 const CXXRecordDecl *BaseRD = nullptr;
180 if (auto *BaseTT = Base.getType()->getAs<TagType>())
181 BaseRD = BaseTT->getAsCXXRecordDecl();
182 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
183 // Look for type decls in dependent base classes that have known primary
185 if (!TST || !TST->isDependentType())
187 auto *TD = TST->getTemplateName().getAsTemplateDecl();
190 if (auto *BasePrimaryTemplate =
191 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
192 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
193 BaseRD = BasePrimaryTemplate;
194 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
195 if (const ClassTemplatePartialSpecializationDecl *PS =
196 CTD->findPartialSpecialization(Base.getType()))
197 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
203 for (NamedDecl *ND : BaseRD->lookup(&II)) {
204 if (!isa<TypeDecl>(ND))
205 return UnqualifiedTypeNameLookupResult::FoundNonType;
206 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
208 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
209 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
210 case UnqualifiedTypeNameLookupResult::FoundNonType:
211 return UnqualifiedTypeNameLookupResult::FoundNonType;
212 case UnqualifiedTypeNameLookupResult::FoundType:
213 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215 case UnqualifiedTypeNameLookupResult::NotFound:
222 return FoundTypeDecl;
225 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
226 const IdentifierInfo &II,
227 SourceLocation NameLoc) {
228 // Lookup in the parent class template context, if any.
229 const CXXRecordDecl *RD = nullptr;
230 UnqualifiedTypeNameLookupResult FoundTypeDecl =
231 UnqualifiedTypeNameLookupResult::NotFound;
232 for (DeclContext *DC = S.CurContext;
233 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
234 DC = DC->getParent()) {
235 // Look for type decls in dependent base classes that have known primary
237 RD = dyn_cast<CXXRecordDecl>(DC);
238 if (RD && RD->getDescribedClassTemplate())
239 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
241 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
244 // We found some types in dependent base classes. Recover as if the user
245 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
246 // lookup during template instantiation.
247 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
249 ASTContext &Context = S.Context;
250 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
251 cast<Type>(Context.getRecordType(RD)));
252 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
255 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
257 TypeLocBuilder Builder;
258 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
259 DepTL.setNameLoc(NameLoc);
260 DepTL.setElaboratedKeywordLoc(SourceLocation());
261 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
262 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
265 /// \brief If the identifier refers to a type name within this scope,
266 /// return the declaration of that type.
268 /// This routine performs ordinary name lookup of the identifier II
269 /// within the given scope, with optional C++ scope specifier SS, to
270 /// determine whether the name refers to a type. If so, returns an
271 /// opaque pointer (actually a QualType) corresponding to that
272 /// type. Otherwise, returns NULL.
273 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
274 Scope *S, CXXScopeSpec *SS,
275 bool isClassName, bool HasTrailingDot,
276 ParsedType ObjectTypePtr,
277 bool IsCtorOrDtorName,
278 bool WantNontrivialTypeSourceInfo,
279 bool IsClassTemplateDeductionContext,
280 IdentifierInfo **CorrectedII) {
281 // FIXME: Consider allowing this outside C++1z mode as an extension.
282 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
283 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
284 !isClassName && !HasTrailingDot;
286 // Determine where we will perform name lookup.
287 DeclContext *LookupCtx = nullptr;
289 QualType ObjectType = ObjectTypePtr.get();
290 if (ObjectType->isRecordType())
291 LookupCtx = computeDeclContext(ObjectType);
292 } else if (SS && SS->isNotEmpty()) {
293 LookupCtx = computeDeclContext(*SS, false);
296 if (isDependentScopeSpecifier(*SS)) {
298 // A qualified-id that refers to a type and in which the
299 // nested-name-specifier depends on a template-parameter (14.6.2)
300 // shall be prefixed by the keyword typename to indicate that the
301 // qualified-id denotes a type, forming an
302 // elaborated-type-specifier (7.1.5.3).
304 // We therefore do not perform any name lookup if the result would
305 // refer to a member of an unknown specialization.
306 if (!isClassName && !IsCtorOrDtorName)
309 // We know from the grammar that this name refers to a type,
310 // so build a dependent node to describe the type.
311 if (WantNontrivialTypeSourceInfo)
312 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
314 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
315 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
317 return ParsedType::make(T);
323 if (!LookupCtx->isDependentContext() &&
324 RequireCompleteDeclContext(*SS, LookupCtx))
328 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
329 // lookup for class-names.
330 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
332 LookupResult Result(*this, &II, NameLoc, Kind);
334 // Perform "qualified" name lookup into the declaration context we
335 // computed, which is either the type of the base of a member access
336 // expression or the declaration context associated with a prior
337 // nested-name-specifier.
338 LookupQualifiedName(Result, LookupCtx);
340 if (ObjectTypePtr && Result.empty()) {
341 // C++ [basic.lookup.classref]p3:
342 // If the unqualified-id is ~type-name, the type-name is looked up
343 // in the context of the entire postfix-expression. If the type T of
344 // the object expression is of a class type C, the type-name is also
345 // looked up in the scope of class C. At least one of the lookups shall
346 // find a name that refers to (possibly cv-qualified) T.
347 LookupName(Result, S);
350 // Perform unqualified name lookup.
351 LookupName(Result, S);
353 // For unqualified lookup in a class template in MSVC mode, look into
354 // dependent base classes where the primary class template is known.
355 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
356 if (ParsedType TypeInBase =
357 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
362 NamedDecl *IIDecl = nullptr;
363 switch (Result.getResultKind()) {
364 case LookupResult::NotFound:
365 case LookupResult::NotFoundInCurrentInstantiation:
367 TypoCorrection Correction =
368 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
369 llvm::make_unique<TypeNameValidatorCCC>(
370 true, isClassName, AllowDeducedTemplate),
372 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
374 bool MemberOfUnknownSpecialization;
375 UnqualifiedId TemplateName;
376 TemplateName.setIdentifier(NewII, NameLoc);
377 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
378 CXXScopeSpec NewSS, *NewSSPtr = SS;
380 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
383 if (Correction && (NNS || NewII != &II) &&
384 // Ignore a correction to a template type as the to-be-corrected
385 // identifier is not a template (typo correction for template names
386 // is handled elsewhere).
387 !(getLangOpts().CPlusPlus && NewSSPtr &&
388 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
389 Template, MemberOfUnknownSpecialization))) {
390 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
391 isClassName, HasTrailingDot, ObjectTypePtr,
393 WantNontrivialTypeSourceInfo,
394 IsClassTemplateDeductionContext);
396 diagnoseTypo(Correction,
397 PDiag(diag::err_unknown_type_or_class_name_suggest)
398 << Result.getLookupName() << isClassName);
400 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
401 *CorrectedII = NewII;
406 // If typo correction failed or was not performed, fall through
408 case LookupResult::FoundOverloaded:
409 case LookupResult::FoundUnresolvedValue:
410 Result.suppressDiagnostics();
413 case LookupResult::Ambiguous:
414 // Recover from type-hiding ambiguities by hiding the type. We'll
415 // do the lookup again when looking for an object, and we can
416 // diagnose the error then. If we don't do this, then the error
417 // about hiding the type will be immediately followed by an error
418 // that only makes sense if the identifier was treated like a type.
419 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
420 Result.suppressDiagnostics();
424 // Look to see if we have a type anywhere in the list of results.
425 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
426 Res != ResEnd; ++Res) {
427 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
428 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
430 (*Res)->getLocation().getRawEncoding() <
431 IIDecl->getLocation().getRawEncoding())
437 // None of the entities we found is a type, so there is no way
438 // to even assume that the result is a type. In this case, don't
439 // complain about the ambiguity. The parser will either try to
440 // perform this lookup again (e.g., as an object name), which
441 // will produce the ambiguity, or will complain that it expected
443 Result.suppressDiagnostics();
447 // We found a type within the ambiguous lookup; diagnose the
448 // ambiguity and then return that type. This might be the right
449 // answer, or it might not be, but it suppresses any attempt to
450 // perform the name lookup again.
453 case LookupResult::Found:
454 IIDecl = Result.getFoundDecl();
458 assert(IIDecl && "Didn't find decl");
461 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
462 // C++ [class.qual]p2: A lookup that would find the injected-class-name
463 // instead names the constructors of the class, except when naming a class.
464 // This is ill-formed when we're not actually forming a ctor or dtor name.
465 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
466 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
467 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
468 FoundRD->isInjectedClassName() &&
469 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
470 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
473 DiagnoseUseOfDecl(IIDecl, NameLoc);
475 T = Context.getTypeDeclType(TD);
476 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
477 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
478 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
480 T = Context.getObjCInterfaceType(IDecl);
481 } else if (AllowDeducedTemplate) {
482 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
483 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
488 // If it's not plausibly a type, suppress diagnostics.
489 Result.suppressDiagnostics();
493 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
494 // constructor or destructor name (in such a case, the scope specifier
495 // will be attached to the enclosing Expr or Decl node).
496 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
497 !isa<ObjCInterfaceDecl>(IIDecl)) {
498 if (WantNontrivialTypeSourceInfo) {
499 // Construct a type with type-source information.
500 TypeLocBuilder Builder;
501 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
503 T = getElaboratedType(ETK_None, *SS, T);
504 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
505 ElabTL.setElaboratedKeywordLoc(SourceLocation());
506 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
507 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
509 T = getElaboratedType(ETK_None, *SS, T);
513 return ParsedType::make(T);
516 // Builds a fake NNS for the given decl context.
517 static NestedNameSpecifier *
518 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
519 for (;; DC = DC->getLookupParent()) {
520 DC = DC->getPrimaryContext();
521 auto *ND = dyn_cast<NamespaceDecl>(DC);
522 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
523 return NestedNameSpecifier::Create(Context, nullptr, ND);
524 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
525 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
526 RD->getTypeForDecl());
527 else if (isa<TranslationUnitDecl>(DC))
528 return NestedNameSpecifier::GlobalSpecifier(Context);
530 llvm_unreachable("something isn't in TU scope?");
533 /// Find the parent class with dependent bases of the innermost enclosing method
534 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
535 /// up allowing unqualified dependent type names at class-level, which MSVC
536 /// correctly rejects.
537 static const CXXRecordDecl *
538 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
539 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
540 DC = DC->getPrimaryContext();
541 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
542 if (MD->getParent()->hasAnyDependentBases())
543 return MD->getParent();
548 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
549 SourceLocation NameLoc,
550 bool IsTemplateTypeArg) {
551 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
553 NestedNameSpecifier *NNS = nullptr;
554 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
555 // If we weren't able to parse a default template argument, delay lookup
556 // until instantiation time by making a non-dependent DependentTypeName. We
557 // pretend we saw a NestedNameSpecifier referring to the current scope, and
558 // lookup is retried.
559 // FIXME: This hurts our diagnostic quality, since we get errors like "no
560 // type named 'Foo' in 'current_namespace'" when the user didn't write any
562 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
563 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
564 } else if (const CXXRecordDecl *RD =
565 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
566 // Build a DependentNameType that will perform lookup into RD at
567 // instantiation time.
568 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
569 RD->getTypeForDecl());
571 // Diagnose that this identifier was undeclared, and retry the lookup during
572 // template instantiation.
573 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
576 // This is not a situation that we should recover from.
580 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
582 // Build type location information. We synthesized the qualifier, so we have
583 // to build a fake NestedNameSpecifierLoc.
584 NestedNameSpecifierLocBuilder NNSLocBuilder;
585 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
586 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
588 TypeLocBuilder Builder;
589 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
590 DepTL.setNameLoc(NameLoc);
591 DepTL.setElaboratedKeywordLoc(SourceLocation());
592 DepTL.setQualifierLoc(QualifierLoc);
593 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
596 /// isTagName() - This method is called *for error recovery purposes only*
597 /// to determine if the specified name is a valid tag name ("struct foo"). If
598 /// so, this returns the TST for the tag corresponding to it (TST_enum,
599 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
600 /// cases in C where the user forgot to specify the tag.
601 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
602 // Do a tag name lookup in this scope.
603 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
604 LookupName(R, S, false);
605 R.suppressDiagnostics();
606 if (R.getResultKind() == LookupResult::Found)
607 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
608 switch (TD->getTagKind()) {
609 case TTK_Struct: return DeclSpec::TST_struct;
610 case TTK_Interface: return DeclSpec::TST_interface;
611 case TTK_Union: return DeclSpec::TST_union;
612 case TTK_Class: return DeclSpec::TST_class;
613 case TTK_Enum: return DeclSpec::TST_enum;
617 return DeclSpec::TST_unspecified;
620 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
621 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
622 /// then downgrade the missing typename error to a warning.
623 /// This is needed for MSVC compatibility; Example:
625 /// template<class T> class A {
627 /// typedef int TYPE;
629 /// template<class T> class B : public A<T> {
631 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
634 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
635 if (CurContext->isRecord()) {
636 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
639 const Type *Ty = SS->getScopeRep()->getAsType();
641 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
642 for (const auto &Base : RD->bases())
643 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
645 return S->isFunctionPrototypeScope();
647 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
650 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
651 SourceLocation IILoc,
654 ParsedType &SuggestedType,
655 bool IsTemplateName) {
656 // Don't report typename errors for editor placeholders.
657 if (II->isEditorPlaceholder())
659 // We don't have anything to suggest (yet).
660 SuggestedType = nullptr;
662 // There may have been a typo in the name of the type. Look up typo
663 // results, in case we have something that we can suggest.
664 if (TypoCorrection Corrected =
665 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
666 llvm::make_unique<TypeNameValidatorCCC>(
667 false, false, IsTemplateName, !IsTemplateName),
668 CTK_ErrorRecovery)) {
669 // FIXME: Support error recovery for the template-name case.
670 bool CanRecover = !IsTemplateName;
671 if (Corrected.isKeyword()) {
672 // We corrected to a keyword.
673 diagnoseTypo(Corrected,
674 PDiag(IsTemplateName ? diag::err_no_template_suggest
675 : diag::err_unknown_typename_suggest)
677 II = Corrected.getCorrectionAsIdentifierInfo();
679 // We found a similarly-named type or interface; suggest that.
680 if (!SS || !SS->isSet()) {
681 diagnoseTypo(Corrected,
682 PDiag(IsTemplateName ? diag::err_no_template_suggest
683 : diag::err_unknown_typename_suggest)
685 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
686 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
687 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
688 II->getName().equals(CorrectedStr);
689 diagnoseTypo(Corrected,
691 ? diag::err_no_member_template_suggest
692 : diag::err_unknown_nested_typename_suggest)
693 << II << DC << DroppedSpecifier << SS->getRange(),
696 llvm_unreachable("could not have corrected a typo here");
703 if (Corrected.getCorrectionSpecifier())
704 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
706 // FIXME: Support class template argument deduction here.
708 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
709 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
710 /*IsCtorOrDtorName=*/false,
711 /*NonTrivialTypeSourceInfo=*/true);
716 if (getLangOpts().CPlusPlus && !IsTemplateName) {
717 // See if II is a class template that the user forgot to pass arguments to.
719 Name.setIdentifier(II, IILoc);
720 CXXScopeSpec EmptySS;
721 TemplateTy TemplateResult;
722 bool MemberOfUnknownSpecialization;
723 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
724 Name, nullptr, true, TemplateResult,
725 MemberOfUnknownSpecialization) == TNK_Type_template) {
726 TemplateName TplName = TemplateResult.get();
727 Diag(IILoc, diag::err_template_missing_args)
728 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
729 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
730 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
731 << TplDecl->getTemplateParameters()->getSourceRange();
737 // FIXME: Should we move the logic that tries to recover from a missing tag
738 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
740 if (!SS || (!SS->isSet() && !SS->isInvalid()))
741 Diag(IILoc, IsTemplateName ? diag::err_no_template
742 : diag::err_unknown_typename)
744 else if (DeclContext *DC = computeDeclContext(*SS, false))
745 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
746 : diag::err_typename_nested_not_found)
747 << II << DC << SS->getRange();
748 else if (isDependentScopeSpecifier(*SS)) {
749 unsigned DiagID = diag::err_typename_missing;
750 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
751 DiagID = diag::ext_typename_missing;
753 Diag(SS->getRange().getBegin(), DiagID)
754 << SS->getScopeRep() << II->getName()
755 << SourceRange(SS->getRange().getBegin(), IILoc)
756 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
757 SuggestedType = ActOnTypenameType(S, SourceLocation(),
758 *SS, *II, IILoc).get();
760 assert(SS && SS->isInvalid() &&
761 "Invalid scope specifier has already been diagnosed");
765 /// \brief Determine whether the given result set contains either a type name
767 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
768 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
769 NextToken.is(tok::less);
771 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
772 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
775 if (CheckTemplate && isa<TemplateDecl>(*I))
782 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
783 Scope *S, CXXScopeSpec &SS,
784 IdentifierInfo *&Name,
785 SourceLocation NameLoc) {
786 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
787 SemaRef.LookupParsedName(R, S, &SS);
788 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
789 StringRef FixItTagName;
790 switch (Tag->getTagKind()) {
792 FixItTagName = "class ";
796 FixItTagName = "enum ";
800 FixItTagName = "struct ";
804 FixItTagName = "__interface ";
808 FixItTagName = "union ";
812 StringRef TagName = FixItTagName.drop_back();
813 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
814 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
815 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
817 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
819 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
822 // Replace lookup results with just the tag decl.
823 Result.clear(Sema::LookupTagName);
824 SemaRef.LookupParsedName(Result, S, &SS);
831 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
832 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
833 QualType T, SourceLocation NameLoc) {
834 ASTContext &Context = S.Context;
836 TypeLocBuilder Builder;
837 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839 T = S.getElaboratedType(ETK_None, SS, T);
840 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
841 ElabTL.setElaboratedKeywordLoc(SourceLocation());
842 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
843 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
846 Sema::NameClassification
847 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
848 SourceLocation NameLoc, const Token &NextToken,
849 bool IsAddressOfOperand,
850 std::unique_ptr<CorrectionCandidateCallback> CCC) {
851 DeclarationNameInfo NameInfo(Name, NameLoc);
852 ObjCMethodDecl *CurMethod = getCurMethodDecl();
854 if (NextToken.is(tok::coloncolon)) {
855 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
856 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
857 } else if (getLangOpts().CPlusPlus && SS.isSet() &&
858 isCurrentClassName(*Name, S, &SS)) {
859 // Per [class.qual]p2, this names the constructors of SS, not the
860 // injected-class-name. We don't have a classification for that.
861 // There's not much point caching this result, since the parser
862 // will reject it later.
863 return NameClassification::Unknown();
866 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
867 LookupParsedName(Result, S, &SS, !CurMethod);
869 // For unqualified lookup in a class template in MSVC mode, look into
870 // dependent base classes where the primary class template is known.
871 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
872 if (ParsedType TypeInBase =
873 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
877 // Perform lookup for Objective-C instance variables (including automatically
878 // synthesized instance variables), if we're in an Objective-C method.
879 // FIXME: This lookup really, really needs to be folded in to the normal
880 // unqualified lookup mechanism.
881 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
882 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
883 if (E.get() || E.isInvalid())
887 bool SecondTry = false;
888 bool IsFilteredTemplateName = false;
891 switch (Result.getResultKind()) {
892 case LookupResult::NotFound:
893 // If an unqualified-id is followed by a '(', then we have a function
895 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
896 // In C++, this is an ADL-only call.
898 if (getLangOpts().CPlusPlus)
899 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
902 // If the expression that precedes the parenthesized argument list in a
903 // function call consists solely of an identifier, and if no
904 // declaration is visible for this identifier, the identifier is
905 // implicitly declared exactly as if, in the innermost block containing
906 // the function call, the declaration
908 // extern int identifier ();
912 // We also allow this in C99 as an extension.
913 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915 Result.resolveKind();
916 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
920 // In C, we first see whether there is a tag type by the same name, in
921 // which case it's likely that the user just forgot to write "enum",
922 // "struct", or "union".
923 if (!getLangOpts().CPlusPlus && !SecondTry &&
924 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
928 // Perform typo correction to determine if there is another name that is
929 // close to this name.
930 if (!SecondTry && CCC) {
932 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
933 Result.getLookupKind(), S,
935 CTK_ErrorRecovery)) {
936 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
937 unsigned QualifiedDiag = diag::err_no_member_suggest;
939 NamedDecl *FirstDecl = Corrected.getFoundDecl();
940 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
941 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
942 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
943 UnqualifiedDiag = diag::err_no_template_suggest;
944 QualifiedDiag = diag::err_no_member_template_suggest;
945 } else if (UnderlyingFirstDecl &&
946 (isa<TypeDecl>(UnderlyingFirstDecl) ||
947 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
948 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
949 UnqualifiedDiag = diag::err_unknown_typename_suggest;
950 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
954 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
955 } else {// FIXME: is this even reachable? Test it.
956 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
957 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
958 Name->getName().equals(CorrectedStr);
959 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
960 << Name << computeDeclContext(SS, false)
961 << DroppedSpecifier << SS.getRange());
964 // Update the name, so that the caller has the new name.
965 Name = Corrected.getCorrectionAsIdentifierInfo();
967 // Typo correction corrected to a keyword.
968 if (Corrected.isKeyword())
971 // Also update the LookupResult...
972 // FIXME: This should probably go away at some point
974 Result.setLookupName(Corrected.getCorrection());
976 Result.addDecl(FirstDecl);
978 // If we found an Objective-C instance variable, let
979 // LookupInObjCMethod build the appropriate expression to
980 // reference the ivar.
981 // FIXME: This is a gross hack.
982 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
984 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
992 // We failed to correct; just fall through and let the parser deal with it.
993 Result.suppressDiagnostics();
994 return NameClassification::Unknown();
996 case LookupResult::NotFoundInCurrentInstantiation: {
997 // We performed name lookup into the current instantiation, and there were
998 // dependent bases, so we treat this result the same way as any other
999 // dependent nested-name-specifier.
1001 // C++ [temp.res]p2:
1002 // A name used in a template declaration or definition and that is
1003 // dependent on a template-parameter is assumed not to name a type
1004 // unless the applicable name lookup finds a type name or the name is
1005 // qualified by the keyword typename.
1007 // FIXME: If the next token is '<', we might want to ask the parser to
1008 // perform some heroics to see if we actually have a
1009 // template-argument-list, which would indicate a missing 'template'
1011 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1012 NameInfo, IsAddressOfOperand,
1013 /*TemplateArgs=*/nullptr);
1016 case LookupResult::Found:
1017 case LookupResult::FoundOverloaded:
1018 case LookupResult::FoundUnresolvedValue:
1021 case LookupResult::Ambiguous:
1022 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1023 hasAnyAcceptableTemplateNames(Result)) {
1024 // C++ [temp.local]p3:
1025 // A lookup that finds an injected-class-name (10.2) can result in an
1026 // ambiguity in certain cases (for example, if it is found in more than
1027 // one base class). If all of the injected-class-names that are found
1028 // refer to specializations of the same class template, and if the name
1029 // is followed by a template-argument-list, the reference refers to the
1030 // class template itself and not a specialization thereof, and is not
1033 // This filtering can make an ambiguous result into an unambiguous one,
1034 // so try again after filtering out template names.
1035 FilterAcceptableTemplateNames(Result);
1036 if (!Result.isAmbiguous()) {
1037 IsFilteredTemplateName = true;
1042 // Diagnose the ambiguity and return an error.
1043 return NameClassification::Error();
1046 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1047 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1048 // C++ [temp.names]p3:
1049 // After name lookup (3.4) finds that a name is a template-name or that
1050 // an operator-function-id or a literal- operator-id refers to a set of
1051 // overloaded functions any member of which is a function template if
1052 // this is followed by a <, the < is always taken as the delimiter of a
1053 // template-argument-list and never as the less-than operator.
1054 if (!IsFilteredTemplateName)
1055 FilterAcceptableTemplateNames(Result);
1057 if (!Result.empty()) {
1058 bool IsFunctionTemplate;
1060 TemplateName Template;
1061 if (Result.end() - Result.begin() > 1) {
1062 IsFunctionTemplate = true;
1063 Template = Context.getOverloadedTemplateName(Result.begin(),
1067 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1068 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1069 IsVarTemplate = isa<VarTemplateDecl>(TD);
1071 if (SS.isSet() && !SS.isInvalid())
1072 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1073 /*TemplateKeyword=*/false,
1076 Template = TemplateName(TD);
1079 if (IsFunctionTemplate) {
1080 // Function templates always go through overload resolution, at which
1081 // point we'll perform the various checks (e.g., accessibility) we need
1082 // to based on which function we selected.
1083 Result.suppressDiagnostics();
1085 return NameClassification::FunctionTemplate(Template);
1088 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1089 : NameClassification::TypeTemplate(Template);
1093 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1094 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1095 DiagnoseUseOfDecl(Type, NameLoc);
1096 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1097 QualType T = Context.getTypeDeclType(Type);
1098 if (SS.isNotEmpty())
1099 return buildNestedType(*this, SS, T, NameLoc);
1100 return ParsedType::make(T);
1103 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1106 if (ObjCCompatibleAliasDecl *Alias =
1107 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1108 Class = Alias->getClassInterface();
1112 DiagnoseUseOfDecl(Class, NameLoc);
1114 if (NextToken.is(tok::period)) {
1115 // Interface. <something> is parsed as a property reference expression.
1116 // Just return "unknown" as a fall-through for now.
1117 Result.suppressDiagnostics();
1118 return NameClassification::Unknown();
1121 QualType T = Context.getObjCInterfaceType(Class);
1122 return ParsedType::make(T);
1125 // We can have a type template here if we're classifying a template argument.
1126 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1127 !isa<VarTemplateDecl>(FirstDecl))
1128 return NameClassification::TypeTemplate(
1129 TemplateName(cast<TemplateDecl>(FirstDecl)));
1131 // Check for a tag type hidden by a non-type decl in a few cases where it
1132 // seems likely a type is wanted instead of the non-type that was found.
1133 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1134 if ((NextToken.is(tok::identifier) ||
1136 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1137 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1138 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1139 DiagnoseUseOfDecl(Type, NameLoc);
1140 QualType T = Context.getTypeDeclType(Type);
1141 if (SS.isNotEmpty())
1142 return buildNestedType(*this, SS, T, NameLoc);
1143 return ParsedType::make(T);
1146 if (FirstDecl->isCXXClassMember())
1147 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1150 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1151 return BuildDeclarationNameExpr(SS, Result, ADL);
1154 Sema::TemplateNameKindForDiagnostics
1155 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1156 auto *TD = Name.getAsTemplateDecl();
1158 return TemplateNameKindForDiagnostics::DependentTemplate;
1159 if (isa<ClassTemplateDecl>(TD))
1160 return TemplateNameKindForDiagnostics::ClassTemplate;
1161 if (isa<FunctionTemplateDecl>(TD))
1162 return TemplateNameKindForDiagnostics::FunctionTemplate;
1163 if (isa<VarTemplateDecl>(TD))
1164 return TemplateNameKindForDiagnostics::VarTemplate;
1165 if (isa<TypeAliasTemplateDecl>(TD))
1166 return TemplateNameKindForDiagnostics::AliasTemplate;
1167 if (isa<TemplateTemplateParmDecl>(TD))
1168 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1169 return TemplateNameKindForDiagnostics::DependentTemplate;
1172 // Determines the context to return to after temporarily entering a
1173 // context. This depends in an unnecessarily complicated way on the
1174 // exact ordering of callbacks from the parser.
1175 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1177 // Functions defined inline within classes aren't parsed until we've
1178 // finished parsing the top-level class, so the top-level class is
1179 // the context we'll need to return to.
1180 // A Lambda call operator whose parent is a class must not be treated
1181 // as an inline member function. A Lambda can be used legally
1182 // either as an in-class member initializer or a default argument. These
1183 // are parsed once the class has been marked complete and so the containing
1184 // context would be the nested class (when the lambda is defined in one);
1185 // If the class is not complete, then the lambda is being used in an
1186 // ill-formed fashion (such as to specify the width of a bit-field, or
1187 // in an array-bound) - in which case we still want to return the
1188 // lexically containing DC (which could be a nested class).
1189 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1190 DC = DC->getLexicalParent();
1192 // A function not defined within a class will always return to its
1194 if (!isa<CXXRecordDecl>(DC))
1197 // A C++ inline method/friend is parsed *after* the topmost class
1198 // it was declared in is fully parsed ("complete"); the topmost
1199 // class is the context we need to return to.
1200 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1203 // Return the declaration context of the topmost class the inline method is
1208 return DC->getLexicalParent();
1211 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1212 assert(getContainingDC(DC) == CurContext &&
1213 "The next DeclContext should be lexically contained in the current one.");
1218 void Sema::PopDeclContext() {
1219 assert(CurContext && "DeclContext imbalance!");
1221 CurContext = getContainingDC(CurContext);
1222 assert(CurContext && "Popped translation unit!");
1225 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1227 // Unlike PushDeclContext, the context to which we return is not necessarily
1228 // the containing DC of TD, because the new context will be some pre-existing
1229 // TagDecl definition instead of a fresh one.
1230 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1231 CurContext = cast<TagDecl>(D)->getDefinition();
1232 assert(CurContext && "skipping definition of undefined tag");
1233 // Start lookups from the parent of the current context; we don't want to look
1234 // into the pre-existing complete definition.
1235 S->setEntity(CurContext->getLookupParent());
1239 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1240 CurContext = static_cast<decltype(CurContext)>(Context);
1243 /// EnterDeclaratorContext - Used when we must lookup names in the context
1244 /// of a declarator's nested name specifier.
1246 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1247 // C++0x [basic.lookup.unqual]p13:
1248 // A name used in the definition of a static data member of class
1249 // X (after the qualified-id of the static member) is looked up as
1250 // if the name was used in a member function of X.
1251 // C++0x [basic.lookup.unqual]p14:
1252 // If a variable member of a namespace is defined outside of the
1253 // scope of its namespace then any name used in the definition of
1254 // the variable member (after the declarator-id) is looked up as
1255 // if the definition of the variable member occurred in its
1257 // Both of these imply that we should push a scope whose context
1258 // is the semantic context of the declaration. We can't use
1259 // PushDeclContext here because that context is not necessarily
1260 // lexically contained in the current context. Fortunately,
1261 // the containing scope should have the appropriate information.
1263 assert(!S->getEntity() && "scope already has entity");
1266 Scope *Ancestor = S->getParent();
1267 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1268 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1275 void Sema::ExitDeclaratorContext(Scope *S) {
1276 assert(S->getEntity() == CurContext && "Context imbalance!");
1278 // Switch back to the lexical context. The safety of this is
1279 // enforced by an assert in EnterDeclaratorContext.
1280 Scope *Ancestor = S->getParent();
1281 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1282 CurContext = Ancestor->getEntity();
1284 // We don't need to do anything with the scope, which is going to
1288 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1289 // We assume that the caller has already called
1290 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1291 FunctionDecl *FD = D->getAsFunction();
1295 // Same implementation as PushDeclContext, but enters the context
1296 // from the lexical parent, rather than the top-level class.
1297 assert(CurContext == FD->getLexicalParent() &&
1298 "The next DeclContext should be lexically contained in the current one.");
1300 S->setEntity(CurContext);
1302 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1303 ParmVarDecl *Param = FD->getParamDecl(P);
1304 // If the parameter has an identifier, then add it to the scope
1305 if (Param->getIdentifier()) {
1307 IdResolver.AddDecl(Param);
1312 void Sema::ActOnExitFunctionContext() {
1313 // Same implementation as PopDeclContext, but returns to the lexical parent,
1314 // rather than the top-level class.
1315 assert(CurContext && "DeclContext imbalance!");
1316 CurContext = CurContext->getLexicalParent();
1317 assert(CurContext && "Popped translation unit!");
1320 /// \brief Determine whether we allow overloading of the function
1321 /// PrevDecl with another declaration.
1323 /// This routine determines whether overloading is possible, not
1324 /// whether some new function is actually an overload. It will return
1325 /// true in C++ (where we can always provide overloads) or, as an
1326 /// extension, in C when the previous function is already an
1327 /// overloaded function declaration or has the "overloadable"
1329 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1330 ASTContext &Context,
1331 const FunctionDecl *New) {
1332 if (Context.getLangOpts().CPlusPlus)
1335 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1338 return Previous.getResultKind() == LookupResult::Found &&
1339 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1340 New->hasAttr<OverloadableAttr>());
1343 /// Add this decl to the scope shadowed decl chains.
1344 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1345 // Move up the scope chain until we find the nearest enclosing
1346 // non-transparent context. The declaration will be introduced into this
1348 while (S->getEntity() && S->getEntity()->isTransparentContext())
1351 // Add scoped declarations into their context, so that they can be
1352 // found later. Declarations without a context won't be inserted
1353 // into any context.
1355 CurContext->addDecl(D);
1357 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1358 // are function-local declarations.
1359 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1360 !D->getDeclContext()->getRedeclContext()->Equals(
1361 D->getLexicalDeclContext()->getRedeclContext()) &&
1362 !D->getLexicalDeclContext()->isFunctionOrMethod())
1365 // Template instantiations should also not be pushed into scope.
1366 if (isa<FunctionDecl>(D) &&
1367 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1370 // If this replaces anything in the current scope,
1371 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1372 IEnd = IdResolver.end();
1373 for (; I != IEnd; ++I) {
1374 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376 IdResolver.RemoveDecl(*I);
1378 // Should only need to replace one decl.
1385 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1386 // Implicitly-generated labels may end up getting generated in an order that
1387 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1388 // the label at the appropriate place in the identifier chain.
1389 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1390 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1391 if (IDC == CurContext) {
1392 if (!S->isDeclScope(*I))
1394 } else if (IDC->Encloses(CurContext))
1398 IdResolver.InsertDeclAfter(I, D);
1400 IdResolver.AddDecl(D);
1404 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1405 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1406 TUScope->AddDecl(D);
1409 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1410 bool AllowInlineNamespace) {
1411 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1414 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1415 DeclContext *TargetDC = DC->getPrimaryContext();
1417 if (DeclContext *ScopeDC = S->getEntity())
1418 if (ScopeDC->getPrimaryContext() == TargetDC)
1420 } while ((S = S->getParent()));
1425 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1429 /// Filters out lookup results that don't fall within the given scope
1430 /// as determined by isDeclInScope.
1431 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1432 bool ConsiderLinkage,
1433 bool AllowInlineNamespace) {
1434 LookupResult::Filter F = R.makeFilter();
1435 while (F.hasNext()) {
1436 NamedDecl *D = F.next();
1438 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1441 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1450 static bool isUsingDecl(NamedDecl *D) {
1451 return isa<UsingShadowDecl>(D) ||
1452 isa<UnresolvedUsingTypenameDecl>(D) ||
1453 isa<UnresolvedUsingValueDecl>(D);
1456 /// Removes using shadow declarations from the lookup results.
1457 static void RemoveUsingDecls(LookupResult &R) {
1458 LookupResult::Filter F = R.makeFilter();
1460 if (isUsingDecl(F.next()))
1466 /// \brief Check for this common pattern:
1469 /// S(const S&); // DO NOT IMPLEMENT
1470 /// void operator=(const S&); // DO NOT IMPLEMENT
1473 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1474 // FIXME: Should check for private access too but access is set after we get
1476 if (D->doesThisDeclarationHaveABody())
1479 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1480 return CD->isCopyConstructor();
1481 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1482 return Method->isCopyAssignmentOperator();
1486 // We need this to handle
1489 // void *foo() { return 0; }
1492 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1493 // for example. If 'A', foo will have external linkage. If we have '*A',
1494 // foo will have no linkage. Since we can't know until we get to the end
1495 // of the typedef, this function finds out if D might have non-external linkage.
1496 // Callers should verify at the end of the TU if it D has external linkage or
1498 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1499 const DeclContext *DC = D->getDeclContext();
1500 while (!DC->isTranslationUnit()) {
1501 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1502 if (!RD->hasNameForLinkage())
1505 DC = DC->getParent();
1508 return !D->isExternallyVisible();
1511 // FIXME: This needs to be refactored; some other isInMainFile users want
1513 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1514 if (S.TUKind != TU_Complete)
1516 return S.SourceMgr.isInMainFile(Loc);
1519 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1522 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1525 // Ignore all entities declared within templates, and out-of-line definitions
1526 // of members of class templates.
1527 if (D->getDeclContext()->isDependentContext() ||
1528 D->getLexicalDeclContext()->isDependentContext())
1531 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1532 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1534 // A non-out-of-line declaration of a member specialization was implicitly
1535 // instantiated; it's the out-of-line declaration that we're interested in.
1536 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1537 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1540 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1541 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1544 // 'static inline' functions are defined in headers; don't warn.
1545 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1549 if (FD->doesThisDeclarationHaveABody() &&
1550 Context.DeclMustBeEmitted(FD))
1552 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1553 // Constants and utility variables are defined in headers with internal
1554 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1556 if (!isMainFileLoc(*this, VD->getLocation()))
1559 if (Context.DeclMustBeEmitted(VD))
1562 if (VD->isStaticDataMember() &&
1563 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1565 if (VD->isStaticDataMember() &&
1566 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1567 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1570 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1576 // Only warn for unused decls internal to the translation unit.
1577 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1578 // for inline functions defined in the main source file, for instance.
1579 return mightHaveNonExternalLinkage(D);
1582 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1586 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1587 const FunctionDecl *First = FD->getFirstDecl();
1588 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1589 return; // First should already be in the vector.
1592 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1593 const VarDecl *First = VD->getFirstDecl();
1594 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1595 return; // First should already be in the vector.
1598 if (ShouldWarnIfUnusedFileScopedDecl(D))
1599 UnusedFileScopedDecls.push_back(D);
1602 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1603 if (D->isInvalidDecl())
1606 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1607 D->hasAttr<ObjCPreciseLifetimeAttr>())
1610 if (isa<LabelDecl>(D))
1613 // Except for labels, we only care about unused decls that are local to
1615 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1616 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1617 // For dependent types, the diagnostic is deferred.
1619 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1620 if (!WithinFunction)
1623 if (isa<TypedefNameDecl>(D))
1626 // White-list anything that isn't a local variable.
1627 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1630 // Types of valid local variables should be complete, so this should succeed.
1631 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1633 // White-list anything with an __attribute__((unused)) type.
1634 const auto *Ty = VD->getType().getTypePtr();
1636 // Only look at the outermost level of typedef.
1637 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1638 if (TT->getDecl()->hasAttr<UnusedAttr>())
1642 // If we failed to complete the type for some reason, or if the type is
1643 // dependent, don't diagnose the variable.
1644 if (Ty->isIncompleteType() || Ty->isDependentType())
1647 // Look at the element type to ensure that the warning behaviour is
1648 // consistent for both scalars and arrays.
1649 Ty = Ty->getBaseElementTypeUnsafe();
1651 if (const TagType *TT = Ty->getAs<TagType>()) {
1652 const TagDecl *Tag = TT->getDecl();
1653 if (Tag->hasAttr<UnusedAttr>())
1656 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1657 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1660 if (const Expr *Init = VD->getInit()) {
1661 if (const ExprWithCleanups *Cleanups =
1662 dyn_cast<ExprWithCleanups>(Init))
1663 Init = Cleanups->getSubExpr();
1664 const CXXConstructExpr *Construct =
1665 dyn_cast<CXXConstructExpr>(Init);
1666 if (Construct && !Construct->isElidable()) {
1667 CXXConstructorDecl *CD = Construct->getConstructor();
1668 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1675 // TODO: __attribute__((unused)) templates?
1681 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1683 if (isa<LabelDecl>(D)) {
1684 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1685 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1686 if (AfterColon.isInvalid())
1688 Hint = FixItHint::CreateRemoval(CharSourceRange::
1689 getCharRange(D->getLocStart(), AfterColon));
1693 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1694 if (D->getTypeForDecl()->isDependentType())
1697 for (auto *TmpD : D->decls()) {
1698 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1699 DiagnoseUnusedDecl(T);
1700 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1701 DiagnoseUnusedNestedTypedefs(R);
1705 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1706 /// unless they are marked attr(unused).
1707 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1708 if (!ShouldDiagnoseUnusedDecl(D))
1711 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1712 // typedefs can be referenced later on, so the diagnostics are emitted
1713 // at end-of-translation-unit.
1714 UnusedLocalTypedefNameCandidates.insert(TD);
1719 GenerateFixForUnusedDecl(D, Context, Hint);
1722 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1723 DiagID = diag::warn_unused_exception_param;
1724 else if (isa<LabelDecl>(D))
1725 DiagID = diag::warn_unused_label;
1727 DiagID = diag::warn_unused_variable;
1729 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1732 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1733 // Verify that we have no forward references left. If so, there was a goto
1734 // or address of a label taken, but no definition of it. Label fwd
1735 // definitions are indicated with a null substmt which is also not a resolved
1736 // MS inline assembly label name.
1737 bool Diagnose = false;
1738 if (L->isMSAsmLabel())
1739 Diagnose = !L->isResolvedMSAsmLabel();
1741 Diagnose = L->getStmt() == nullptr;
1743 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1746 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1747 S->mergeNRVOIntoParent();
1749 if (S->decl_empty()) return;
1750 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1751 "Scope shouldn't contain decls!");
1753 for (auto *TmpD : S->decls()) {
1754 assert(TmpD && "This decl didn't get pushed??");
1756 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1757 NamedDecl *D = cast<NamedDecl>(TmpD);
1759 if (!D->getDeclName()) continue;
1761 // Diagnose unused variables in this scope.
1762 if (!S->hasUnrecoverableErrorOccurred()) {
1763 DiagnoseUnusedDecl(D);
1764 if (const auto *RD = dyn_cast<RecordDecl>(D))
1765 DiagnoseUnusedNestedTypedefs(RD);
1768 // If this was a forward reference to a label, verify it was defined.
1769 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1770 CheckPoppedLabel(LD, *this);
1772 // Remove this name from our lexical scope, and warn on it if we haven't
1774 IdResolver.RemoveDecl(D);
1775 auto ShadowI = ShadowingDecls.find(D);
1776 if (ShadowI != ShadowingDecls.end()) {
1777 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1778 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1779 << D << FD << FD->getParent();
1780 Diag(FD->getLocation(), diag::note_previous_declaration);
1782 ShadowingDecls.erase(ShadowI);
1787 /// \brief Look for an Objective-C class in the translation unit.
1789 /// \param Id The name of the Objective-C class we're looking for. If
1790 /// typo-correction fixes this name, the Id will be updated
1791 /// to the fixed name.
1793 /// \param IdLoc The location of the name in the translation unit.
1795 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1796 /// if there is no class with the given name.
1798 /// \returns The declaration of the named Objective-C class, or NULL if the
1799 /// class could not be found.
1800 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1801 SourceLocation IdLoc,
1802 bool DoTypoCorrection) {
1803 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1804 // creation from this context.
1805 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1807 if (!IDecl && DoTypoCorrection) {
1808 // Perform typo correction at the given location, but only if we
1809 // find an Objective-C class name.
1810 if (TypoCorrection C = CorrectTypo(
1811 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1812 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1813 CTK_ErrorRecovery)) {
1814 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1815 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1816 Id = IDecl->getIdentifier();
1819 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1820 // This routine must always return a class definition, if any.
1821 if (Def && Def->getDefinition())
1822 Def = Def->getDefinition();
1826 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1827 /// from S, where a non-field would be declared. This routine copes
1828 /// with the difference between C and C++ scoping rules in structs and
1829 /// unions. For example, the following code is well-formed in C but
1830 /// ill-formed in C++:
1836 /// void test_S6() {
1841 /// For the declaration of BAR, this routine will return a different
1842 /// scope. The scope S will be the scope of the unnamed enumeration
1843 /// within S6. In C++, this routine will return the scope associated
1844 /// with S6, because the enumeration's scope is a transparent
1845 /// context but structures can contain non-field names. In C, this
1846 /// routine will return the translation unit scope, since the
1847 /// enumeration's scope is a transparent context and structures cannot
1848 /// contain non-field names.
1849 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1850 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1851 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1852 (S->isClassScope() && !getLangOpts().CPlusPlus))
1857 /// \brief Looks up the declaration of "struct objc_super" and
1858 /// saves it for later use in building builtin declaration of
1859 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1860 /// pre-existing declaration exists no action takes place.
1861 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1862 IdentifierInfo *II) {
1863 if (!II->isStr("objc_msgSendSuper"))
1865 ASTContext &Context = ThisSema.Context;
1867 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1868 SourceLocation(), Sema::LookupTagName);
1869 ThisSema.LookupName(Result, S);
1870 if (Result.getResultKind() == LookupResult::Found)
1871 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1872 Context.setObjCSuperType(Context.getTagDeclType(TD));
1875 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1877 case ASTContext::GE_None:
1879 case ASTContext::GE_Missing_stdio:
1881 case ASTContext::GE_Missing_setjmp:
1883 case ASTContext::GE_Missing_ucontext:
1884 return "ucontext.h";
1886 llvm_unreachable("unhandled error kind");
1889 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1890 /// file scope. lazily create a decl for it. ForRedeclaration is true
1891 /// if we're creating this built-in in anticipation of redeclaring the
1893 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1894 Scope *S, bool ForRedeclaration,
1895 SourceLocation Loc) {
1896 LookupPredefedObjCSuperType(*this, S, II);
1898 ASTContext::GetBuiltinTypeError Error;
1899 QualType R = Context.GetBuiltinType(ID, Error);
1901 if (ForRedeclaration)
1902 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1903 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1907 if (!ForRedeclaration &&
1908 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1909 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1910 Diag(Loc, diag::ext_implicit_lib_function_decl)
1911 << Context.BuiltinInfo.getName(ID) << R;
1912 if (Context.BuiltinInfo.getHeaderName(ID) &&
1913 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1914 Diag(Loc, diag::note_include_header_or_declare)
1915 << Context.BuiltinInfo.getHeaderName(ID)
1916 << Context.BuiltinInfo.getName(ID);
1922 DeclContext *Parent = Context.getTranslationUnitDecl();
1923 if (getLangOpts().CPlusPlus) {
1924 LinkageSpecDecl *CLinkageDecl =
1925 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1926 LinkageSpecDecl::lang_c, false);
1927 CLinkageDecl->setImplicit();
1928 Parent->addDecl(CLinkageDecl);
1929 Parent = CLinkageDecl;
1932 FunctionDecl *New = FunctionDecl::Create(Context,
1934 Loc, Loc, II, R, /*TInfo=*/nullptr,
1937 R->isFunctionProtoType());
1940 // Create Decl objects for each parameter, adding them to the
1942 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1943 SmallVector<ParmVarDecl*, 16> Params;
1944 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1946 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1947 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1949 parm->setScopeInfo(0, i);
1950 Params.push_back(parm);
1952 New->setParams(Params);
1955 AddKnownFunctionAttributes(New);
1956 RegisterLocallyScopedExternCDecl(New, S);
1958 // TUScope is the translation-unit scope to insert this function into.
1959 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1960 // relate Scopes to DeclContexts, and probably eliminate CurContext
1961 // entirely, but we're not there yet.
1962 DeclContext *SavedContext = CurContext;
1963 CurContext = Parent;
1964 PushOnScopeChains(New, TUScope);
1965 CurContext = SavedContext;
1969 /// Typedef declarations don't have linkage, but they still denote the same
1970 /// entity if their types are the same.
1971 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1973 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1974 TypedefNameDecl *Decl,
1975 LookupResult &Previous) {
1976 // This is only interesting when modules are enabled.
1977 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1980 // Empty sets are uninteresting.
1981 if (Previous.empty())
1984 LookupResult::Filter Filter = Previous.makeFilter();
1985 while (Filter.hasNext()) {
1986 NamedDecl *Old = Filter.next();
1988 // Non-hidden declarations are never ignored.
1989 if (S.isVisible(Old))
1992 // Declarations of the same entity are not ignored, even if they have
1993 // different linkages.
1994 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1995 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1996 Decl->getUnderlyingType()))
1999 // If both declarations give a tag declaration a typedef name for linkage
2000 // purposes, then they declare the same entity.
2001 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2002 Decl->getAnonDeclWithTypedefName())
2012 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2014 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2015 OldType = OldTypedef->getUnderlyingType();
2017 OldType = Context.getTypeDeclType(Old);
2018 QualType NewType = New->getUnderlyingType();
2020 if (NewType->isVariablyModifiedType()) {
2021 // Must not redefine a typedef with a variably-modified type.
2022 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2023 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2025 if (Old->getLocation().isValid())
2026 notePreviousDefinition(Old, New->getLocation());
2027 New->setInvalidDecl();
2031 if (OldType != NewType &&
2032 !OldType->isDependentType() &&
2033 !NewType->isDependentType() &&
2034 !Context.hasSameType(OldType, NewType)) {
2035 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2036 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2037 << Kind << NewType << OldType;
2038 if (Old->getLocation().isValid())
2039 notePreviousDefinition(Old, New->getLocation());
2040 New->setInvalidDecl();
2046 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2047 /// same name and scope as a previous declaration 'Old'. Figure out
2048 /// how to resolve this situation, merging decls or emitting
2049 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2051 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2052 LookupResult &OldDecls) {
2053 // If the new decl is known invalid already, don't bother doing any
2055 if (New->isInvalidDecl()) return;
2057 // Allow multiple definitions for ObjC built-in typedefs.
2058 // FIXME: Verify the underlying types are equivalent!
2059 if (getLangOpts().ObjC1) {
2060 const IdentifierInfo *TypeID = New->getIdentifier();
2061 switch (TypeID->getLength()) {
2065 if (!TypeID->isStr("id"))
2067 QualType T = New->getUnderlyingType();
2068 if (!T->isPointerType())
2070 if (!T->isVoidPointerType()) {
2071 QualType PT = T->getAs<PointerType>()->getPointeeType();
2072 if (!PT->isStructureType())
2075 Context.setObjCIdRedefinitionType(T);
2076 // Install the built-in type for 'id', ignoring the current definition.
2077 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2081 if (!TypeID->isStr("Class"))
2083 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2084 // Install the built-in type for 'Class', ignoring the current definition.
2085 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2088 if (!TypeID->isStr("SEL"))
2090 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2091 // Install the built-in type for 'SEL', ignoring the current definition.
2092 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2095 // Fall through - the typedef name was not a builtin type.
2098 // Verify the old decl was also a type.
2099 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2101 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2102 << New->getDeclName();
2104 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2105 if (OldD->getLocation().isValid())
2106 notePreviousDefinition(OldD, New->getLocation());
2108 return New->setInvalidDecl();
2111 // If the old declaration is invalid, just give up here.
2112 if (Old->isInvalidDecl())
2113 return New->setInvalidDecl();
2115 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2116 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2117 auto *NewTag = New->getAnonDeclWithTypedefName();
2118 NamedDecl *Hidden = nullptr;
2119 if (OldTag && NewTag &&
2120 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2121 !hasVisibleDefinition(OldTag, &Hidden)) {
2122 // There is a definition of this tag, but it is not visible. Use it
2123 // instead of our tag.
2124 New->setTypeForDecl(OldTD->getTypeForDecl());
2125 if (OldTD->isModed())
2126 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2127 OldTD->getUnderlyingType());
2129 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2131 // Make the old tag definition visible.
2132 makeMergedDefinitionVisible(Hidden);
2134 // If this was an unscoped enumeration, yank all of its enumerators
2135 // out of the scope.
2136 if (isa<EnumDecl>(NewTag)) {
2137 Scope *EnumScope = getNonFieldDeclScope(S);
2138 for (auto *D : NewTag->decls()) {
2139 auto *ED = cast<EnumConstantDecl>(D);
2140 assert(EnumScope->isDeclScope(ED));
2141 EnumScope->RemoveDecl(ED);
2142 IdResolver.RemoveDecl(ED);
2143 ED->getLexicalDeclContext()->removeDecl(ED);
2149 // If the typedef types are not identical, reject them in all languages and
2150 // with any extensions enabled.
2151 if (isIncompatibleTypedef(Old, New))
2154 // The types match. Link up the redeclaration chain and merge attributes if
2155 // the old declaration was a typedef.
2156 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2157 New->setPreviousDecl(Typedef);
2158 mergeDeclAttributes(New, Old);
2161 if (getLangOpts().MicrosoftExt)
2164 if (getLangOpts().CPlusPlus) {
2165 // C++ [dcl.typedef]p2:
2166 // In a given non-class scope, a typedef specifier can be used to
2167 // redefine the name of any type declared in that scope to refer
2168 // to the type to which it already refers.
2169 if (!isa<CXXRecordDecl>(CurContext))
2172 // C++0x [dcl.typedef]p4:
2173 // In a given class scope, a typedef specifier can be used to redefine
2174 // any class-name declared in that scope that is not also a typedef-name
2175 // to refer to the type to which it already refers.
2177 // This wording came in via DR424, which was a correction to the
2178 // wording in DR56, which accidentally banned code like:
2181 // typedef struct A { } A;
2184 // in the C++03 standard. We implement the C++0x semantics, which
2185 // allow the above but disallow
2192 // since that was the intent of DR56.
2193 if (!isa<TypedefNameDecl>(Old))
2196 Diag(New->getLocation(), diag::err_redefinition)
2197 << New->getDeclName();
2198 notePreviousDefinition(Old, New->getLocation());
2199 return New->setInvalidDecl();
2202 // Modules always permit redefinition of typedefs, as does C11.
2203 if (getLangOpts().Modules || getLangOpts().C11)
2206 // If we have a redefinition of a typedef in C, emit a warning. This warning
2207 // is normally mapped to an error, but can be controlled with
2208 // -Wtypedef-redefinition. If either the original or the redefinition is
2209 // in a system header, don't emit this for compatibility with GCC.
2210 if (getDiagnostics().getSuppressSystemWarnings() &&
2211 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2212 (Old->isImplicit() ||
2213 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2214 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2217 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2218 << New->getDeclName();
2219 notePreviousDefinition(Old, New->getLocation());
2222 /// DeclhasAttr - returns true if decl Declaration already has the target
2224 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2225 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2226 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2227 for (const auto *i : D->attrs())
2228 if (i->getKind() == A->getKind()) {
2230 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2234 // FIXME: Don't hardcode this check
2235 if (OA && isa<OwnershipAttr>(i))
2236 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2243 static bool isAttributeTargetADefinition(Decl *D) {
2244 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2245 return VD->isThisDeclarationADefinition();
2246 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2247 return TD->isCompleteDefinition() || TD->isBeingDefined();
2251 /// Merge alignment attributes from \p Old to \p New, taking into account the
2252 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2254 /// \return \c true if any attributes were added to \p New.
2255 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2256 // Look for alignas attributes on Old, and pick out whichever attribute
2257 // specifies the strictest alignment requirement.
2258 AlignedAttr *OldAlignasAttr = nullptr;
2259 AlignedAttr *OldStrictestAlignAttr = nullptr;
2260 unsigned OldAlign = 0;
2261 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2262 // FIXME: We have no way of representing inherited dependent alignments
2264 // template<int A, int B> struct alignas(A) X;
2265 // template<int A, int B> struct alignas(B) X {};
2266 // For now, we just ignore any alignas attributes which are not on the
2267 // definition in such a case.
2268 if (I->isAlignmentDependent())
2274 unsigned Align = I->getAlignment(S.Context);
2275 if (Align > OldAlign) {
2277 OldStrictestAlignAttr = I;
2281 // Look for alignas attributes on New.
2282 AlignedAttr *NewAlignasAttr = nullptr;
2283 unsigned NewAlign = 0;
2284 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2285 if (I->isAlignmentDependent())
2291 unsigned Align = I->getAlignment(S.Context);
2292 if (Align > NewAlign)
2296 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2297 // Both declarations have 'alignas' attributes. We require them to match.
2298 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2299 // fall short. (If two declarations both have alignas, they must both match
2300 // every definition, and so must match each other if there is a definition.)
2302 // If either declaration only contains 'alignas(0)' specifiers, then it
2303 // specifies the natural alignment for the type.
2304 if (OldAlign == 0 || NewAlign == 0) {
2306 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2309 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2312 OldAlign = S.Context.getTypeAlign(Ty);
2314 NewAlign = S.Context.getTypeAlign(Ty);
2317 if (OldAlign != NewAlign) {
2318 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2319 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2320 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2321 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2325 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2326 // C++11 [dcl.align]p6:
2327 // if any declaration of an entity has an alignment-specifier,
2328 // every defining declaration of that entity shall specify an
2329 // equivalent alignment.
2331 // If the definition of an object does not have an alignment
2332 // specifier, any other declaration of that object shall also
2333 // have no alignment specifier.
2334 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2336 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2340 bool AnyAdded = false;
2342 // Ensure we have an attribute representing the strictest alignment.
2343 if (OldAlign > NewAlign) {
2344 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2345 Clone->setInherited(true);
2346 New->addAttr(Clone);
2350 // Ensure we have an alignas attribute if the old declaration had one.
2351 if (OldAlignasAttr && !NewAlignasAttr &&
2352 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2353 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2354 Clone->setInherited(true);
2355 New->addAttr(Clone);
2362 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2363 const InheritableAttr *Attr,
2364 Sema::AvailabilityMergeKind AMK) {
2365 // This function copies an attribute Attr from a previous declaration to the
2366 // new declaration D if the new declaration doesn't itself have that attribute
2367 // yet or if that attribute allows duplicates.
2368 // If you're adding a new attribute that requires logic different from
2369 // "use explicit attribute on decl if present, else use attribute from
2370 // previous decl", for example if the attribute needs to be consistent
2371 // between redeclarations, you need to call a custom merge function here.
2372 InheritableAttr *NewAttr = nullptr;
2373 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2374 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2375 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2376 AA->isImplicit(), AA->getIntroduced(),
2377 AA->getDeprecated(),
2378 AA->getObsoleted(), AA->getUnavailable(),
2379 AA->getMessage(), AA->getStrict(),
2380 AA->getReplacement(), AMK,
2381 AttrSpellingListIndex);
2382 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2383 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2384 AttrSpellingListIndex);
2385 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2386 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2387 AttrSpellingListIndex);
2388 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2389 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2390 AttrSpellingListIndex);
2391 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2392 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2393 AttrSpellingListIndex);
2394 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2395 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2396 FA->getFormatIdx(), FA->getFirstArg(),
2397 AttrSpellingListIndex);
2398 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2399 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2400 AttrSpellingListIndex);
2401 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2402 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2403 AttrSpellingListIndex,
2404 IA->getSemanticSpelling());
2405 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2406 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2407 &S.Context.Idents.get(AA->getSpelling()),
2408 AttrSpellingListIndex);
2409 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2410 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2411 isa<CUDAGlobalAttr>(Attr))) {
2412 // CUDA target attributes are part of function signature for
2413 // overloading purposes and must not be merged.
2415 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2416 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2417 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2418 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2419 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2420 NewAttr = S.mergeInternalLinkageAttr(
2421 D, InternalLinkageA->getRange(),
2422 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2423 AttrSpellingListIndex);
2424 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2425 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2426 &S.Context.Idents.get(CommonA->getSpelling()),
2427 AttrSpellingListIndex);
2428 else if (isa<AlignedAttr>(Attr))
2429 // AlignedAttrs are handled separately, because we need to handle all
2430 // such attributes on a declaration at the same time.
2432 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2433 (AMK == Sema::AMK_Override ||
2434 AMK == Sema::AMK_ProtocolImplementation))
2436 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2437 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2439 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2440 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2443 NewAttr->setInherited(true);
2444 D->addAttr(NewAttr);
2445 if (isa<MSInheritanceAttr>(NewAttr))
2446 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2453 static const NamedDecl *getDefinition(const Decl *D) {
2454 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2455 return TD->getDefinition();
2456 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2457 const VarDecl *Def = VD->getDefinition();
2460 return VD->getActingDefinition();
2462 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2463 return FD->getDefinition();
2467 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2468 for (const auto *Attribute : D->attrs())
2469 if (Attribute->getKind() == Kind)
2474 /// checkNewAttributesAfterDef - If we already have a definition, check that
2475 /// there are no new attributes in this declaration.
2476 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2477 if (!New->hasAttrs())
2480 const NamedDecl *Def = getDefinition(Old);
2481 if (!Def || Def == New)
2484 AttrVec &NewAttributes = New->getAttrs();
2485 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2486 const Attr *NewAttribute = NewAttributes[I];
2488 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2489 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2490 Sema::SkipBodyInfo SkipBody;
2491 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2493 // If we're skipping this definition, drop the "alias" attribute.
2494 if (SkipBody.ShouldSkip) {
2495 NewAttributes.erase(NewAttributes.begin() + I);
2500 VarDecl *VD = cast<VarDecl>(New);
2501 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2502 VarDecl::TentativeDefinition
2503 ? diag::err_alias_after_tentative
2504 : diag::err_redefinition;
2505 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2506 if (Diag == diag::err_redefinition)
2507 S.notePreviousDefinition(Def, VD->getLocation());
2509 S.Diag(Def->getLocation(), diag::note_previous_definition);
2510 VD->setInvalidDecl();
2516 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2517 // Tentative definitions are only interesting for the alias check above.
2518 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2524 if (hasAttribute(Def, NewAttribute->getKind())) {
2526 continue; // regular attr merging will take care of validating this.
2529 if (isa<C11NoReturnAttr>(NewAttribute)) {
2530 // C's _Noreturn is allowed to be added to a function after it is defined.
2533 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2534 if (AA->isAlignas()) {
2535 // C++11 [dcl.align]p6:
2536 // if any declaration of an entity has an alignment-specifier,
2537 // every defining declaration of that entity shall specify an
2538 // equivalent alignment.
2540 // If the definition of an object does not have an alignment
2541 // specifier, any other declaration of that object shall also
2542 // have no alignment specifier.
2543 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2545 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2547 NewAttributes.erase(NewAttributes.begin() + I);
2553 S.Diag(NewAttribute->getLocation(),
2554 diag::warn_attribute_precede_definition);
2555 S.Diag(Def->getLocation(), diag::note_previous_definition);
2556 NewAttributes.erase(NewAttributes.begin() + I);
2561 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2562 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2563 AvailabilityMergeKind AMK) {
2564 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2565 UsedAttr *NewAttr = OldAttr->clone(Context);
2566 NewAttr->setInherited(true);
2567 New->addAttr(NewAttr);
2570 if (!Old->hasAttrs() && !New->hasAttrs())
2573 // Attributes declared post-definition are currently ignored.
2574 checkNewAttributesAfterDef(*this, New, Old);
2576 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2577 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2578 if (OldA->getLabel() != NewA->getLabel()) {
2579 // This redeclaration changes __asm__ label.
2580 Diag(New->getLocation(), diag::err_different_asm_label);
2581 Diag(OldA->getLocation(), diag::note_previous_declaration);
2583 } else if (Old->isUsed()) {
2584 // This redeclaration adds an __asm__ label to a declaration that has
2585 // already been ODR-used.
2586 Diag(New->getLocation(), diag::err_late_asm_label_name)
2587 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2591 // Re-declaration cannot add abi_tag's.
2592 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2593 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2594 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2595 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2596 NewTag) == OldAbiTagAttr->tags_end()) {
2597 Diag(NewAbiTagAttr->getLocation(),
2598 diag::err_new_abi_tag_on_redeclaration)
2600 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2604 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2605 Diag(Old->getLocation(), diag::note_previous_declaration);
2609 if (!Old->hasAttrs())
2612 bool foundAny = New->hasAttrs();
2614 // Ensure that any moving of objects within the allocated map is done before
2616 if (!foundAny) New->setAttrs(AttrVec());
2618 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2619 // Ignore deprecated/unavailable/availability attributes if requested.
2620 AvailabilityMergeKind LocalAMK = AMK_None;
2621 if (isa<DeprecatedAttr>(I) ||
2622 isa<UnavailableAttr>(I) ||
2623 isa<AvailabilityAttr>(I)) {
2628 case AMK_Redeclaration:
2630 case AMK_ProtocolImplementation:
2637 if (isa<UsedAttr>(I))
2640 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2644 if (mergeAlignedAttrs(*this, New, Old))
2647 if (!foundAny) New->dropAttrs();
2650 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2652 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2653 const ParmVarDecl *oldDecl,
2655 // C++11 [dcl.attr.depend]p2:
2656 // The first declaration of a function shall specify the
2657 // carries_dependency attribute for its declarator-id if any declaration
2658 // of the function specifies the carries_dependency attribute.
2659 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2660 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2661 S.Diag(CDA->getLocation(),
2662 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2663 // Find the first declaration of the parameter.
2664 // FIXME: Should we build redeclaration chains for function parameters?
2665 const FunctionDecl *FirstFD =
2666 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2667 const ParmVarDecl *FirstVD =
2668 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2669 S.Diag(FirstVD->getLocation(),
2670 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2673 if (!oldDecl->hasAttrs())
2676 bool foundAny = newDecl->hasAttrs();
2678 // Ensure that any moving of objects within the allocated map is
2679 // done before we process them.
2680 if (!foundAny) newDecl->setAttrs(AttrVec());
2682 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2683 if (!DeclHasAttr(newDecl, I)) {
2684 InheritableAttr *newAttr =
2685 cast<InheritableParamAttr>(I->clone(S.Context));
2686 newAttr->setInherited(true);
2687 newDecl->addAttr(newAttr);
2692 if (!foundAny) newDecl->dropAttrs();
2695 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2696 const ParmVarDecl *OldParam,
2698 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2699 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2700 if (*Oldnullability != *Newnullability) {
2701 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2702 << DiagNullabilityKind(
2704 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2706 << DiagNullabilityKind(
2708 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2710 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2713 QualType NewT = NewParam->getType();
2714 NewT = S.Context.getAttributedType(
2715 AttributedType::getNullabilityAttrKind(*Oldnullability),
2717 NewParam->setType(NewT);
2724 /// Used in MergeFunctionDecl to keep track of function parameters in
2726 struct GNUCompatibleParamWarning {
2727 ParmVarDecl *OldParm;
2728 ParmVarDecl *NewParm;
2729 QualType PromotedType;
2732 } // end anonymous namespace
2734 /// getSpecialMember - get the special member enum for a method.
2735 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2736 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2737 if (Ctor->isDefaultConstructor())
2738 return Sema::CXXDefaultConstructor;
2740 if (Ctor->isCopyConstructor())
2741 return Sema::CXXCopyConstructor;
2743 if (Ctor->isMoveConstructor())
2744 return Sema::CXXMoveConstructor;
2745 } else if (isa<CXXDestructorDecl>(MD)) {
2746 return Sema::CXXDestructor;
2747 } else if (MD->isCopyAssignmentOperator()) {
2748 return Sema::CXXCopyAssignment;
2749 } else if (MD->isMoveAssignmentOperator()) {
2750 return Sema::CXXMoveAssignment;
2753 return Sema::CXXInvalid;
2756 // Determine whether the previous declaration was a definition, implicit
2757 // declaration, or a declaration.
2758 template <typename T>
2759 static std::pair<diag::kind, SourceLocation>
2760 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2761 diag::kind PrevDiag;
2762 SourceLocation OldLocation = Old->getLocation();
2763 if (Old->isThisDeclarationADefinition())
2764 PrevDiag = diag::note_previous_definition;
2765 else if (Old->isImplicit()) {
2766 PrevDiag = diag::note_previous_implicit_declaration;
2767 if (OldLocation.isInvalid())
2768 OldLocation = New->getLocation();
2770 PrevDiag = diag::note_previous_declaration;
2771 return std::make_pair(PrevDiag, OldLocation);
2774 /// canRedefineFunction - checks if a function can be redefined. Currently,
2775 /// only extern inline functions can be redefined, and even then only in
2777 static bool canRedefineFunction(const FunctionDecl *FD,
2778 const LangOptions& LangOpts) {
2779 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2780 !LangOpts.CPlusPlus &&
2781 FD->isInlineSpecified() &&
2782 FD->getStorageClass() == SC_Extern);
2785 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2786 const AttributedType *AT = T->getAs<AttributedType>();
2787 while (AT && !AT->isCallingConv())
2788 AT = AT->getModifiedType()->getAs<AttributedType>();
2792 template <typename T>
2793 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2794 const DeclContext *DC = Old->getDeclContext();
2798 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2799 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2801 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2806 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2807 static bool isExternC(VarTemplateDecl *) { return false; }
2809 /// \brief Check whether a redeclaration of an entity introduced by a
2810 /// using-declaration is valid, given that we know it's not an overload
2811 /// (nor a hidden tag declaration).
2812 template<typename ExpectedDecl>
2813 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2814 ExpectedDecl *New) {
2815 // C++11 [basic.scope.declarative]p4:
2816 // Given a set of declarations in a single declarative region, each of
2817 // which specifies the same unqualified name,
2818 // -- they shall all refer to the same entity, or all refer to functions
2819 // and function templates; or
2820 // -- exactly one declaration shall declare a class name or enumeration
2821 // name that is not a typedef name and the other declarations shall all
2822 // refer to the same variable or enumerator, or all refer to functions
2823 // and function templates; in this case the class name or enumeration
2824 // name is hidden (3.3.10).
2826 // C++11 [namespace.udecl]p14:
2827 // If a function declaration in namespace scope or block scope has the
2828 // same name and the same parameter-type-list as a function introduced
2829 // by a using-declaration, and the declarations do not declare the same
2830 // function, the program is ill-formed.
2832 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2834 !Old->getDeclContext()->getRedeclContext()->Equals(
2835 New->getDeclContext()->getRedeclContext()) &&
2836 !(isExternC(Old) && isExternC(New)))
2840 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2841 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2842 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2848 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2849 const FunctionDecl *B) {
2850 assert(A->getNumParams() == B->getNumParams());
2852 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2853 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2854 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2857 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2860 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2863 /// MergeFunctionDecl - We just parsed a function 'New' from
2864 /// declarator D which has the same name and scope as a previous
2865 /// declaration 'Old'. Figure out how to resolve this situation,
2866 /// merging decls or emitting diagnostics as appropriate.
2868 /// In C++, New and Old must be declarations that are not
2869 /// overloaded. Use IsOverload to determine whether New and Old are
2870 /// overloaded, and to select the Old declaration that New should be
2873 /// Returns true if there was an error, false otherwise.
2874 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2875 Scope *S, bool MergeTypeWithOld) {
2876 // Verify the old decl was also a function.
2877 FunctionDecl *Old = OldD->getAsFunction();
2879 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2880 if (New->getFriendObjectKind()) {
2881 Diag(New->getLocation(), diag::err_using_decl_friend);
2882 Diag(Shadow->getTargetDecl()->getLocation(),
2883 diag::note_using_decl_target);
2884 Diag(Shadow->getUsingDecl()->getLocation(),
2885 diag::note_using_decl) << 0;
2889 // Check whether the two declarations might declare the same function.
2890 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2892 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2894 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2895 << New->getDeclName();
2896 notePreviousDefinition(OldD, New->getLocation());
2901 // If the old declaration is invalid, just give up here.
2902 if (Old->isInvalidDecl())
2905 diag::kind PrevDiag;
2906 SourceLocation OldLocation;
2907 std::tie(PrevDiag, OldLocation) =
2908 getNoteDiagForInvalidRedeclaration(Old, New);
2910 // Don't complain about this if we're in GNU89 mode and the old function
2911 // is an extern inline function.
2912 // Don't complain about specializations. They are not supposed to have
2914 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2915 New->getStorageClass() == SC_Static &&
2916 Old->hasExternalFormalLinkage() &&
2917 !New->getTemplateSpecializationInfo() &&
2918 !canRedefineFunction(Old, getLangOpts())) {
2919 if (getLangOpts().MicrosoftExt) {
2920 Diag(New->getLocation(), diag::ext_static_non_static) << New;
2921 Diag(OldLocation, PrevDiag);
2923 Diag(New->getLocation(), diag::err_static_non_static) << New;
2924 Diag(OldLocation, PrevDiag);
2929 if (New->hasAttr<InternalLinkageAttr>() &&
2930 !Old->hasAttr<InternalLinkageAttr>()) {
2931 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2932 << New->getDeclName();
2933 notePreviousDefinition(Old, New->getLocation());
2934 New->dropAttr<InternalLinkageAttr>();
2937 if (!getLangOpts().CPlusPlus) {
2938 bool OldOvl = Old->hasAttr<OverloadableAttr>();
2939 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
2940 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
2943 // Try our best to find a decl that actually has the overloadable
2944 // attribute for the note. In most cases (e.g. programs with only one
2945 // broken declaration/definition), this won't matter.
2947 // FIXME: We could do this if we juggled some extra state in
2948 // OverloadableAttr, rather than just removing it.
2949 const Decl *DiagOld = Old;
2951 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
2952 const auto *A = D->getAttr<OverloadableAttr>();
2953 return A && !A->isImplicit();
2955 // If we've implicitly added *all* of the overloadable attrs to this
2956 // chain, emitting a "previous redecl" note is pointless.
2957 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
2961 Diag(DiagOld->getLocation(),
2962 diag::note_attribute_overloadable_prev_overload)
2966 New->addAttr(OverloadableAttr::CreateImplicit(Context));
2968 New->dropAttr<OverloadableAttr>();
2972 // If a function is first declared with a calling convention, but is later
2973 // declared or defined without one, all following decls assume the calling
2974 // convention of the first.
2976 // It's OK if a function is first declared without a calling convention,
2977 // but is later declared or defined with the default calling convention.
2979 // To test if either decl has an explicit calling convention, we look for
2980 // AttributedType sugar nodes on the type as written. If they are missing or
2981 // were canonicalized away, we assume the calling convention was implicit.
2983 // Note also that we DO NOT return at this point, because we still have
2984 // other tests to run.
2985 QualType OldQType = Context.getCanonicalType(Old->getType());
2986 QualType NewQType = Context.getCanonicalType(New->getType());
2987 const FunctionType *OldType = cast<FunctionType>(OldQType);
2988 const FunctionType *NewType = cast<FunctionType>(NewQType);
2989 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2990 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2991 bool RequiresAdjustment = false;
2993 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2994 FunctionDecl *First = Old->getFirstDecl();
2995 const FunctionType *FT =
2996 First->getType().getCanonicalType()->castAs<FunctionType>();
2997 FunctionType::ExtInfo FI = FT->getExtInfo();
2998 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2999 if (!NewCCExplicit) {
3000 // Inherit the CC from the previous declaration if it was specified
3001 // there but not here.
3002 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3003 RequiresAdjustment = true;
3005 // Calling conventions aren't compatible, so complain.
3006 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3007 Diag(New->getLocation(), diag::err_cconv_change)
3008 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3010 << (!FirstCCExplicit ? "" :
3011 FunctionType::getNameForCallConv(FI.getCC()));
3013 // Put the note on the first decl, since it is the one that matters.
3014 Diag(First->getLocation(), diag::note_previous_declaration);
3019 // FIXME: diagnose the other way around?
3020 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3021 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3022 RequiresAdjustment = true;
3025 // Merge regparm attribute.
3026 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3027 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3028 if (NewTypeInfo.getHasRegParm()) {
3029 Diag(New->getLocation(), diag::err_regparm_mismatch)
3030 << NewType->getRegParmType()
3031 << OldType->getRegParmType();
3032 Diag(OldLocation, diag::note_previous_declaration);
3036 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3037 RequiresAdjustment = true;
3040 // Merge ns_returns_retained attribute.
3041 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3042 if (NewTypeInfo.getProducesResult()) {
3043 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3044 << "'ns_returns_retained'";
3045 Diag(OldLocation, diag::note_previous_declaration);
3049 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3050 RequiresAdjustment = true;
3053 if (OldTypeInfo.getNoCallerSavedRegs() !=
3054 NewTypeInfo.getNoCallerSavedRegs()) {
3055 if (NewTypeInfo.getNoCallerSavedRegs()) {
3056 AnyX86NoCallerSavedRegistersAttr *Attr =
3057 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3058 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3059 Diag(OldLocation, diag::note_previous_declaration);
3063 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3064 RequiresAdjustment = true;
3067 if (RequiresAdjustment) {
3068 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3069 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3070 New->setType(QualType(AdjustedType, 0));
3071 NewQType = Context.getCanonicalType(New->getType());
3072 NewType = cast<FunctionType>(NewQType);
3075 // If this redeclaration makes the function inline, we may need to add it to
3076 // UndefinedButUsed.
3077 if (!Old->isInlined() && New->isInlined() &&
3078 !New->hasAttr<GNUInlineAttr>() &&
3079 !getLangOpts().GNUInline &&
3080 Old->isUsed(false) &&
3081 !Old->isDefined() && !New->isThisDeclarationADefinition())
3082 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3085 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3087 if (New->hasAttr<GNUInlineAttr>() &&
3088 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3089 UndefinedButUsed.erase(Old->getCanonicalDecl());
3092 // If pass_object_size params don't match up perfectly, this isn't a valid
3094 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3095 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3096 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3097 << New->getDeclName();
3098 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3102 if (getLangOpts().CPlusPlus) {
3103 // C++1z [over.load]p2
3104 // Certain function declarations cannot be overloaded:
3105 // -- Function declarations that differ only in the return type,
3106 // the exception specification, or both cannot be overloaded.
3108 // Check the exception specifications match. This may recompute the type of
3109 // both Old and New if it resolved exception specifications, so grab the
3110 // types again after this. Because this updates the type, we do this before
3111 // any of the other checks below, which may update the "de facto" NewQType
3112 // but do not necessarily update the type of New.
3113 if (CheckEquivalentExceptionSpec(Old, New))
3115 OldQType = Context.getCanonicalType(Old->getType());
3116 NewQType = Context.getCanonicalType(New->getType());
3118 // Go back to the type source info to compare the declared return types,
3119 // per C++1y [dcl.type.auto]p13:
3120 // Redeclarations or specializations of a function or function template
3121 // with a declared return type that uses a placeholder type shall also
3122 // use that placeholder, not a deduced type.
3123 QualType OldDeclaredReturnType =
3124 (Old->getTypeSourceInfo()
3125 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3126 : OldType)->getReturnType();
3127 QualType NewDeclaredReturnType =
3128 (New->getTypeSourceInfo()
3129 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3130 : NewType)->getReturnType();
3131 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3132 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3133 New->isLocalExternDecl())) {
3135 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3136 OldDeclaredReturnType->isObjCObjectPointerType())
3137 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3138 if (ResQT.isNull()) {
3139 if (New->isCXXClassMember() && New->isOutOfLine())
3140 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3141 << New << New->getReturnTypeSourceRange();
3143 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3144 << New->getReturnTypeSourceRange();
3145 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3146 << Old->getReturnTypeSourceRange();
3153 QualType OldReturnType = OldType->getReturnType();
3154 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3155 if (OldReturnType != NewReturnType) {
3156 // If this function has a deduced return type and has already been
3157 // defined, copy the deduced value from the old declaration.
3158 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3159 if (OldAT && OldAT->isDeduced()) {
3161 SubstAutoType(New->getType(),
3162 OldAT->isDependentType() ? Context.DependentTy
3163 : OldAT->getDeducedType()));
3164 NewQType = Context.getCanonicalType(
3165 SubstAutoType(NewQType,
3166 OldAT->isDependentType() ? Context.DependentTy
3167 : OldAT->getDeducedType()));
3171 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3172 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3173 if (OldMethod && NewMethod) {
3174 // Preserve triviality.
3175 NewMethod->setTrivial(OldMethod->isTrivial());
3177 // MSVC allows explicit template specialization at class scope:
3178 // 2 CXXMethodDecls referring to the same function will be injected.
3179 // We don't want a redeclaration error.
3180 bool IsClassScopeExplicitSpecialization =
3181 OldMethod->isFunctionTemplateSpecialization() &&
3182 NewMethod->isFunctionTemplateSpecialization();
3183 bool isFriend = NewMethod->getFriendObjectKind();
3185 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3186 !IsClassScopeExplicitSpecialization) {
3187 // -- Member function declarations with the same name and the
3188 // same parameter types cannot be overloaded if any of them
3189 // is a static member function declaration.
3190 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3191 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3192 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3196 // C++ [class.mem]p1:
3197 // [...] A member shall not be declared twice in the
3198 // member-specification, except that a nested class or member
3199 // class template can be declared and then later defined.
3200 if (!inTemplateInstantiation()) {
3202 if (isa<CXXConstructorDecl>(OldMethod))
3203 NewDiag = diag::err_constructor_redeclared;
3204 else if (isa<CXXDestructorDecl>(NewMethod))
3205 NewDiag = diag::err_destructor_redeclared;
3206 else if (isa<CXXConversionDecl>(NewMethod))
3207 NewDiag = diag::err_conv_function_redeclared;
3209 NewDiag = diag::err_member_redeclared;
3211 Diag(New->getLocation(), NewDiag);
3213 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3214 << New << New->getType();
3216 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3219 // Complain if this is an explicit declaration of a special
3220 // member that was initially declared implicitly.
3222 // As an exception, it's okay to befriend such methods in order
3223 // to permit the implicit constructor/destructor/operator calls.
3224 } else if (OldMethod->isImplicit()) {
3226 NewMethod->setImplicit();
3228 Diag(NewMethod->getLocation(),
3229 diag::err_definition_of_implicitly_declared_member)
3230 << New << getSpecialMember(OldMethod);
3233 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3234 Diag(NewMethod->getLocation(),
3235 diag::err_definition_of_explicitly_defaulted_member)
3236 << getSpecialMember(OldMethod);
3241 // C++11 [dcl.attr.noreturn]p1:
3242 // The first declaration of a function shall specify the noreturn
3243 // attribute if any declaration of that function specifies the noreturn
3245 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3246 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3247 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3248 Diag(Old->getFirstDecl()->getLocation(),
3249 diag::note_noreturn_missing_first_decl);
3252 // C++11 [dcl.attr.depend]p2:
3253 // The first declaration of a function shall specify the
3254 // carries_dependency attribute for its declarator-id if any declaration
3255 // of the function specifies the carries_dependency attribute.
3256 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3257 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3258 Diag(CDA->getLocation(),
3259 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3260 Diag(Old->getFirstDecl()->getLocation(),
3261 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3265 // All declarations for a function shall agree exactly in both the
3266 // return type and the parameter-type-list.
3267 // We also want to respect all the extended bits except noreturn.
3269 // noreturn should now match unless the old type info didn't have it.
3270 QualType OldQTypeForComparison = OldQType;
3271 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3272 auto *OldType = OldQType->castAs<FunctionProtoType>();
3273 const FunctionType *OldTypeForComparison
3274 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3275 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3276 assert(OldQTypeForComparison.isCanonical());
3279 if (haveIncompatibleLanguageLinkages(Old, New)) {
3280 // As a special case, retain the language linkage from previous
3281 // declarations of a friend function as an extension.
3283 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3284 // and is useful because there's otherwise no way to specify language
3285 // linkage within class scope.
3287 // Check cautiously as the friend object kind isn't yet complete.
3288 if (New->getFriendObjectKind() != Decl::FOK_None) {
3289 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3290 Diag(OldLocation, PrevDiag);
3292 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3293 Diag(OldLocation, PrevDiag);
3298 if (OldQTypeForComparison == NewQType)
3299 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3301 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3302 New->isLocalExternDecl()) {
3303 // It's OK if we couldn't merge types for a local function declaraton
3304 // if either the old or new type is dependent. We'll merge the types
3305 // when we instantiate the function.
3309 // Fall through for conflicting redeclarations and redefinitions.
3312 // C: Function types need to be compatible, not identical. This handles
3313 // duplicate function decls like "void f(int); void f(enum X);" properly.
3314 if (!getLangOpts().CPlusPlus &&
3315 Context.typesAreCompatible(OldQType, NewQType)) {
3316 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3317 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3318 const FunctionProtoType *OldProto = nullptr;
3319 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3320 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3321 // The old declaration provided a function prototype, but the
3322 // new declaration does not. Merge in the prototype.
3323 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3324 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3326 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3327 OldProto->getExtProtoInfo());
3328 New->setType(NewQType);
3329 New->setHasInheritedPrototype();
3331 // Synthesize parameters with the same types.
3332 SmallVector<ParmVarDecl*, 16> Params;
3333 for (const auto &ParamType : OldProto->param_types()) {
3334 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3335 SourceLocation(), nullptr,
3336 ParamType, /*TInfo=*/nullptr,
3338 Param->setScopeInfo(0, Params.size());
3339 Param->setImplicit();
3340 Params.push_back(Param);
3343 New->setParams(Params);
3346 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3349 // GNU C permits a K&R definition to follow a prototype declaration
3350 // if the declared types of the parameters in the K&R definition
3351 // match the types in the prototype declaration, even when the
3352 // promoted types of the parameters from the K&R definition differ
3353 // from the types in the prototype. GCC then keeps the types from
3356 // If a variadic prototype is followed by a non-variadic K&R definition,
3357 // the K&R definition becomes variadic. This is sort of an edge case, but
3358 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3360 if (!getLangOpts().CPlusPlus &&
3361 Old->hasPrototype() && !New->hasPrototype() &&
3362 New->getType()->getAs<FunctionProtoType>() &&
3363 Old->getNumParams() == New->getNumParams()) {
3364 SmallVector<QualType, 16> ArgTypes;
3365 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3366 const FunctionProtoType *OldProto
3367 = Old->getType()->getAs<FunctionProtoType>();
3368 const FunctionProtoType *NewProto
3369 = New->getType()->getAs<FunctionProtoType>();
3371 // Determine whether this is the GNU C extension.
3372 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3373 NewProto->getReturnType());
3374 bool LooseCompatible = !MergedReturn.isNull();
3375 for (unsigned Idx = 0, End = Old->getNumParams();
3376 LooseCompatible && Idx != End; ++Idx) {
3377 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3378 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3379 if (Context.typesAreCompatible(OldParm->getType(),
3380 NewProto->getParamType(Idx))) {
3381 ArgTypes.push_back(NewParm->getType());
3382 } else if (Context.typesAreCompatible(OldParm->getType(),
3384 /*CompareUnqualified=*/true)) {
3385 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3386 NewProto->getParamType(Idx) };
3387 Warnings.push_back(Warn);
3388 ArgTypes.push_back(NewParm->getType());
3390 LooseCompatible = false;
3393 if (LooseCompatible) {
3394 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3395 Diag(Warnings[Warn].NewParm->getLocation(),
3396 diag::ext_param_promoted_not_compatible_with_prototype)
3397 << Warnings[Warn].PromotedType
3398 << Warnings[Warn].OldParm->getType();
3399 if (Warnings[Warn].OldParm->getLocation().isValid())
3400 Diag(Warnings[Warn].OldParm->getLocation(),
3401 diag::note_previous_declaration);
3404 if (MergeTypeWithOld)
3405 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3406 OldProto->getExtProtoInfo()));
3407 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3410 // Fall through to diagnose conflicting types.
3413 // A function that has already been declared has been redeclared or
3414 // defined with a different type; show an appropriate diagnostic.
3416 // If the previous declaration was an implicitly-generated builtin
3417 // declaration, then at the very least we should use a specialized note.
3419 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3420 // If it's actually a library-defined builtin function like 'malloc'
3421 // or 'printf', just warn about the incompatible redeclaration.
3422 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3423 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3424 Diag(OldLocation, diag::note_previous_builtin_declaration)
3425 << Old << Old->getType();
3427 // If this is a global redeclaration, just forget hereafter
3428 // about the "builtin-ness" of the function.
3430 // Doing this for local extern declarations is problematic. If
3431 // the builtin declaration remains visible, a second invalid
3432 // local declaration will produce a hard error; if it doesn't
3433 // remain visible, a single bogus local redeclaration (which is
3434 // actually only a warning) could break all the downstream code.
3435 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3436 New->getIdentifier()->revertBuiltin();
3441 PrevDiag = diag::note_previous_builtin_declaration;
3444 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3445 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3449 /// \brief Completes the merge of two function declarations that are
3450 /// known to be compatible.
3452 /// This routine handles the merging of attributes and other
3453 /// properties of function declarations from the old declaration to
3454 /// the new declaration, once we know that New is in fact a
3455 /// redeclaration of Old.
3458 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3459 Scope *S, bool MergeTypeWithOld) {
3460 // Merge the attributes
3461 mergeDeclAttributes(New, Old);
3463 // Merge "pure" flag.
3467 // Merge "used" flag.
3468 if (Old->getMostRecentDecl()->isUsed(false))
3471 // Merge attributes from the parameters. These can mismatch with K&R
3473 if (New->getNumParams() == Old->getNumParams())
3474 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3475 ParmVarDecl *NewParam = New->getParamDecl(i);
3476 ParmVarDecl *OldParam = Old->getParamDecl(i);
3477 mergeParamDeclAttributes(NewParam, OldParam, *this);
3478 mergeParamDeclTypes(NewParam, OldParam, *this);
3481 if (getLangOpts().CPlusPlus)
3482 return MergeCXXFunctionDecl(New, Old, S);
3484 // Merge the function types so the we get the composite types for the return
3485 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3487 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3488 if (!Merged.isNull() && MergeTypeWithOld)
3489 New->setType(Merged);
3494 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3495 ObjCMethodDecl *oldMethod) {
3496 // Merge the attributes, including deprecated/unavailable
3497 AvailabilityMergeKind MergeKind =
3498 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3499 ? AMK_ProtocolImplementation
3500 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3503 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3505 // Merge attributes from the parameters.
3506 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3507 oe = oldMethod->param_end();
3508 for (ObjCMethodDecl::param_iterator
3509 ni = newMethod->param_begin(), ne = newMethod->param_end();
3510 ni != ne && oi != oe; ++ni, ++oi)
3511 mergeParamDeclAttributes(*ni, *oi, *this);
3513 CheckObjCMethodOverride(newMethod, oldMethod);
3516 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3517 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3519 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3520 ? diag::err_redefinition_different_type
3521 : diag::err_redeclaration_different_type)
3522 << New->getDeclName() << New->getType() << Old->getType();
3524 diag::kind PrevDiag;
3525 SourceLocation OldLocation;
3526 std::tie(PrevDiag, OldLocation)
3527 = getNoteDiagForInvalidRedeclaration(Old, New);
3528 S.Diag(OldLocation, PrevDiag);
3529 New->setInvalidDecl();
3532 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3533 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3534 /// emitting diagnostics as appropriate.
3536 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3537 /// to here in AddInitializerToDecl. We can't check them before the initializer
3539 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3540 bool MergeTypeWithOld) {
3541 if (New->isInvalidDecl() || Old->isInvalidDecl())
3545 if (getLangOpts().CPlusPlus) {
3546 if (New->getType()->isUndeducedType()) {
3547 // We don't know what the new type is until the initializer is attached.
3549 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3550 // These could still be something that needs exception specs checked.
3551 return MergeVarDeclExceptionSpecs(New, Old);
3553 // C++ [basic.link]p10:
3554 // [...] the types specified by all declarations referring to a given
3555 // object or function shall be identical, except that declarations for an
3556 // array object can specify array types that differ by the presence or
3557 // absence of a major array bound (8.3.4).
3558 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3559 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3560 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3562 // We are merging a variable declaration New into Old. If it has an array
3563 // bound, and that bound differs from Old's bound, we should diagnose the
3565 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3566 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3567 PrevVD = PrevVD->getPreviousDecl()) {
3568 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3569 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3572 if (!Context.hasSameType(NewArray, PrevVDTy))
3573 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3577 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3578 if (Context.hasSameType(OldArray->getElementType(),
3579 NewArray->getElementType()))
3580 MergedT = New->getType();
3582 // FIXME: Check visibility. New is hidden but has a complete type. If New
3583 // has no array bound, it should not inherit one from Old, if Old is not
3585 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3586 if (Context.hasSameType(OldArray->getElementType(),
3587 NewArray->getElementType()))
3588 MergedT = Old->getType();
3591 else if (New->getType()->isObjCObjectPointerType() &&
3592 Old->getType()->isObjCObjectPointerType()) {
3593 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3598 // All declarations that refer to the same object or function shall have
3600 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3602 if (MergedT.isNull()) {
3603 // It's OK if we couldn't merge types if either type is dependent, for a
3604 // block-scope variable. In other cases (static data members of class
3605 // templates, variable templates, ...), we require the types to be
3607 // FIXME: The C++ standard doesn't say anything about this.
3608 if ((New->getType()->isDependentType() ||
3609 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3610 // If the old type was dependent, we can't merge with it, so the new type
3611 // becomes dependent for now. We'll reproduce the original type when we
3612 // instantiate the TypeSourceInfo for the variable.
3613 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3614 New->setType(Context.DependentTy);
3617 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3620 // Don't actually update the type on the new declaration if the old
3621 // declaration was an extern declaration in a different scope.
3622 if (MergeTypeWithOld)
3623 New->setType(MergedT);
3626 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3627 LookupResult &Previous) {
3629 // For an identifier with internal or external linkage declared
3630 // in a scope in which a prior declaration of that identifier is
3631 // visible, if the prior declaration specifies internal or
3632 // external linkage, the type of the identifier at the later
3633 // declaration becomes the composite type.
3635 // If the variable isn't visible, we do not merge with its type.
3636 if (Previous.isShadowed())
3639 if (S.getLangOpts().CPlusPlus) {
3640 // C++11 [dcl.array]p3:
3641 // If there is a preceding declaration of the entity in the same
3642 // scope in which the bound was specified, an omitted array bound
3643 // is taken to be the same as in that earlier declaration.
3644 return NewVD->isPreviousDeclInSameBlockScope() ||
3645 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3646 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3648 // If the old declaration was function-local, don't merge with its
3649 // type unless we're in the same function.
3650 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3651 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3655 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3656 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3657 /// situation, merging decls or emitting diagnostics as appropriate.
3659 /// Tentative definition rules (C99 6.9.2p2) are checked by
3660 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3661 /// definitions here, since the initializer hasn't been attached.
3663 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3664 // If the new decl is already invalid, don't do any other checking.
3665 if (New->isInvalidDecl())
3668 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3671 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3673 // Verify the old decl was also a variable or variable template.
3674 VarDecl *Old = nullptr;
3675 VarTemplateDecl *OldTemplate = nullptr;
3676 if (Previous.isSingleResult()) {
3678 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3679 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3682 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3683 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3684 return New->setInvalidDecl();
3686 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3689 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3690 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3691 return New->setInvalidDecl();
3695 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3696 << New->getDeclName();
3697 notePreviousDefinition(Previous.getRepresentativeDecl(),
3698 New->getLocation());
3699 return New->setInvalidDecl();
3702 // Ensure the template parameters are compatible.
3704 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3705 OldTemplate->getTemplateParameters(),
3706 /*Complain=*/true, TPL_TemplateMatch))
3707 return New->setInvalidDecl();
3709 // C++ [class.mem]p1:
3710 // A member shall not be declared twice in the member-specification [...]
3712 // Here, we need only consider static data members.
3713 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3714 Diag(New->getLocation(), diag::err_duplicate_member)
3715 << New->getIdentifier();
3716 Diag(Old->getLocation(), diag::note_previous_declaration);
3717 New->setInvalidDecl();
3720 mergeDeclAttributes(New, Old);
3721 // Warn if an already-declared variable is made a weak_import in a subsequent
3723 if (New->hasAttr<WeakImportAttr>() &&
3724 Old->getStorageClass() == SC_None &&
3725 !Old->hasAttr<WeakImportAttr>()) {
3726 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3727 notePreviousDefinition(Old, New->getLocation());
3728 // Remove weak_import attribute on new declaration.
3729 New->dropAttr<WeakImportAttr>();
3732 if (New->hasAttr<InternalLinkageAttr>() &&
3733 !Old->hasAttr<InternalLinkageAttr>()) {
3734 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3735 << New->getDeclName();
3736 notePreviousDefinition(Old, New->getLocation());
3737 New->dropAttr<InternalLinkageAttr>();
3741 VarDecl *MostRecent = Old->getMostRecentDecl();
3742 if (MostRecent != Old) {
3743 MergeVarDeclTypes(New, MostRecent,
3744 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3745 if (New->isInvalidDecl())
3749 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3750 if (New->isInvalidDecl())
3753 diag::kind PrevDiag;
3754 SourceLocation OldLocation;
3755 std::tie(PrevDiag, OldLocation) =
3756 getNoteDiagForInvalidRedeclaration(Old, New);
3758 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3759 if (New->getStorageClass() == SC_Static &&
3760 !New->isStaticDataMember() &&
3761 Old->hasExternalFormalLinkage()) {
3762 if (getLangOpts().MicrosoftExt) {
3763 Diag(New->getLocation(), diag::ext_static_non_static)
3764 << New->getDeclName();
3765 Diag(OldLocation, PrevDiag);
3767 Diag(New->getLocation(), diag::err_static_non_static)
3768 << New->getDeclName();
3769 Diag(OldLocation, PrevDiag);
3770 return New->setInvalidDecl();
3774 // For an identifier declared with the storage-class specifier
3775 // extern in a scope in which a prior declaration of that
3776 // identifier is visible,23) if the prior declaration specifies
3777 // internal or external linkage, the linkage of the identifier at
3778 // the later declaration is the same as the linkage specified at
3779 // the prior declaration. If no prior declaration is visible, or
3780 // if the prior declaration specifies no linkage, then the
3781 // identifier has external linkage.
3782 if (New->hasExternalStorage() && Old->hasLinkage())
3784 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3785 !New->isStaticDataMember() &&
3786 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3787 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3788 Diag(OldLocation, PrevDiag);
3789 return New->setInvalidDecl();
3792 // Check if extern is followed by non-extern and vice-versa.
3793 if (New->hasExternalStorage() &&
3794 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3795 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3796 Diag(OldLocation, PrevDiag);
3797 return New->setInvalidDecl();
3799 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3800 !New->hasExternalStorage()) {
3801 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3802 Diag(OldLocation, PrevDiag);
3803 return New->setInvalidDecl();
3806 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3808 // FIXME: The test for external storage here seems wrong? We still
3809 // need to check for mismatches.
3810 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3811 // Don't complain about out-of-line definitions of static members.
3812 !(Old->getLexicalDeclContext()->isRecord() &&
3813 !New->getLexicalDeclContext()->isRecord())) {
3814 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3815 Diag(OldLocation, PrevDiag);
3816 return New->setInvalidDecl();
3819 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3820 if (VarDecl *Def = Old->getDefinition()) {
3821 // C++1z [dcl.fcn.spec]p4:
3822 // If the definition of a variable appears in a translation unit before
3823 // its first declaration as inline, the program is ill-formed.
3824 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3825 Diag(Def->getLocation(), diag::note_previous_definition);
3829 // If this redeclaration makes the function inline, we may need to add it to
3830 // UndefinedButUsed.
3831 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3832 !Old->getDefinition() && !New->isThisDeclarationADefinition())
3833 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3836 if (New->getTLSKind() != Old->getTLSKind()) {
3837 if (!Old->getTLSKind()) {
3838 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3839 Diag(OldLocation, PrevDiag);
3840 } else if (!New->getTLSKind()) {
3841 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3842 Diag(OldLocation, PrevDiag);
3844 // Do not allow redeclaration to change the variable between requiring
3845 // static and dynamic initialization.
3846 // FIXME: GCC allows this, but uses the TLS keyword on the first
3847 // declaration to determine the kind. Do we need to be compatible here?
3848 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3849 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3850 Diag(OldLocation, PrevDiag);
3854 // C++ doesn't have tentative definitions, so go right ahead and check here.
3855 if (getLangOpts().CPlusPlus &&
3856 New->isThisDeclarationADefinition() == VarDecl::Definition) {
3857 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3858 Old->getCanonicalDecl()->isConstexpr()) {
3859 // This definition won't be a definition any more once it's been merged.
3860 Diag(New->getLocation(),
3861 diag::warn_deprecated_redundant_constexpr_static_def);
3862 } else if (VarDecl *Def = Old->getDefinition()) {
3863 if (checkVarDeclRedefinition(Def, New))
3868 if (haveIncompatibleLanguageLinkages(Old, New)) {
3869 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3870 Diag(OldLocation, PrevDiag);
3871 New->setInvalidDecl();
3875 // Merge "used" flag.
3876 if (Old->getMostRecentDecl()->isUsed(false))
3879 // Keep a chain of previous declarations.
3880 New->setPreviousDecl(Old);
3882 NewTemplate->setPreviousDecl(OldTemplate);
3884 // Inherit access appropriately.
3885 New->setAccess(Old->getAccess());
3887 NewTemplate->setAccess(New->getAccess());
3889 if (Old->isInline())
3890 New->setImplicitlyInline();
3893 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3894 SourceManager &SrcMgr = getSourceManager();
3895 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3896 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3897 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3898 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3899 auto &HSI = PP.getHeaderSearchInfo();
3900 StringRef HdrFilename =
3901 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3903 auto noteFromModuleOrInclude = [&](Module *Mod,
3904 SourceLocation IncLoc) -> bool {
3905 // Redefinition errors with modules are common with non modular mapped
3906 // headers, example: a non-modular header H in module A that also gets
3907 // included directly in a TU. Pointing twice to the same header/definition
3908 // is confusing, try to get better diagnostics when modules is on.
3909 if (IncLoc.isValid()) {
3911 Diag(IncLoc, diag::note_redefinition_modules_same_file)
3912 << HdrFilename.str() << Mod->getFullModuleName();
3913 if (!Mod->DefinitionLoc.isInvalid())
3914 Diag(Mod->DefinitionLoc, diag::note_defined_here)
3915 << Mod->getFullModuleName();
3917 Diag(IncLoc, diag::note_redefinition_include_same_file)
3918 << HdrFilename.str();
3926 // Is it the same file and same offset? Provide more information on why
3927 // this leads to a redefinition error.
3928 bool EmittedDiag = false;
3929 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
3930 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
3931 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
3932 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
3933 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
3935 // If the header has no guards, emit a note suggesting one.
3936 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
3937 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
3943 // Redefinition coming from different files or couldn't do better above.
3944 Diag(Old->getLocation(), diag::note_previous_definition);
3947 /// We've just determined that \p Old and \p New both appear to be definitions
3948 /// of the same variable. Either diagnose or fix the problem.
3949 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3950 if (!hasVisibleDefinition(Old) &&
3951 (New->getFormalLinkage() == InternalLinkage ||
3953 New->getDescribedVarTemplate() ||
3954 New->getNumTemplateParameterLists() ||
3955 New->getDeclContext()->isDependentContext())) {
3956 // The previous definition is hidden, and multiple definitions are
3957 // permitted (in separate TUs). Demote this to a declaration.
3958 New->demoteThisDefinitionToDeclaration();
3960 // Make the canonical definition visible.
3961 if (auto *OldTD = Old->getDescribedVarTemplate())
3962 makeMergedDefinitionVisible(OldTD);
3963 makeMergedDefinitionVisible(Old);
3966 Diag(New->getLocation(), diag::err_redefinition) << New;
3967 notePreviousDefinition(Old, New->getLocation());
3968 New->setInvalidDecl();
3973 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3974 /// no declarator (e.g. "struct foo;") is parsed.
3976 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3977 RecordDecl *&AnonRecord) {
3978 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3982 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3983 // disambiguate entities defined in different scopes.
3984 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3986 // We will pick our mangling number depending on which version of MSVC is being
3988 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3989 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3990 ? S->getMSCurManglingNumber()
3991 : S->getMSLastManglingNumber();
3994 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3995 if (!Context.getLangOpts().CPlusPlus)
3998 if (isa<CXXRecordDecl>(Tag->getParent())) {
3999 // If this tag is the direct child of a class, number it if
4001 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4003 MangleNumberingContext &MCtx =
4004 Context.getManglingNumberContext(Tag->getParent());
4005 Context.setManglingNumber(
4006 Tag, MCtx.getManglingNumber(
4007 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4011 // If this tag isn't a direct child of a class, number it if it is local.
4012 Decl *ManglingContextDecl;
4013 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4014 Tag->getDeclContext(), ManglingContextDecl)) {
4015 Context.setManglingNumber(
4016 Tag, MCtx->getManglingNumber(
4017 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4021 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4022 TypedefNameDecl *NewTD) {
4023 if (TagFromDeclSpec->isInvalidDecl())
4026 // Do nothing if the tag already has a name for linkage purposes.
4027 if (TagFromDeclSpec->hasNameForLinkage())
4030 // A well-formed anonymous tag must always be a TUK_Definition.
4031 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4033 // The type must match the tag exactly; no qualifiers allowed.
4034 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4035 Context.getTagDeclType(TagFromDeclSpec))) {
4036 if (getLangOpts().CPlusPlus)
4037 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4041 // If we've already computed linkage for the anonymous tag, then
4042 // adding a typedef name for the anonymous decl can change that
4043 // linkage, which might be a serious problem. Diagnose this as
4044 // unsupported and ignore the typedef name. TODO: we should
4045 // pursue this as a language defect and establish a formal rule
4046 // for how to handle it.
4047 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4048 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4050 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4051 tagLoc = getLocForEndOfToken(tagLoc);
4053 llvm::SmallString<40> textToInsert;
4054 textToInsert += ' ';
4055 textToInsert += NewTD->getIdentifier()->getName();
4056 Diag(tagLoc, diag::note_typedef_changes_linkage)
4057 << FixItHint::CreateInsertion(tagLoc, textToInsert);
4061 // Otherwise, set this is the anon-decl typedef for the tag.
4062 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4065 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4067 case DeclSpec::TST_class:
4069 case DeclSpec::TST_struct:
4071 case DeclSpec::TST_interface:
4073 case DeclSpec::TST_union:
4075 case DeclSpec::TST_enum:
4078 llvm_unreachable("unexpected type specifier");
4082 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4083 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4084 /// parameters to cope with template friend declarations.
4086 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4087 MultiTemplateParamsArg TemplateParams,
4088 bool IsExplicitInstantiation,
4089 RecordDecl *&AnonRecord) {
4090 Decl *TagD = nullptr;
4091 TagDecl *Tag = nullptr;
4092 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4093 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4094 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4095 DS.getTypeSpecType() == DeclSpec::TST_union ||
4096 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4097 TagD = DS.getRepAsDecl();
4099 if (!TagD) // We probably had an error
4102 // Note that the above type specs guarantee that the
4103 // type rep is a Decl, whereas in many of the others
4105 if (isa<TagDecl>(TagD))
4106 Tag = cast<TagDecl>(TagD);
4107 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4108 Tag = CTD->getTemplatedDecl();
4112 handleTagNumbering(Tag, S);
4113 Tag->setFreeStanding();
4114 if (Tag->isInvalidDecl())
4118 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4119 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4120 // or incomplete types shall not be restrict-qualified."
4121 if (TypeQuals & DeclSpec::TQ_restrict)
4122 Diag(DS.getRestrictSpecLoc(),
4123 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4124 << DS.getSourceRange();
4127 if (DS.isInlineSpecified())
4128 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4129 << getLangOpts().CPlusPlus1z;
4131 if (DS.isConstexprSpecified()) {
4132 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4133 // and definitions of functions and variables.
4135 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4136 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4138 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4139 // Don't emit warnings after this error.
4143 if (DS.isConceptSpecified()) {
4144 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4145 // either a function concept and its definition or a variable concept and
4147 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4151 DiagnoseFunctionSpecifiers(DS);
4153 if (DS.isFriendSpecified()) {
4154 // If we're dealing with a decl but not a TagDecl, assume that
4155 // whatever routines created it handled the friendship aspect.
4158 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4161 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4162 bool IsExplicitSpecialization =
4163 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4164 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4165 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4166 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4167 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4168 // nested-name-specifier unless it is an explicit instantiation
4169 // or an explicit specialization.
4171 // FIXME: We allow class template partial specializations here too, per the
4172 // obvious intent of DR1819.
4174 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4175 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4176 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4180 // Track whether this decl-specifier declares anything.
4181 bool DeclaresAnything = true;
4183 // Handle anonymous struct definitions.
4184 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4185 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4186 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4187 if (getLangOpts().CPlusPlus ||
4188 Record->getDeclContext()->isRecord()) {
4189 // If CurContext is a DeclContext that can contain statements,
4190 // RecursiveASTVisitor won't visit the decls that
4191 // BuildAnonymousStructOrUnion() will put into CurContext.
4192 // Also store them here so that they can be part of the
4193 // DeclStmt that gets created in this case.
4194 // FIXME: Also return the IndirectFieldDecls created by
4195 // BuildAnonymousStructOr union, for the same reason?
4196 if (CurContext->isFunctionOrMethod())
4197 AnonRecord = Record;
4198 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4199 Context.getPrintingPolicy());
4202 DeclaresAnything = false;
4207 // A struct-declaration that does not declare an anonymous structure or
4208 // anonymous union shall contain a struct-declarator-list.
4210 // This rule also existed in C89 and C99; the grammar for struct-declaration
4211 // did not permit a struct-declaration without a struct-declarator-list.
4212 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4213 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4214 // Check for Microsoft C extension: anonymous struct/union member.
4215 // Handle 2 kinds of anonymous struct/union:
4219 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4220 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4221 if ((Tag && Tag->getDeclName()) ||
4222 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4223 RecordDecl *Record = nullptr;
4225 Record = dyn_cast<RecordDecl>(Tag);
4226 else if (const RecordType *RT =
4227 DS.getRepAsType().get()->getAsStructureType())
4228 Record = RT->getDecl();
4229 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4230 Record = UT->getDecl();
4232 if (Record && getLangOpts().MicrosoftExt) {
4233 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4234 << Record->isUnion() << DS.getSourceRange();
4235 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4238 DeclaresAnything = false;
4242 // Skip all the checks below if we have a type error.
4243 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4244 (TagD && TagD->isInvalidDecl()))
4247 if (getLangOpts().CPlusPlus &&
4248 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4249 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4250 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4251 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4252 DeclaresAnything = false;
4254 if (!DS.isMissingDeclaratorOk()) {
4255 // Customize diagnostic for a typedef missing a name.
4256 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4257 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4258 << DS.getSourceRange();
4260 DeclaresAnything = false;
4263 if (DS.isModulePrivateSpecified() &&
4264 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4265 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4266 << Tag->getTagKind()
4267 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4269 ActOnDocumentableDecl(TagD);
4272 // A declaration [...] shall declare at least a declarator [...], a tag,
4273 // or the members of an enumeration.
4275 // [If there are no declarators], and except for the declaration of an
4276 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4277 // names into the program, or shall redeclare a name introduced by a
4278 // previous declaration.
4279 if (!DeclaresAnything) {
4280 // In C, we allow this as a (popular) extension / bug. Don't bother
4281 // producing further diagnostics for redundant qualifiers after this.
4282 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4287 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4288 // init-declarator-list of the declaration shall not be empty.
4289 // C++ [dcl.fct.spec]p1:
4290 // If a cv-qualifier appears in a decl-specifier-seq, the
4291 // init-declarator-list of the declaration shall not be empty.
4293 // Spurious qualifiers here appear to be valid in C.
4294 unsigned DiagID = diag::warn_standalone_specifier;
4295 if (getLangOpts().CPlusPlus)
4296 DiagID = diag::ext_standalone_specifier;
4298 // Note that a linkage-specification sets a storage class, but
4299 // 'extern "C" struct foo;' is actually valid and not theoretically
4301 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4302 if (SCS == DeclSpec::SCS_mutable)
4303 // Since mutable is not a viable storage class specifier in C, there is
4304 // no reason to treat it as an extension. Instead, diagnose as an error.
4305 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4306 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4307 Diag(DS.getStorageClassSpecLoc(), DiagID)
4308 << DeclSpec::getSpecifierName(SCS);
4311 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4312 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4313 << DeclSpec::getSpecifierName(TSCS);
4314 if (DS.getTypeQualifiers()) {
4315 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4316 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4317 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4318 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4319 // Restrict is covered above.
4320 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4321 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4322 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4323 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4326 // Warn about ignored type attributes, for example:
4327 // __attribute__((aligned)) struct A;
4328 // Attributes should be placed after tag to apply to type declaration.
4329 if (!DS.getAttributes().empty()) {
4330 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4331 if (TypeSpecType == DeclSpec::TST_class ||
4332 TypeSpecType == DeclSpec::TST_struct ||
4333 TypeSpecType == DeclSpec::TST_interface ||
4334 TypeSpecType == DeclSpec::TST_union ||
4335 TypeSpecType == DeclSpec::TST_enum) {
4336 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4337 attrs = attrs->getNext())
4338 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4339 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4346 /// We are trying to inject an anonymous member into the given scope;
4347 /// check if there's an existing declaration that can't be overloaded.
4349 /// \return true if this is a forbidden redeclaration
4350 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4353 DeclarationName Name,
4354 SourceLocation NameLoc,
4356 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4357 Sema::ForRedeclaration);
4358 if (!SemaRef.LookupName(R, S)) return false;
4360 // Pick a representative declaration.
4361 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4362 assert(PrevDecl && "Expected a non-null Decl");
4364 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4367 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4369 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4374 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4375 /// anonymous struct or union AnonRecord into the owning context Owner
4376 /// and scope S. This routine will be invoked just after we realize
4377 /// that an unnamed union or struct is actually an anonymous union or
4384 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4385 /// // f into the surrounding scope.x
4388 /// This routine is recursive, injecting the names of nested anonymous
4389 /// structs/unions into the owning context and scope as well.
4391 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4392 RecordDecl *AnonRecord, AccessSpecifier AS,
4393 SmallVectorImpl<NamedDecl *> &Chaining) {
4394 bool Invalid = false;
4396 // Look every FieldDecl and IndirectFieldDecl with a name.
4397 for (auto *D : AnonRecord->decls()) {
4398 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4399 cast<NamedDecl>(D)->getDeclName()) {
4400 ValueDecl *VD = cast<ValueDecl>(D);
4401 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4403 AnonRecord->isUnion())) {
4404 // C++ [class.union]p2:
4405 // The names of the members of an anonymous union shall be
4406 // distinct from the names of any other entity in the
4407 // scope in which the anonymous union is declared.
4410 // C++ [class.union]p2:
4411 // For the purpose of name lookup, after the anonymous union
4412 // definition, the members of the anonymous union are
4413 // considered to have been defined in the scope in which the
4414 // anonymous union is declared.
4415 unsigned OldChainingSize = Chaining.size();
4416 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4417 Chaining.append(IF->chain_begin(), IF->chain_end());
4419 Chaining.push_back(VD);
4421 assert(Chaining.size() >= 2);
4422 NamedDecl **NamedChain =
4423 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4424 for (unsigned i = 0; i < Chaining.size(); i++)
4425 NamedChain[i] = Chaining[i];
4427 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4428 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4429 VD->getType(), {NamedChain, Chaining.size()});
4431 for (const auto *Attr : VD->attrs())
4432 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4434 IndirectField->setAccess(AS);
4435 IndirectField->setImplicit();
4436 SemaRef.PushOnScopeChains(IndirectField, S);
4438 // That includes picking up the appropriate access specifier.
4439 if (AS != AS_none) IndirectField->setAccess(AS);
4441 Chaining.resize(OldChainingSize);
4449 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4450 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4451 /// illegal input values are mapped to SC_None.
4453 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4454 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4455 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4456 "Parser allowed 'typedef' as storage class VarDecl.");
4457 switch (StorageClassSpec) {
4458 case DeclSpec::SCS_unspecified: return SC_None;
4459 case DeclSpec::SCS_extern:
4460 if (DS.isExternInLinkageSpec())
4463 case DeclSpec::SCS_static: return SC_Static;
4464 case DeclSpec::SCS_auto: return SC_Auto;
4465 case DeclSpec::SCS_register: return SC_Register;
4466 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4467 // Illegal SCSs map to None: error reporting is up to the caller.
4468 case DeclSpec::SCS_mutable: // Fall through.
4469 case DeclSpec::SCS_typedef: return SC_None;
4471 llvm_unreachable("unknown storage class specifier");
4474 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4475 assert(Record->hasInClassInitializer());
4477 for (const auto *I : Record->decls()) {
4478 const auto *FD = dyn_cast<FieldDecl>(I);
4479 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4480 FD = IFD->getAnonField();
4481 if (FD && FD->hasInClassInitializer())
4482 return FD->getLocation();
4485 llvm_unreachable("couldn't find in-class initializer");
4488 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4489 SourceLocation DefaultInitLoc) {
4490 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4493 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4494 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4497 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4498 CXXRecordDecl *AnonUnion) {
4499 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4502 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4505 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4506 /// anonymous structure or union. Anonymous unions are a C++ feature
4507 /// (C++ [class.union]) and a C11 feature; anonymous structures
4508 /// are a C11 feature and GNU C++ extension.
4509 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4512 const PrintingPolicy &Policy) {
4513 DeclContext *Owner = Record->getDeclContext();
4515 // Diagnose whether this anonymous struct/union is an extension.
4516 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4517 Diag(Record->getLocation(), diag::ext_anonymous_union);
4518 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4519 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4520 else if (!Record->isUnion() && !getLangOpts().C11)
4521 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4523 // C and C++ require different kinds of checks for anonymous
4525 bool Invalid = false;
4526 if (getLangOpts().CPlusPlus) {
4527 const char *PrevSpec = nullptr;
4529 if (Record->isUnion()) {
4530 // C++ [class.union]p6:
4531 // Anonymous unions declared in a named namespace or in the
4532 // global namespace shall be declared static.
4533 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4534 (isa<TranslationUnitDecl>(Owner) ||
4535 (isa<NamespaceDecl>(Owner) &&
4536 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4537 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4538 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4540 // Recover by adding 'static'.
4541 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4542 PrevSpec, DiagID, Policy);
4544 // C++ [class.union]p6:
4545 // A storage class is not allowed in a declaration of an
4546 // anonymous union in a class scope.
4547 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4548 isa<RecordDecl>(Owner)) {
4549 Diag(DS.getStorageClassSpecLoc(),
4550 diag::err_anonymous_union_with_storage_spec)
4551 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4553 // Recover by removing the storage specifier.
4554 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4556 PrevSpec, DiagID, Context.getPrintingPolicy());
4560 // Ignore const/volatile/restrict qualifiers.
4561 if (DS.getTypeQualifiers()) {
4562 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4563 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4564 << Record->isUnion() << "const"
4565 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4566 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4567 Diag(DS.getVolatileSpecLoc(),
4568 diag::ext_anonymous_struct_union_qualified)
4569 << Record->isUnion() << "volatile"
4570 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4571 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4572 Diag(DS.getRestrictSpecLoc(),
4573 diag::ext_anonymous_struct_union_qualified)
4574 << Record->isUnion() << "restrict"
4575 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4576 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4577 Diag(DS.getAtomicSpecLoc(),
4578 diag::ext_anonymous_struct_union_qualified)
4579 << Record->isUnion() << "_Atomic"
4580 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4581 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4582 Diag(DS.getUnalignedSpecLoc(),
4583 diag::ext_anonymous_struct_union_qualified)
4584 << Record->isUnion() << "__unaligned"
4585 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4587 DS.ClearTypeQualifiers();
4590 // C++ [class.union]p2:
4591 // The member-specification of an anonymous union shall only
4592 // define non-static data members. [Note: nested types and
4593 // functions cannot be declared within an anonymous union. ]
4594 for (auto *Mem : Record->decls()) {
4595 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4596 // C++ [class.union]p3:
4597 // An anonymous union shall not have private or protected
4598 // members (clause 11).
4599 assert(FD->getAccess() != AS_none);
4600 if (FD->getAccess() != AS_public) {
4601 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4602 << Record->isUnion() << (FD->getAccess() == AS_protected);
4606 // C++ [class.union]p1
4607 // An object of a class with a non-trivial constructor, a non-trivial
4608 // copy constructor, a non-trivial destructor, or a non-trivial copy
4609 // assignment operator cannot be a member of a union, nor can an
4610 // array of such objects.
4611 if (CheckNontrivialField(FD))
4613 } else if (Mem->isImplicit()) {
4614 // Any implicit members are fine.
4615 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4616 // This is a type that showed up in an
4617 // elaborated-type-specifier inside the anonymous struct or
4618 // union, but which actually declares a type outside of the
4619 // anonymous struct or union. It's okay.
4620 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4621 if (!MemRecord->isAnonymousStructOrUnion() &&
4622 MemRecord->getDeclName()) {
4623 // Visual C++ allows type definition in anonymous struct or union.
4624 if (getLangOpts().MicrosoftExt)
4625 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4626 << Record->isUnion();
4628 // This is a nested type declaration.
4629 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4630 << Record->isUnion();
4634 // This is an anonymous type definition within another anonymous type.
4635 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4636 // not part of standard C++.
4637 Diag(MemRecord->getLocation(),
4638 diag::ext_anonymous_record_with_anonymous_type)
4639 << Record->isUnion();
4641 } else if (isa<AccessSpecDecl>(Mem)) {
4642 // Any access specifier is fine.
4643 } else if (isa<StaticAssertDecl>(Mem)) {
4644 // In C++1z, static_assert declarations are also fine.
4646 // We have something that isn't a non-static data
4647 // member. Complain about it.
4648 unsigned DK = diag::err_anonymous_record_bad_member;
4649 if (isa<TypeDecl>(Mem))
4650 DK = diag::err_anonymous_record_with_type;
4651 else if (isa<FunctionDecl>(Mem))
4652 DK = diag::err_anonymous_record_with_function;
4653 else if (isa<VarDecl>(Mem))
4654 DK = diag::err_anonymous_record_with_static;
4656 // Visual C++ allows type definition in anonymous struct or union.
4657 if (getLangOpts().MicrosoftExt &&
4658 DK == diag::err_anonymous_record_with_type)
4659 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4660 << Record->isUnion();
4662 Diag(Mem->getLocation(), DK) << Record->isUnion();
4668 // C++11 [class.union]p8 (DR1460):
4669 // At most one variant member of a union may have a
4670 // brace-or-equal-initializer.
4671 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4673 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4674 cast<CXXRecordDecl>(Record));
4677 if (!Record->isUnion() && !Owner->isRecord()) {
4678 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4679 << getLangOpts().CPlusPlus;
4683 // Mock up a declarator.
4684 Declarator Dc(DS, Declarator::MemberContext);
4685 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4686 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4688 // Create a declaration for this anonymous struct/union.
4689 NamedDecl *Anon = nullptr;
4690 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4691 Anon = FieldDecl::Create(Context, OwningClass,
4693 Record->getLocation(),
4694 /*IdentifierInfo=*/nullptr,
4695 Context.getTypeDeclType(Record),
4697 /*BitWidth=*/nullptr, /*Mutable=*/false,
4698 /*InitStyle=*/ICIS_NoInit);
4699 Anon->setAccess(AS);
4700 if (getLangOpts().CPlusPlus)
4701 FieldCollector->Add(cast<FieldDecl>(Anon));
4703 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4704 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4705 if (SCSpec == DeclSpec::SCS_mutable) {
4706 // mutable can only appear on non-static class members, so it's always
4708 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4713 Anon = VarDecl::Create(Context, Owner,
4715 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4716 Context.getTypeDeclType(Record),
4719 // Default-initialize the implicit variable. This initialization will be
4720 // trivial in almost all cases, except if a union member has an in-class
4722 // union { int n = 0; };
4723 ActOnUninitializedDecl(Anon);
4725 Anon->setImplicit();
4727 // Mark this as an anonymous struct/union type.
4728 Record->setAnonymousStructOrUnion(true);
4730 // Add the anonymous struct/union object to the current
4731 // context. We'll be referencing this object when we refer to one of
4733 Owner->addDecl(Anon);
4735 // Inject the members of the anonymous struct/union into the owning
4736 // context and into the identifier resolver chain for name lookup
4738 SmallVector<NamedDecl*, 2> Chain;
4739 Chain.push_back(Anon);
4741 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4744 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4745 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4746 Decl *ManglingContextDecl;
4747 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4748 NewVD->getDeclContext(), ManglingContextDecl)) {
4749 Context.setManglingNumber(
4750 NewVD, MCtx->getManglingNumber(
4751 NewVD, getMSManglingNumber(getLangOpts(), S)));
4752 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4758 Anon->setInvalidDecl();
4763 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4764 /// Microsoft C anonymous structure.
4765 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4768 /// struct A { int a; };
4769 /// struct B { struct A; int b; };
4776 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4777 RecordDecl *Record) {
4778 assert(Record && "expected a record!");
4780 // Mock up a declarator.
4781 Declarator Dc(DS, Declarator::TypeNameContext);
4782 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4783 assert(TInfo && "couldn't build declarator info for anonymous struct");
4785 auto *ParentDecl = cast<RecordDecl>(CurContext);
4786 QualType RecTy = Context.getTypeDeclType(Record);
4788 // Create a declaration for this anonymous struct.
4789 NamedDecl *Anon = FieldDecl::Create(Context,
4793 /*IdentifierInfo=*/nullptr,
4796 /*BitWidth=*/nullptr, /*Mutable=*/false,
4797 /*InitStyle=*/ICIS_NoInit);
4798 Anon->setImplicit();
4800 // Add the anonymous struct object to the current context.
4801 CurContext->addDecl(Anon);
4803 // Inject the members of the anonymous struct into the current
4804 // context and into the identifier resolver chain for name lookup
4806 SmallVector<NamedDecl*, 2> Chain;
4807 Chain.push_back(Anon);
4809 RecordDecl *RecordDef = Record->getDefinition();
4810 if (RequireCompleteType(Anon->getLocation(), RecTy,
4811 diag::err_field_incomplete) ||
4812 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4814 Anon->setInvalidDecl();
4815 ParentDecl->setInvalidDecl();
4821 /// GetNameForDeclarator - Determine the full declaration name for the
4822 /// given Declarator.
4823 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4824 return GetNameFromUnqualifiedId(D.getName());
4827 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4829 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4830 DeclarationNameInfo NameInfo;
4831 NameInfo.setLoc(Name.StartLocation);
4833 switch (Name.getKind()) {
4835 case UnqualifiedId::IK_ImplicitSelfParam:
4836 case UnqualifiedId::IK_Identifier:
4837 NameInfo.setName(Name.Identifier);
4838 NameInfo.setLoc(Name.StartLocation);
4841 case UnqualifiedId::IK_DeductionGuideName: {
4842 // C++ [temp.deduct.guide]p3:
4843 // The simple-template-id shall name a class template specialization.
4844 // The template-name shall be the same identifier as the template-name
4845 // of the simple-template-id.
4846 // These together intend to imply that the template-name shall name a
4848 // FIXME: template<typename T> struct X {};
4849 // template<typename T> using Y = X<T>;
4850 // Y(int) -> Y<int>;
4851 // satisfies these rules but does not name a class template.
4852 TemplateName TN = Name.TemplateName.get().get();
4853 auto *Template = TN.getAsTemplateDecl();
4854 if (!Template || !isa<ClassTemplateDecl>(Template)) {
4855 Diag(Name.StartLocation,
4856 diag::err_deduction_guide_name_not_class_template)
4857 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4859 Diag(Template->getLocation(), diag::note_template_decl_here);
4860 return DeclarationNameInfo();
4864 Context.DeclarationNames.getCXXDeductionGuideName(Template));
4865 NameInfo.setLoc(Name.StartLocation);
4869 case UnqualifiedId::IK_OperatorFunctionId:
4870 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4871 Name.OperatorFunctionId.Operator));
4872 NameInfo.setLoc(Name.StartLocation);
4873 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4874 = Name.OperatorFunctionId.SymbolLocations[0];
4875 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4876 = Name.EndLocation.getRawEncoding();
4879 case UnqualifiedId::IK_LiteralOperatorId:
4880 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4882 NameInfo.setLoc(Name.StartLocation);
4883 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4886 case UnqualifiedId::IK_ConversionFunctionId: {
4887 TypeSourceInfo *TInfo;
4888 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4890 return DeclarationNameInfo();
4891 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4892 Context.getCanonicalType(Ty)));
4893 NameInfo.setLoc(Name.StartLocation);
4894 NameInfo.setNamedTypeInfo(TInfo);
4898 case UnqualifiedId::IK_ConstructorName: {
4899 TypeSourceInfo *TInfo;
4900 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4902 return DeclarationNameInfo();
4903 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4904 Context.getCanonicalType(Ty)));
4905 NameInfo.setLoc(Name.StartLocation);
4906 NameInfo.setNamedTypeInfo(TInfo);
4910 case UnqualifiedId::IK_ConstructorTemplateId: {
4911 // In well-formed code, we can only have a constructor
4912 // template-id that refers to the current context, so go there
4913 // to find the actual type being constructed.
4914 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4915 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4916 return DeclarationNameInfo();
4918 // Determine the type of the class being constructed.
4919 QualType CurClassType = Context.getTypeDeclType(CurClass);
4921 // FIXME: Check two things: that the template-id names the same type as
4922 // CurClassType, and that the template-id does not occur when the name
4925 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4926 Context.getCanonicalType(CurClassType)));
4927 NameInfo.setLoc(Name.StartLocation);
4928 // FIXME: should we retrieve TypeSourceInfo?
4929 NameInfo.setNamedTypeInfo(nullptr);
4933 case UnqualifiedId::IK_DestructorName: {
4934 TypeSourceInfo *TInfo;
4935 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4937 return DeclarationNameInfo();
4938 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4939 Context.getCanonicalType(Ty)));
4940 NameInfo.setLoc(Name.StartLocation);
4941 NameInfo.setNamedTypeInfo(TInfo);
4945 case UnqualifiedId::IK_TemplateId: {
4946 TemplateName TName = Name.TemplateId->Template.get();
4947 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4948 return Context.getNameForTemplate(TName, TNameLoc);
4951 } // switch (Name.getKind())
4953 llvm_unreachable("Unknown name kind");
4956 static QualType getCoreType(QualType Ty) {
4958 if (Ty->isPointerType() || Ty->isReferenceType())
4959 Ty = Ty->getPointeeType();
4960 else if (Ty->isArrayType())
4961 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4963 return Ty.withoutLocalFastQualifiers();
4967 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4968 /// and Definition have "nearly" matching parameters. This heuristic is
4969 /// used to improve diagnostics in the case where an out-of-line function
4970 /// definition doesn't match any declaration within the class or namespace.
4971 /// Also sets Params to the list of indices to the parameters that differ
4972 /// between the declaration and the definition. If hasSimilarParameters
4973 /// returns true and Params is empty, then all of the parameters match.
4974 static bool hasSimilarParameters(ASTContext &Context,
4975 FunctionDecl *Declaration,
4976 FunctionDecl *Definition,
4977 SmallVectorImpl<unsigned> &Params) {
4979 if (Declaration->param_size() != Definition->param_size())
4981 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4982 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4983 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4985 // The parameter types are identical
4986 if (Context.hasSameType(DefParamTy, DeclParamTy))
4989 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4990 QualType DefParamBaseTy = getCoreType(DefParamTy);
4991 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4992 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4994 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4995 (DeclTyName && DeclTyName == DefTyName))
4996 Params.push_back(Idx);
4997 else // The two parameters aren't even close
5004 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5005 /// declarator needs to be rebuilt in the current instantiation.
5006 /// Any bits of declarator which appear before the name are valid for
5007 /// consideration here. That's specifically the type in the decl spec
5008 /// and the base type in any member-pointer chunks.
5009 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5010 DeclarationName Name) {
5011 // The types we specifically need to rebuild are:
5012 // - typenames, typeofs, and decltypes
5013 // - types which will become injected class names
5014 // Of course, we also need to rebuild any type referencing such a
5015 // type. It's safest to just say "dependent", but we call out a
5018 DeclSpec &DS = D.getMutableDeclSpec();
5019 switch (DS.getTypeSpecType()) {
5020 case DeclSpec::TST_typename:
5021 case DeclSpec::TST_typeofType:
5022 case DeclSpec::TST_underlyingType:
5023 case DeclSpec::TST_atomic: {
5024 // Grab the type from the parser.
5025 TypeSourceInfo *TSI = nullptr;
5026 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5027 if (T.isNull() || !T->isDependentType()) break;
5029 // Make sure there's a type source info. This isn't really much
5030 // of a waste; most dependent types should have type source info
5031 // attached already.
5033 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5035 // Rebuild the type in the current instantiation.
5036 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5037 if (!TSI) return true;
5039 // Store the new type back in the decl spec.
5040 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5041 DS.UpdateTypeRep(LocType);
5045 case DeclSpec::TST_decltype:
5046 case DeclSpec::TST_typeofExpr: {
5047 Expr *E = DS.getRepAsExpr();
5048 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5049 if (Result.isInvalid()) return true;
5050 DS.UpdateExprRep(Result.get());
5055 // Nothing to do for these decl specs.
5059 // It doesn't matter what order we do this in.
5060 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5061 DeclaratorChunk &Chunk = D.getTypeObject(I);
5063 // The only type information in the declarator which can come
5064 // before the declaration name is the base type of a member
5066 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5069 // Rebuild the scope specifier in-place.
5070 CXXScopeSpec &SS = Chunk.Mem.Scope();
5071 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5078 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5079 D.setFunctionDefinitionKind(FDK_Declaration);
5080 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5082 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5083 Dcl && Dcl->getDeclContext()->isFileContext())
5084 Dcl->setTopLevelDeclInObjCContainer();
5086 if (getLangOpts().OpenCL)
5087 setCurrentOpenCLExtensionForDecl(Dcl);
5092 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5093 /// If T is the name of a class, then each of the following shall have a
5094 /// name different from T:
5095 /// - every static data member of class T;
5096 /// - every member function of class T
5097 /// - every member of class T that is itself a type;
5098 /// \returns true if the declaration name violates these rules.
5099 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5100 DeclarationNameInfo NameInfo) {
5101 DeclarationName Name = NameInfo.getName();
5103 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5104 while (Record && Record->isAnonymousStructOrUnion())
5105 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5106 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5107 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5114 /// \brief Diagnose a declaration whose declarator-id has the given
5115 /// nested-name-specifier.
5117 /// \param SS The nested-name-specifier of the declarator-id.
5119 /// \param DC The declaration context to which the nested-name-specifier
5122 /// \param Name The name of the entity being declared.
5124 /// \param Loc The location of the name of the entity being declared.
5126 /// \returns true if we cannot safely recover from this error, false otherwise.
5127 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5128 DeclarationName Name,
5129 SourceLocation Loc) {
5130 DeclContext *Cur = CurContext;
5131 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5132 Cur = Cur->getParent();
5134 // If the user provided a superfluous scope specifier that refers back to the
5135 // class in which the entity is already declared, diagnose and ignore it.
5141 // Note, it was once ill-formed to give redundant qualification in all
5142 // contexts, but that rule was removed by DR482.
5143 if (Cur->Equals(DC)) {
5144 if (Cur->isRecord()) {
5145 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5146 : diag::err_member_extra_qualification)
5147 << Name << FixItHint::CreateRemoval(SS.getRange());
5150 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5155 // Check whether the qualifying scope encloses the scope of the original
5157 if (!Cur->Encloses(DC)) {
5158 if (Cur->isRecord())
5159 Diag(Loc, diag::err_member_qualification)
5160 << Name << SS.getRange();
5161 else if (isa<TranslationUnitDecl>(DC))
5162 Diag(Loc, diag::err_invalid_declarator_global_scope)
5163 << Name << SS.getRange();
5164 else if (isa<FunctionDecl>(Cur))
5165 Diag(Loc, diag::err_invalid_declarator_in_function)
5166 << Name << SS.getRange();
5167 else if (isa<BlockDecl>(Cur))
5168 Diag(Loc, diag::err_invalid_declarator_in_block)
5169 << Name << SS.getRange();
5171 Diag(Loc, diag::err_invalid_declarator_scope)
5172 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5177 if (Cur->isRecord()) {
5178 // Cannot qualify members within a class.
5179 Diag(Loc, diag::err_member_qualification)
5180 << Name << SS.getRange();
5183 // C++ constructors and destructors with incorrect scopes can break
5184 // our AST invariants by having the wrong underlying types. If
5185 // that's the case, then drop this declaration entirely.
5186 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5187 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5188 !Context.hasSameType(Name.getCXXNameType(),
5189 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5195 // C++11 [dcl.meaning]p1:
5196 // [...] "The nested-name-specifier of the qualified declarator-id shall
5197 // not begin with a decltype-specifer"
5198 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5199 while (SpecLoc.getPrefix())
5200 SpecLoc = SpecLoc.getPrefix();
5201 if (dyn_cast_or_null<DecltypeType>(
5202 SpecLoc.getNestedNameSpecifier()->getAsType()))
5203 Diag(Loc, diag::err_decltype_in_declarator)
5204 << SpecLoc.getTypeLoc().getSourceRange();
5209 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5210 MultiTemplateParamsArg TemplateParamLists) {
5211 // TODO: consider using NameInfo for diagnostic.
5212 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5213 DeclarationName Name = NameInfo.getName();
5215 // All of these full declarators require an identifier. If it doesn't have
5216 // one, the ParsedFreeStandingDeclSpec action should be used.
5217 if (D.isDecompositionDeclarator()) {
5218 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5220 if (!D.isInvalidType()) // Reject this if we think it is valid.
5221 Diag(D.getDeclSpec().getLocStart(),
5222 diag::err_declarator_need_ident)
5223 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5225 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5228 // The scope passed in may not be a decl scope. Zip up the scope tree until
5229 // we find one that is.
5230 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5231 (S->getFlags() & Scope::TemplateParamScope) != 0)
5234 DeclContext *DC = CurContext;
5235 if (D.getCXXScopeSpec().isInvalid())
5237 else if (D.getCXXScopeSpec().isSet()) {
5238 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5239 UPPC_DeclarationQualifier))
5242 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5243 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5244 if (!DC || isa<EnumDecl>(DC)) {
5245 // If we could not compute the declaration context, it's because the
5246 // declaration context is dependent but does not refer to a class,
5247 // class template, or class template partial specialization. Complain
5248 // and return early, to avoid the coming semantic disaster.
5249 Diag(D.getIdentifierLoc(),
5250 diag::err_template_qualified_declarator_no_match)
5251 << D.getCXXScopeSpec().getScopeRep()
5252 << D.getCXXScopeSpec().getRange();
5255 bool IsDependentContext = DC->isDependentContext();
5257 if (!IsDependentContext &&
5258 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5261 // If a class is incomplete, do not parse entities inside it.
5262 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5263 Diag(D.getIdentifierLoc(),
5264 diag::err_member_def_undefined_record)
5265 << Name << DC << D.getCXXScopeSpec().getRange();
5268 if (!D.getDeclSpec().isFriendSpecified()) {
5269 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5270 Name, D.getIdentifierLoc())) {
5278 // Check whether we need to rebuild the type of the given
5279 // declaration in the current instantiation.
5280 if (EnteringContext && IsDependentContext &&
5281 TemplateParamLists.size() != 0) {
5282 ContextRAII SavedContext(*this, DC);
5283 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5288 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5289 QualType R = TInfo->getType();
5291 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5292 // If this is a typedef, we'll end up spewing multiple diagnostics.
5293 // Just return early; it's safer. If this is a function, let the
5294 // "constructor cannot have a return type" diagnostic handle it.
5295 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5298 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5299 UPPC_DeclarationType))
5302 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5305 // See if this is a redefinition of a variable in the same scope.
5306 if (!D.getCXXScopeSpec().isSet()) {
5307 bool IsLinkageLookup = false;
5308 bool CreateBuiltins = false;
5310 // If the declaration we're planning to build will be a function
5311 // or object with linkage, then look for another declaration with
5312 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5314 // If the declaration we're planning to build will be declared with
5315 // external linkage in the translation unit, create any builtin with
5317 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5319 else if (CurContext->isFunctionOrMethod() &&
5320 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5321 R->isFunctionType())) {
5322 IsLinkageLookup = true;
5324 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5325 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5326 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5327 CreateBuiltins = true;
5329 if (IsLinkageLookup)
5330 Previous.clear(LookupRedeclarationWithLinkage);
5332 LookupName(Previous, S, CreateBuiltins);
5333 } else { // Something like "int foo::x;"
5334 LookupQualifiedName(Previous, DC);
5336 // C++ [dcl.meaning]p1:
5337 // When the declarator-id is qualified, the declaration shall refer to a
5338 // previously declared member of the class or namespace to which the
5339 // qualifier refers (or, in the case of a namespace, of an element of the
5340 // inline namespace set of that namespace (7.3.1)) or to a specialization
5343 // Note that we already checked the context above, and that we do not have
5344 // enough information to make sure that Previous contains the declaration
5345 // we want to match. For example, given:
5352 // void X::f(int) { } // ill-formed
5354 // In this case, Previous will point to the overload set
5355 // containing the two f's declared in X, but neither of them
5358 // C++ [dcl.meaning]p1:
5359 // [...] the member shall not merely have been introduced by a
5360 // using-declaration in the scope of the class or namespace nominated by
5361 // the nested-name-specifier of the declarator-id.
5362 RemoveUsingDecls(Previous);
5365 if (Previous.isSingleResult() &&
5366 Previous.getFoundDecl()->isTemplateParameter()) {
5367 // Maybe we will complain about the shadowed template parameter.
5368 if (!D.isInvalidType())
5369 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5370 Previous.getFoundDecl());
5372 // Just pretend that we didn't see the previous declaration.
5376 // In C++, the previous declaration we find might be a tag type
5377 // (class or enum). In this case, the new declaration will hide the
5378 // tag type. Note that this does does not apply if we're declaring a
5379 // typedef (C++ [dcl.typedef]p4).
5380 if (Previous.isSingleTagDecl() &&
5381 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5384 // Check that there are no default arguments other than in the parameters
5385 // of a function declaration (C++ only).
5386 if (getLangOpts().CPlusPlus)
5387 CheckExtraCXXDefaultArguments(D);
5389 if (D.getDeclSpec().isConceptSpecified()) {
5390 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5391 // applied only to the definition of a function template or variable
5392 // template, declared in namespace scope
5393 if (!TemplateParamLists.size()) {
5394 Diag(D.getDeclSpec().getConceptSpecLoc(),
5395 diag:: err_concept_wrong_decl_kind);
5399 if (!DC->getRedeclContext()->isFileContext()) {
5400 Diag(D.getIdentifierLoc(),
5401 diag::err_concept_decls_may_only_appear_in_namespace_scope);
5408 bool AddToScope = true;
5409 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5410 if (TemplateParamLists.size()) {
5411 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5415 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5416 } else if (R->isFunctionType()) {
5417 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5421 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5428 // If this has an identifier and is not a function template specialization,
5429 // add it to the scope stack.
5430 if (New->getDeclName() && AddToScope) {
5431 // Only make a locally-scoped extern declaration visible if it is the first
5432 // declaration of this entity. Qualified lookup for such an entity should
5433 // only find this declaration if there is no visible declaration of it.
5434 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5435 PushOnScopeChains(New, S, AddToContext);
5437 CurContext->addHiddenDecl(New);
5440 if (isInOpenMPDeclareTargetContext())
5441 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5446 /// Helper method to turn variable array types into constant array
5447 /// types in certain situations which would otherwise be errors (for
5448 /// GCC compatibility).
5449 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5450 ASTContext &Context,
5451 bool &SizeIsNegative,
5452 llvm::APSInt &Oversized) {
5453 // This method tries to turn a variable array into a constant
5454 // array even when the size isn't an ICE. This is necessary
5455 // for compatibility with code that depends on gcc's buggy
5456 // constant expression folding, like struct {char x[(int)(char*)2];}
5457 SizeIsNegative = false;
5460 if (T->isDependentType())
5463 QualifierCollector Qs;
5464 const Type *Ty = Qs.strip(T);
5466 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5467 QualType Pointee = PTy->getPointeeType();
5468 QualType FixedType =
5469 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5471 if (FixedType.isNull()) return FixedType;
5472 FixedType = Context.getPointerType(FixedType);
5473 return Qs.apply(Context, FixedType);
5475 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5476 QualType Inner = PTy->getInnerType();
5477 QualType FixedType =
5478 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5480 if (FixedType.isNull()) return FixedType;
5481 FixedType = Context.getParenType(FixedType);
5482 return Qs.apply(Context, FixedType);
5485 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5488 // FIXME: We should probably handle this case
5489 if (VLATy->getElementType()->isVariablyModifiedType())
5493 if (!VLATy->getSizeExpr() ||
5494 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5497 // Check whether the array size is negative.
5498 if (Res.isSigned() && Res.isNegative()) {
5499 SizeIsNegative = true;
5503 // Check whether the array is too large to be addressed.
5504 unsigned ActiveSizeBits
5505 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5507 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5512 return Context.getConstantArrayType(VLATy->getElementType(),
5513 Res, ArrayType::Normal, 0);
5517 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5518 SrcTL = SrcTL.getUnqualifiedLoc();
5519 DstTL = DstTL.getUnqualifiedLoc();
5520 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5521 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5522 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5523 DstPTL.getPointeeLoc());
5524 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5527 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5528 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5529 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5530 DstPTL.getInnerLoc());
5531 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5532 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5535 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5536 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5537 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5538 TypeLoc DstElemTL = DstATL.getElementLoc();
5539 DstElemTL.initializeFullCopy(SrcElemTL);
5540 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5541 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5542 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5545 /// Helper method to turn variable array types into constant array
5546 /// types in certain situations which would otherwise be errors (for
5547 /// GCC compatibility).
5548 static TypeSourceInfo*
5549 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5550 ASTContext &Context,
5551 bool &SizeIsNegative,
5552 llvm::APSInt &Oversized) {
5554 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5555 SizeIsNegative, Oversized);
5556 if (FixedTy.isNull())
5558 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5559 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5560 FixedTInfo->getTypeLoc());
5564 /// \brief Register the given locally-scoped extern "C" declaration so
5565 /// that it can be found later for redeclarations. We include any extern "C"
5566 /// declaration that is not visible in the translation unit here, not just
5567 /// function-scope declarations.
5569 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5570 if (!getLangOpts().CPlusPlus &&
5571 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5572 // Don't need to track declarations in the TU in C.
5575 // Note that we have a locally-scoped external with this name.
5576 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5579 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5580 // FIXME: We can have multiple results via __attribute__((overloadable)).
5581 auto Result = Context.getExternCContextDecl()->lookup(Name);
5582 return Result.empty() ? nullptr : *Result.begin();
5585 /// \brief Diagnose function specifiers on a declaration of an identifier that
5586 /// does not identify a function.
5587 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5588 // FIXME: We should probably indicate the identifier in question to avoid
5589 // confusion for constructs like "virtual int a(), b;"
5590 if (DS.isVirtualSpecified())
5591 Diag(DS.getVirtualSpecLoc(),
5592 diag::err_virtual_non_function);
5594 if (DS.isExplicitSpecified())
5595 Diag(DS.getExplicitSpecLoc(),
5596 diag::err_explicit_non_function);
5598 if (DS.isNoreturnSpecified())
5599 Diag(DS.getNoreturnSpecLoc(),
5600 diag::err_noreturn_non_function);
5604 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5605 TypeSourceInfo *TInfo, LookupResult &Previous) {
5606 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5607 if (D.getCXXScopeSpec().isSet()) {
5608 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5609 << D.getCXXScopeSpec().getRange();
5611 // Pretend we didn't see the scope specifier.
5616 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5618 if (D.getDeclSpec().isInlineSpecified())
5619 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5620 << getLangOpts().CPlusPlus1z;
5621 if (D.getDeclSpec().isConstexprSpecified())
5622 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5624 if (D.getDeclSpec().isConceptSpecified())
5625 Diag(D.getDeclSpec().getConceptSpecLoc(),
5626 diag::err_concept_wrong_decl_kind);
5628 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5629 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5630 Diag(D.getName().StartLocation,
5631 diag::err_deduction_guide_invalid_specifier)
5634 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5635 << D.getName().getSourceRange();
5639 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5640 if (!NewTD) return nullptr;
5642 // Handle attributes prior to checking for duplicates in MergeVarDecl
5643 ProcessDeclAttributes(S, NewTD, D);
5645 CheckTypedefForVariablyModifiedType(S, NewTD);
5647 bool Redeclaration = D.isRedeclaration();
5648 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5649 D.setRedeclaration(Redeclaration);
5654 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5655 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5656 // then it shall have block scope.
5657 // Note that variably modified types must be fixed before merging the decl so
5658 // that redeclarations will match.
5659 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5660 QualType T = TInfo->getType();
5661 if (T->isVariablyModifiedType()) {
5662 getCurFunction()->setHasBranchProtectedScope();
5664 if (S->getFnParent() == nullptr) {
5665 bool SizeIsNegative;
5666 llvm::APSInt Oversized;
5667 TypeSourceInfo *FixedTInfo =
5668 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5672 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5673 NewTD->setTypeSourceInfo(FixedTInfo);
5676 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5677 else if (T->isVariableArrayType())
5678 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5679 else if (Oversized.getBoolValue())
5680 Diag(NewTD->getLocation(), diag::err_array_too_large)
5681 << Oversized.toString(10);
5683 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5684 NewTD->setInvalidDecl();
5690 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5691 /// declares a typedef-name, either using the 'typedef' type specifier or via
5692 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5694 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5695 LookupResult &Previous, bool &Redeclaration) {
5697 // Find the shadowed declaration before filtering for scope.
5698 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5700 // Merge the decl with the existing one if appropriate. If the decl is
5701 // in an outer scope, it isn't the same thing.
5702 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5703 /*AllowInlineNamespace*/false);
5704 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5705 if (!Previous.empty()) {
5706 Redeclaration = true;
5707 MergeTypedefNameDecl(S, NewTD, Previous);
5710 if (ShadowedDecl && !Redeclaration)
5711 CheckShadow(NewTD, ShadowedDecl, Previous);
5713 // If this is the C FILE type, notify the AST context.
5714 if (IdentifierInfo *II = NewTD->getIdentifier())
5715 if (!NewTD->isInvalidDecl() &&
5716 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5717 if (II->isStr("FILE"))
5718 Context.setFILEDecl(NewTD);
5719 else if (II->isStr("jmp_buf"))
5720 Context.setjmp_bufDecl(NewTD);
5721 else if (II->isStr("sigjmp_buf"))
5722 Context.setsigjmp_bufDecl(NewTD);
5723 else if (II->isStr("ucontext_t"))
5724 Context.setucontext_tDecl(NewTD);
5730 /// \brief Determines whether the given declaration is an out-of-scope
5731 /// previous declaration.
5733 /// This routine should be invoked when name lookup has found a
5734 /// previous declaration (PrevDecl) that is not in the scope where a
5735 /// new declaration by the same name is being introduced. If the new
5736 /// declaration occurs in a local scope, previous declarations with
5737 /// linkage may still be considered previous declarations (C99
5738 /// 6.2.2p4-5, C++ [basic.link]p6).
5740 /// \param PrevDecl the previous declaration found by name
5743 /// \param DC the context in which the new declaration is being
5746 /// \returns true if PrevDecl is an out-of-scope previous declaration
5747 /// for a new delcaration with the same name.
5749 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5750 ASTContext &Context) {
5754 if (!PrevDecl->hasLinkage())
5757 if (Context.getLangOpts().CPlusPlus) {
5758 // C++ [basic.link]p6:
5759 // If there is a visible declaration of an entity with linkage
5760 // having the same name and type, ignoring entities declared
5761 // outside the innermost enclosing namespace scope, the block
5762 // scope declaration declares that same entity and receives the
5763 // linkage of the previous declaration.
5764 DeclContext *OuterContext = DC->getRedeclContext();
5765 if (!OuterContext->isFunctionOrMethod())
5766 // This rule only applies to block-scope declarations.
5769 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5770 if (PrevOuterContext->isRecord())
5771 // We found a member function: ignore it.
5774 // Find the innermost enclosing namespace for the new and
5775 // previous declarations.
5776 OuterContext = OuterContext->getEnclosingNamespaceContext();
5777 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5779 // The previous declaration is in a different namespace, so it
5780 // isn't the same function.
5781 if (!OuterContext->Equals(PrevOuterContext))
5788 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5789 CXXScopeSpec &SS = D.getCXXScopeSpec();
5790 if (!SS.isSet()) return;
5791 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5794 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5795 QualType type = decl->getType();
5796 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5797 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5798 // Various kinds of declaration aren't allowed to be __autoreleasing.
5799 unsigned kind = -1U;
5800 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5801 if (var->hasAttr<BlocksAttr>())
5802 kind = 0; // __block
5803 else if (!var->hasLocalStorage())
5805 } else if (isa<ObjCIvarDecl>(decl)) {
5807 } else if (isa<FieldDecl>(decl)) {
5812 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5815 } else if (lifetime == Qualifiers::OCL_None) {
5816 // Try to infer lifetime.
5817 if (!type->isObjCLifetimeType())
5820 lifetime = type->getObjCARCImplicitLifetime();
5821 type = Context.getLifetimeQualifiedType(type, lifetime);
5822 decl->setType(type);
5825 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5826 // Thread-local variables cannot have lifetime.
5827 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5828 var->getTLSKind()) {
5829 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5838 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5839 // Ensure that an auto decl is deduced otherwise the checks below might cache
5840 // the wrong linkage.
5841 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5843 // 'weak' only applies to declarations with external linkage.
5844 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5845 if (!ND.isExternallyVisible()) {
5846 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5847 ND.dropAttr<WeakAttr>();
5850 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5851 if (ND.isExternallyVisible()) {
5852 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5853 ND.dropAttr<WeakRefAttr>();
5854 ND.dropAttr<AliasAttr>();
5858 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5859 if (VD->hasInit()) {
5860 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5861 assert(VD->isThisDeclarationADefinition() &&
5862 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5863 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5864 VD->dropAttr<AliasAttr>();
5869 // 'selectany' only applies to externally visible variable declarations.
5870 // It does not apply to functions.
5871 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5872 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5873 S.Diag(Attr->getLocation(),
5874 diag::err_attribute_selectany_non_extern_data);
5875 ND.dropAttr<SelectAnyAttr>();
5879 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5880 // dll attributes require external linkage. Static locals may have external
5881 // linkage but still cannot be explicitly imported or exported.
5882 auto *VD = dyn_cast<VarDecl>(&ND);
5883 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5884 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5886 ND.setInvalidDecl();
5890 // Virtual functions cannot be marked as 'notail'.
5891 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5892 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5893 if (MD->isVirtual()) {
5894 S.Diag(ND.getLocation(),
5895 diag::err_invalid_attribute_on_virtual_function)
5897 ND.dropAttr<NotTailCalledAttr>();
5901 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5903 bool IsSpecialization,
5904 bool IsDefinition) {
5905 if (OldDecl->isInvalidDecl())
5908 bool IsTemplate = false;
5909 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5910 OldDecl = OldTD->getTemplatedDecl();
5912 if (!IsSpecialization)
5913 IsDefinition = false;
5915 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5916 NewDecl = NewTD->getTemplatedDecl();
5920 if (!OldDecl || !NewDecl)
5923 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5924 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5925 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5926 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5928 // dllimport and dllexport are inheritable attributes so we have to exclude
5929 // inherited attribute instances.
5930 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5931 (NewExportAttr && !NewExportAttr->isInherited());
5933 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5934 // the only exception being explicit specializations.
5935 // Implicitly generated declarations are also excluded for now because there
5936 // is no other way to switch these to use dllimport or dllexport.
5937 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5939 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5940 // Allow with a warning for free functions and global variables.
5941 bool JustWarn = false;
5942 if (!OldDecl->isCXXClassMember()) {
5943 auto *VD = dyn_cast<VarDecl>(OldDecl);
5944 if (VD && !VD->getDescribedVarTemplate())
5946 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5947 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5951 // We cannot change a declaration that's been used because IR has already
5952 // been emitted. Dllimported functions will still work though (modulo
5953 // address equality) as they can use the thunk.
5954 if (OldDecl->isUsed())
5955 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5958 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5959 : diag::err_attribute_dll_redeclaration;
5960 S.Diag(NewDecl->getLocation(), DiagID)
5962 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5963 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5965 NewDecl->setInvalidDecl();
5970 // A redeclaration is not allowed to drop a dllimport attribute, the only
5971 // exceptions being inline function definitions (except for function
5972 // templates), local extern declarations, qualified friend declarations or
5973 // special MSVC extension: in the last case, the declaration is treated as if
5974 // it were marked dllexport.
5975 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5976 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5977 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5978 // Ignore static data because out-of-line definitions are diagnosed
5980 IsStaticDataMember = VD->isStaticDataMember();
5981 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5982 VarDecl::DeclarationOnly;
5983 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5984 IsInline = FD->isInlined();
5985 IsQualifiedFriend = FD->getQualifier() &&
5986 FD->getFriendObjectKind() == Decl::FOK_Declared;
5989 if (OldImportAttr && !HasNewAttr &&
5990 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5991 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5992 if (IsMicrosoft && IsDefinition) {
5993 S.Diag(NewDecl->getLocation(),
5994 diag::warn_redeclaration_without_import_attribute)
5996 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5997 NewDecl->dropAttr<DLLImportAttr>();
5998 NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5999 NewImportAttr->getRange(), S.Context,
6000 NewImportAttr->getSpellingListIndex()));
6002 S.Diag(NewDecl->getLocation(),
6003 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6004 << NewDecl << OldImportAttr;
6005 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6006 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6007 OldDecl->dropAttr<DLLImportAttr>();
6008 NewDecl->dropAttr<DLLImportAttr>();
6010 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6011 // In MinGW, seeing a function declared inline drops the dllimport attribute.
6012 OldDecl->dropAttr<DLLImportAttr>();
6013 NewDecl->dropAttr<DLLImportAttr>();
6014 S.Diag(NewDecl->getLocation(),
6015 diag::warn_dllimport_dropped_from_inline_function)
6016 << NewDecl << OldImportAttr;
6020 /// Given that we are within the definition of the given function,
6021 /// will that definition behave like C99's 'inline', where the
6022 /// definition is discarded except for optimization purposes?
6023 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6024 // Try to avoid calling GetGVALinkageForFunction.
6026 // All cases of this require the 'inline' keyword.
6027 if (!FD->isInlined()) return false;
6029 // This is only possible in C++ with the gnu_inline attribute.
6030 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6033 // Okay, go ahead and call the relatively-more-expensive function.
6034 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6037 /// Determine whether a variable is extern "C" prior to attaching
6038 /// an initializer. We can't just call isExternC() here, because that
6039 /// will also compute and cache whether the declaration is externally
6040 /// visible, which might change when we attach the initializer.
6042 /// This can only be used if the declaration is known to not be a
6043 /// redeclaration of an internal linkage declaration.
6049 /// Attaching the initializer here makes this declaration not externally
6050 /// visible, because its type has internal linkage.
6052 /// FIXME: This is a hack.
6053 template<typename T>
6054 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6055 if (S.getLangOpts().CPlusPlus) {
6056 // In C++, the overloadable attribute negates the effects of extern "C".
6057 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6060 // So do CUDA's host/device attributes.
6061 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6062 D->template hasAttr<CUDAHostAttr>()))
6065 return D->isExternC();
6068 static bool shouldConsiderLinkage(const VarDecl *VD) {
6069 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6070 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6071 return VD->hasExternalStorage();
6072 if (DC->isFileContext())
6076 llvm_unreachable("Unexpected context");
6079 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6080 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6081 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6082 isa<OMPDeclareReductionDecl>(DC))
6086 llvm_unreachable("Unexpected context");
6089 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6090 AttributeList::Kind Kind) {
6091 for (const AttributeList *L = AttrList; L; L = L->getNext())
6092 if (L->getKind() == Kind)
6097 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6098 AttributeList::Kind Kind) {
6099 // Check decl attributes on the DeclSpec.
6100 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6103 // Walk the declarator structure, checking decl attributes that were in a type
6104 // position to the decl itself.
6105 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6106 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6110 // Finally, check attributes on the decl itself.
6111 return hasParsedAttr(S, PD.getAttributes(), Kind);
6114 /// Adjust the \c DeclContext for a function or variable that might be a
6115 /// function-local external declaration.
6116 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6117 if (!DC->isFunctionOrMethod())
6120 // If this is a local extern function or variable declared within a function
6121 // template, don't add it into the enclosing namespace scope until it is
6122 // instantiated; it might have a dependent type right now.
6123 if (DC->isDependentContext())
6126 // C++11 [basic.link]p7:
6127 // When a block scope declaration of an entity with linkage is not found to
6128 // refer to some other declaration, then that entity is a member of the
6129 // innermost enclosing namespace.
6131 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6132 // semantically-enclosing namespace, not a lexically-enclosing one.
6133 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6134 DC = DC->getParent();
6138 /// \brief Returns true if given declaration has external C language linkage.
6139 static bool isDeclExternC(const Decl *D) {
6140 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6141 return FD->isExternC();
6142 if (const auto *VD = dyn_cast<VarDecl>(D))
6143 return VD->isExternC();
6145 llvm_unreachable("Unknown type of decl!");
6148 NamedDecl *Sema::ActOnVariableDeclarator(
6149 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6150 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6151 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6152 QualType R = TInfo->getType();
6153 DeclarationName Name = GetNameForDeclarator(D).getName();
6155 IdentifierInfo *II = Name.getAsIdentifierInfo();
6157 if (D.isDecompositionDeclarator()) {
6159 // Take the name of the first declarator as our name for diagnostic
6161 auto &Decomp = D.getDecompositionDeclarator();
6162 if (!Decomp.bindings().empty()) {
6163 II = Decomp.bindings()[0].Name;
6167 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6171 if (getLangOpts().OpenCL) {
6172 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6173 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6175 if (R->isImageType() || R->isPipeType()) {
6176 Diag(D.getIdentifierLoc(),
6177 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6183 // OpenCL v1.2 s6.9.r:
6184 // The event type cannot be used to declare a program scope variable.
6185 // OpenCL v2.0 s6.9.q:
6186 // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6187 if (NULL == S->getParent()) {
6188 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6189 Diag(D.getIdentifierLoc(),
6190 diag::err_invalid_type_for_program_scope_var) << R;
6196 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6198 while (NR->isPointerType()) {
6199 if (NR->isFunctionPointerType()) {
6200 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6204 NR = NR->getPointeeType();
6207 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6208 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6209 // half array type (unless the cl_khr_fp16 extension is enabled).
6210 if (Context.getBaseElementType(R)->isHalfType()) {
6211 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6216 if (R->isSamplerT()) {
6217 // OpenCL v1.2 s6.9.b p4:
6218 // The sampler type cannot be used with the __local and __global address
6219 // space qualifiers.
6220 if (R.getAddressSpace() == LangAS::opencl_local ||
6221 R.getAddressSpace() == LangAS::opencl_global) {
6222 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6225 // OpenCL v1.2 s6.12.14.1:
6226 // A global sampler must be declared with either the constant address
6227 // space qualifier or with the const qualifier.
6228 if (DC->isTranslationUnit() &&
6229 !(R.getAddressSpace() == LangAS::opencl_constant ||
6230 R.isConstQualified())) {
6231 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6236 // OpenCL v1.2 s6.9.r:
6237 // The event type cannot be used with the __local, __constant and __global
6238 // address space qualifiers.
6239 if (R->isEventT()) {
6240 if (R.getAddressSpace()) {
6241 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6247 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6248 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6250 // dllimport globals without explicit storage class are treated as extern. We
6251 // have to change the storage class this early to get the right DeclContext.
6252 if (SC == SC_None && !DC->isRecord() &&
6253 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6254 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6257 DeclContext *OriginalDC = DC;
6258 bool IsLocalExternDecl = SC == SC_Extern &&
6259 adjustContextForLocalExternDecl(DC);
6261 if (SCSpec == DeclSpec::SCS_mutable) {
6262 // mutable can only appear on non-static class members, so it's always
6264 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6269 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6270 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6271 D.getDeclSpec().getStorageClassSpecLoc())) {
6272 // In C++11, the 'register' storage class specifier is deprecated.
6273 // Suppress the warning in system macros, it's used in macros in some
6274 // popular C system headers, such as in glibc's htonl() macro.
6275 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6276 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6277 : diag::warn_deprecated_register)
6278 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6281 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6283 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6284 // C99 6.9p2: The storage-class specifiers auto and register shall not
6285 // appear in the declaration specifiers in an external declaration.
6286 // Global Register+Asm is a GNU extension we support.
6287 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6288 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6293 bool IsMemberSpecialization = false;
6294 bool IsVariableTemplateSpecialization = false;
6295 bool IsPartialSpecialization = false;
6296 bool IsVariableTemplate = false;
6297 VarDecl *NewVD = nullptr;
6298 VarTemplateDecl *NewTemplate = nullptr;
6299 TemplateParameterList *TemplateParams = nullptr;
6300 if (!getLangOpts().CPlusPlus) {
6301 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6302 D.getIdentifierLoc(), II,
6305 if (R->getContainedDeducedType())
6306 ParsingInitForAutoVars.insert(NewVD);
6308 if (D.isInvalidType())
6309 NewVD->setInvalidDecl();
6311 bool Invalid = false;
6313 if (DC->isRecord() && !CurContext->isRecord()) {
6314 // This is an out-of-line definition of a static data member.
6319 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6320 diag::err_static_out_of_line)
6321 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6326 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6327 // to names of variables declared in a block or to function parameters.
6328 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6331 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6332 diag::err_storage_class_for_static_member)
6333 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6335 case SC_PrivateExtern:
6336 llvm_unreachable("C storage class in c++!");
6340 if (SC == SC_Static && CurContext->isRecord()) {
6341 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6342 if (RD->isLocalClass())
6343 Diag(D.getIdentifierLoc(),
6344 diag::err_static_data_member_not_allowed_in_local_class)
6345 << Name << RD->getDeclName();
6347 // C++98 [class.union]p1: If a union contains a static data member,
6348 // the program is ill-formed. C++11 drops this restriction.
6350 Diag(D.getIdentifierLoc(),
6351 getLangOpts().CPlusPlus11
6352 ? diag::warn_cxx98_compat_static_data_member_in_union
6353 : diag::ext_static_data_member_in_union) << Name;
6354 // We conservatively disallow static data members in anonymous structs.
6355 else if (!RD->getDeclName())
6356 Diag(D.getIdentifierLoc(),
6357 diag::err_static_data_member_not_allowed_in_anon_struct)
6358 << Name << RD->isUnion();
6362 // Match up the template parameter lists with the scope specifier, then
6363 // determine whether we have a template or a template specialization.
6364 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6365 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6366 D.getCXXScopeSpec(),
6367 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6368 ? D.getName().TemplateId
6371 /*never a friend*/ false, IsMemberSpecialization, Invalid);
6373 if (TemplateParams) {
6374 if (!TemplateParams->size() &&
6375 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6376 // There is an extraneous 'template<>' for this variable. Complain
6377 // about it, but allow the declaration of the variable.
6378 Diag(TemplateParams->getTemplateLoc(),
6379 diag::err_template_variable_noparams)
6381 << SourceRange(TemplateParams->getTemplateLoc(),
6382 TemplateParams->getRAngleLoc());
6383 TemplateParams = nullptr;
6385 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6386 // This is an explicit specialization or a partial specialization.
6387 // FIXME: Check that we can declare a specialization here.
6388 IsVariableTemplateSpecialization = true;
6389 IsPartialSpecialization = TemplateParams->size() > 0;
6390 } else { // if (TemplateParams->size() > 0)
6391 // This is a template declaration.
6392 IsVariableTemplate = true;
6394 // Check that we can declare a template here.
6395 if (CheckTemplateDeclScope(S, TemplateParams))
6398 // Only C++1y supports variable templates (N3651).
6399 Diag(D.getIdentifierLoc(),
6400 getLangOpts().CPlusPlus14
6401 ? diag::warn_cxx11_compat_variable_template
6402 : diag::ext_variable_template);
6407 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6408 "should have a 'template<>' for this decl");
6411 if (IsVariableTemplateSpecialization) {
6412 SourceLocation TemplateKWLoc =
6413 TemplateParamLists.size() > 0
6414 ? TemplateParamLists[0]->getTemplateLoc()
6416 DeclResult Res = ActOnVarTemplateSpecialization(
6417 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6418 IsPartialSpecialization);
6419 if (Res.isInvalid())
6421 NewVD = cast<VarDecl>(Res.get());
6423 } else if (D.isDecompositionDeclarator()) {
6424 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6425 D.getIdentifierLoc(), R, TInfo, SC,
6428 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6429 D.getIdentifierLoc(), II, R, TInfo, SC);
6431 // If this is supposed to be a variable template, create it as such.
6432 if (IsVariableTemplate) {
6434 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6435 TemplateParams, NewVD);
6436 NewVD->setDescribedVarTemplate(NewTemplate);
6439 // If this decl has an auto type in need of deduction, make a note of the
6440 // Decl so we can diagnose uses of it in its own initializer.
6441 if (R->getContainedDeducedType())
6442 ParsingInitForAutoVars.insert(NewVD);
6444 if (D.isInvalidType() || Invalid) {
6445 NewVD->setInvalidDecl();
6447 NewTemplate->setInvalidDecl();
6450 SetNestedNameSpecifier(NewVD, D);
6452 // If we have any template parameter lists that don't directly belong to
6453 // the variable (matching the scope specifier), store them.
6454 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6455 if (TemplateParamLists.size() > VDTemplateParamLists)
6456 NewVD->setTemplateParameterListsInfo(
6457 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6459 if (D.getDeclSpec().isConstexprSpecified()) {
6460 NewVD->setConstexpr(true);
6461 // C++1z [dcl.spec.constexpr]p1:
6462 // A static data member declared with the constexpr specifier is
6463 // implicitly an inline variable.
6464 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6465 NewVD->setImplicitlyInline();
6468 if (D.getDeclSpec().isConceptSpecified()) {
6469 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6472 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6473 // be declared with the thread_local, inline, friend, or constexpr
6474 // specifiers, [...]
6475 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6476 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6477 diag::err_concept_decl_invalid_specifiers)
6479 NewVD->setInvalidDecl(true);
6482 if (D.getDeclSpec().isConstexprSpecified()) {
6483 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6484 diag::err_concept_decl_invalid_specifiers)
6486 NewVD->setInvalidDecl(true);
6489 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6490 // applied only to the definition of a function template or variable
6491 // template, declared in namespace scope.
6492 if (IsVariableTemplateSpecialization) {
6493 Diag(D.getDeclSpec().getConceptSpecLoc(),
6494 diag::err_concept_specified_specialization)
6495 << (IsPartialSpecialization ? 2 : 1);
6498 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6499 // following restrictions:
6500 // - The declared type shall have the type bool.
6501 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6502 !NewVD->isInvalidDecl()) {
6503 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6504 NewVD->setInvalidDecl(true);
6509 if (D.getDeclSpec().isInlineSpecified()) {
6510 if (!getLangOpts().CPlusPlus) {
6511 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6513 } else if (CurContext->isFunctionOrMethod()) {
6514 // 'inline' is not allowed on block scope variable declaration.
6515 Diag(D.getDeclSpec().getInlineSpecLoc(),
6516 diag::err_inline_declaration_block_scope) << Name
6517 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6519 Diag(D.getDeclSpec().getInlineSpecLoc(),
6520 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6521 : diag::ext_inline_variable);
6522 NewVD->setInlineSpecified();
6526 // Set the lexical context. If the declarator has a C++ scope specifier, the
6527 // lexical context will be different from the semantic context.
6528 NewVD->setLexicalDeclContext(CurContext);
6530 NewTemplate->setLexicalDeclContext(CurContext);
6532 if (IsLocalExternDecl) {
6533 if (D.isDecompositionDeclarator())
6534 for (auto *B : Bindings)
6535 B->setLocalExternDecl();
6537 NewVD->setLocalExternDecl();
6540 bool EmitTLSUnsupportedError = false;
6541 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6542 // C++11 [dcl.stc]p4:
6543 // When thread_local is applied to a variable of block scope the
6544 // storage-class-specifier static is implied if it does not appear
6546 // Core issue: 'static' is not implied if the variable is declared
6548 if (NewVD->hasLocalStorage() &&
6549 (SCSpec != DeclSpec::SCS_unspecified ||
6550 TSCS != DeclSpec::TSCS_thread_local ||
6551 !DC->isFunctionOrMethod()))
6552 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6553 diag::err_thread_non_global)
6554 << DeclSpec::getSpecifierName(TSCS);
6555 else if (!Context.getTargetInfo().isTLSSupported()) {
6556 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6557 // Postpone error emission until we've collected attributes required to
6558 // figure out whether it's a host or device variable and whether the
6559 // error should be ignored.
6560 EmitTLSUnsupportedError = true;
6561 // We still need to mark the variable as TLS so it shows up in AST with
6562 // proper storage class for other tools to use even if we're not going
6563 // to emit any code for it.
6564 NewVD->setTSCSpec(TSCS);
6566 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6567 diag::err_thread_unsupported);
6569 NewVD->setTSCSpec(TSCS);
6573 // An inline definition of a function with external linkage shall
6574 // not contain a definition of a modifiable object with static or
6575 // thread storage duration...
6576 // We only apply this when the function is required to be defined
6577 // elsewhere, i.e. when the function is not 'extern inline'. Note
6578 // that a local variable with thread storage duration still has to
6579 // be marked 'static'. Also note that it's possible to get these
6580 // semantics in C++ using __attribute__((gnu_inline)).
6581 if (SC == SC_Static && S->getFnParent() != nullptr &&
6582 !NewVD->getType().isConstQualified()) {
6583 FunctionDecl *CurFD = getCurFunctionDecl();
6584 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6585 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6586 diag::warn_static_local_in_extern_inline);
6587 MaybeSuggestAddingStaticToDecl(CurFD);
6591 if (D.getDeclSpec().isModulePrivateSpecified()) {
6592 if (IsVariableTemplateSpecialization)
6593 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6594 << (IsPartialSpecialization ? 1 : 0)
6595 << FixItHint::CreateRemoval(
6596 D.getDeclSpec().getModulePrivateSpecLoc());
6597 else if (IsMemberSpecialization)
6598 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6600 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6601 else if (NewVD->hasLocalStorage())
6602 Diag(NewVD->getLocation(), diag::err_module_private_local)
6603 << 0 << NewVD->getDeclName()
6604 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6605 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6607 NewVD->setModulePrivate();
6609 NewTemplate->setModulePrivate();
6610 for (auto *B : Bindings)
6611 B->setModulePrivate();
6615 // Handle attributes prior to checking for duplicates in MergeVarDecl
6616 ProcessDeclAttributes(S, NewVD, D);
6618 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6619 if (EmitTLSUnsupportedError &&
6620 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6621 (getLangOpts().OpenMPIsDevice &&
6622 NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6623 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6624 diag::err_thread_unsupported);
6625 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6626 // storage [duration]."
6627 if (SC == SC_None && S->getFnParent() != nullptr &&
6628 (NewVD->hasAttr<CUDASharedAttr>() ||
6629 NewVD->hasAttr<CUDAConstantAttr>())) {
6630 NewVD->setStorageClass(SC_Static);
6634 // Ensure that dllimport globals without explicit storage class are treated as
6635 // extern. The storage class is set above using parsed attributes. Now we can
6636 // check the VarDecl itself.
6637 assert(!NewVD->hasAttr<DLLImportAttr>() ||
6638 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6639 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6641 // In auto-retain/release, infer strong retension for variables of
6643 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6644 NewVD->setInvalidDecl();
6646 // Handle GNU asm-label extension (encoded as an attribute).
6647 if (Expr *E = (Expr*)D.getAsmLabel()) {
6648 // The parser guarantees this is a string.
6649 StringLiteral *SE = cast<StringLiteral>(E);
6650 StringRef Label = SE->getString();
6651 if (S->getFnParent() != nullptr) {
6655 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6658 // Local Named register
6659 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6660 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6661 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6665 case SC_PrivateExtern:
6668 } else if (SC == SC_Register) {
6669 // Global Named register
6670 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6671 const auto &TI = Context.getTargetInfo();
6672 bool HasSizeMismatch;
6674 if (!TI.isValidGCCRegisterName(Label))
6675 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6676 else if (!TI.validateGlobalRegisterVariable(Label,
6677 Context.getTypeSize(R),
6679 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6680 else if (HasSizeMismatch)
6681 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6684 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6685 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6686 NewVD->setInvalidDecl(true);
6690 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6691 Context, Label, 0));
6692 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6693 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6694 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6695 if (I != ExtnameUndeclaredIdentifiers.end()) {
6696 if (isDeclExternC(NewVD)) {
6697 NewVD->addAttr(I->second);
6698 ExtnameUndeclaredIdentifiers.erase(I);
6700 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6701 << /*Variable*/1 << NewVD;
6705 // Find the shadowed declaration before filtering for scope.
6706 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6707 ? getShadowedDeclaration(NewVD, Previous)
6710 // Don't consider existing declarations that are in a different
6711 // scope and are out-of-semantic-context declarations (if the new
6712 // declaration has linkage).
6713 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6714 D.getCXXScopeSpec().isNotEmpty() ||
6715 IsMemberSpecialization ||
6716 IsVariableTemplateSpecialization);
6718 // Check whether the previous declaration is in the same block scope. This
6719 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6720 if (getLangOpts().CPlusPlus &&
6721 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6722 NewVD->setPreviousDeclInSameBlockScope(
6723 Previous.isSingleResult() && !Previous.isShadowed() &&
6724 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6726 if (!getLangOpts().CPlusPlus) {
6727 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6729 // If this is an explicit specialization of a static data member, check it.
6730 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6731 CheckMemberSpecialization(NewVD, Previous))
6732 NewVD->setInvalidDecl();
6734 // Merge the decl with the existing one if appropriate.
6735 if (!Previous.empty()) {
6736 if (Previous.isSingleResult() &&
6737 isa<FieldDecl>(Previous.getFoundDecl()) &&
6738 D.getCXXScopeSpec().isSet()) {
6739 // The user tried to define a non-static data member
6740 // out-of-line (C++ [dcl.meaning]p1).
6741 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6742 << D.getCXXScopeSpec().getRange();
6744 NewVD->setInvalidDecl();
6746 } else if (D.getCXXScopeSpec().isSet()) {
6747 // No previous declaration in the qualifying scope.
6748 Diag(D.getIdentifierLoc(), diag::err_no_member)
6749 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6750 << D.getCXXScopeSpec().getRange();
6751 NewVD->setInvalidDecl();
6754 if (!IsVariableTemplateSpecialization)
6755 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6757 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6758 // an explicit specialization (14.8.3) or a partial specialization of a
6759 // concept definition.
6760 if (IsVariableTemplateSpecialization &&
6761 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6762 Previous.isSingleResult()) {
6763 NamedDecl *PreviousDecl = Previous.getFoundDecl();
6764 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6765 if (VarTmpl->isConcept()) {
6766 Diag(NewVD->getLocation(), diag::err_concept_specialized)
6768 << (IsPartialSpecialization ? 2 /*partially specialized*/
6769 : 1 /*explicitly specialized*/);
6770 Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6771 NewVD->setInvalidDecl();
6777 VarTemplateDecl *PrevVarTemplate =
6778 NewVD->getPreviousDecl()
6779 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6782 // Check the template parameter list of this declaration, possibly
6783 // merging in the template parameter list from the previous variable
6784 // template declaration.
6785 if (CheckTemplateParameterList(
6787 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6789 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6790 DC->isDependentContext())
6791 ? TPC_ClassTemplateMember
6793 NewVD->setInvalidDecl();
6795 // If we are providing an explicit specialization of a static variable
6796 // template, make a note of that.
6797 if (PrevVarTemplate &&
6798 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6799 PrevVarTemplate->setMemberSpecialization();
6803 // Diagnose shadowed variables iff this isn't a redeclaration.
6804 if (ShadowedDecl && !D.isRedeclaration())
6805 CheckShadow(NewVD, ShadowedDecl, Previous);
6807 ProcessPragmaWeak(S, NewVD);
6809 // If this is the first declaration of an extern C variable, update
6810 // the map of such variables.
6811 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6812 isIncompleteDeclExternC(*this, NewVD))
6813 RegisterLocallyScopedExternCDecl(NewVD, S);
6815 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6816 Decl *ManglingContextDecl;
6817 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6818 NewVD->getDeclContext(), ManglingContextDecl)) {
6819 Context.setManglingNumber(
6820 NewVD, MCtx->getManglingNumber(
6821 NewVD, getMSManglingNumber(getLangOpts(), S)));
6822 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6826 // Special handling of variable named 'main'.
6827 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6828 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6829 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6831 // C++ [basic.start.main]p3
6832 // A program that declares a variable main at global scope is ill-formed.
6833 if (getLangOpts().CPlusPlus)
6834 Diag(D.getLocStart(), diag::err_main_global_variable);
6836 // In C, and external-linkage variable named main results in undefined
6838 else if (NewVD->hasExternalFormalLinkage())
6839 Diag(D.getLocStart(), diag::warn_main_redefined);
6842 if (D.isRedeclaration() && !Previous.empty()) {
6843 checkDLLAttributeRedeclaration(
6844 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6845 IsMemberSpecialization, D.isFunctionDefinition());
6849 if (NewVD->isInvalidDecl())
6850 NewTemplate->setInvalidDecl();
6851 ActOnDocumentableDecl(NewTemplate);
6855 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6856 CompleteMemberSpecialization(NewVD, Previous);
6861 /// Enum describing the %select options in diag::warn_decl_shadow.
6862 enum ShadowedDeclKind {
6871 /// Determine what kind of declaration we're shadowing.
6872 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6873 const DeclContext *OldDC) {
6874 if (isa<TypeAliasDecl>(ShadowedDecl))
6876 else if (isa<TypedefDecl>(ShadowedDecl))
6878 else if (isa<RecordDecl>(OldDC))
6879 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6881 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6884 /// Return the location of the capture if the given lambda captures the given
6885 /// variable \p VD, or an invalid source location otherwise.
6886 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6887 const VarDecl *VD) {
6888 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6889 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6890 return Capture.getLocation();
6892 return SourceLocation();
6895 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6896 const LookupResult &R) {
6897 // Only diagnose if we're shadowing an unambiguous field or variable.
6898 if (R.getResultKind() != LookupResult::Found)
6901 // Return false if warning is ignored.
6902 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6905 /// \brief Return the declaration shadowed by the given variable \p D, or null
6906 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6907 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6908 const LookupResult &R) {
6909 if (!shouldWarnIfShadowedDecl(Diags, R))
6912 // Don't diagnose declarations at file scope.
6913 if (D->hasGlobalStorage())
6916 NamedDecl *ShadowedDecl = R.getFoundDecl();
6917 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6922 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6923 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6924 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6925 const LookupResult &R) {
6926 // Don't warn if typedef declaration is part of a class
6927 if (D->getDeclContext()->isRecord())
6930 if (!shouldWarnIfShadowedDecl(Diags, R))
6933 NamedDecl *ShadowedDecl = R.getFoundDecl();
6934 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6937 /// \brief Diagnose variable or built-in function shadowing. Implements
6940 /// This method is called whenever a VarDecl is added to a "useful"
6943 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6944 /// \param R the lookup of the name
6946 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6947 const LookupResult &R) {
6948 DeclContext *NewDC = D->getDeclContext();
6950 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6951 // Fields are not shadowed by variables in C++ static methods.
6952 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6956 // Fields shadowed by constructor parameters are a special case. Usually
6957 // the constructor initializes the field with the parameter.
6958 if (isa<CXXConstructorDecl>(NewDC))
6959 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6960 // Remember that this was shadowed so we can either warn about its
6961 // modification or its existence depending on warning settings.
6962 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6967 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6968 if (shadowedVar->isExternC()) {
6969 // For shadowing external vars, make sure that we point to the global
6970 // declaration, not a locally scoped extern declaration.
6971 for (auto I : shadowedVar->redecls())
6972 if (I->isFileVarDecl()) {
6978 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
6980 unsigned WarningDiag = diag::warn_decl_shadow;
6981 SourceLocation CaptureLoc;
6982 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6983 isa<CXXMethodDecl>(NewDC)) {
6984 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6985 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6986 if (RD->getLambdaCaptureDefault() == LCD_None) {
6987 // Try to avoid warnings for lambdas with an explicit capture list.
6988 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6989 // Warn only when the lambda captures the shadowed decl explicitly.
6990 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6991 if (CaptureLoc.isInvalid())
6992 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6994 // Remember that this was shadowed so we can avoid the warning if the
6995 // shadowed decl isn't captured and the warning settings allow it.
6996 cast<LambdaScopeInfo>(getCurFunction())
6997 ->ShadowingDecls.push_back(
6998 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7005 // Only warn about certain kinds of shadowing for class members.
7006 if (NewDC && NewDC->isRecord()) {
7007 // In particular, don't warn about shadowing non-class members.
7008 if (!OldDC->isRecord())
7011 // TODO: should we warn about static data members shadowing
7012 // static data members from base classes?
7014 // TODO: don't diagnose for inaccessible shadowed members.
7015 // This is hard to do perfectly because we might friend the
7016 // shadowing context, but that's just a false negative.
7020 DeclarationName Name = R.getLookupName();
7022 // Emit warning and note.
7023 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7025 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7026 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7027 if (!CaptureLoc.isInvalid())
7028 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7029 << Name << /*explicitly*/ 1;
7030 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7033 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7034 /// when these variables are captured by the lambda.
7035 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7036 for (const auto &Shadow : LSI->ShadowingDecls) {
7037 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7038 // Try to avoid the warning when the shadowed decl isn't captured.
7039 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7040 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7041 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7042 ? diag::warn_decl_shadow_uncaptured_local
7043 : diag::warn_decl_shadow)
7044 << Shadow.VD->getDeclName()
7045 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7046 if (!CaptureLoc.isInvalid())
7047 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7048 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7049 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7053 /// \brief Check -Wshadow without the advantage of a previous lookup.
7054 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7055 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7058 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7059 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
7061 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7062 CheckShadow(D, ShadowedDecl, R);
7065 /// Check if 'E', which is an expression that is about to be modified, refers
7066 /// to a constructor parameter that shadows a field.
7067 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7068 // Quickly ignore expressions that can't be shadowing ctor parameters.
7069 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7071 E = E->IgnoreParenImpCasts();
7072 auto *DRE = dyn_cast<DeclRefExpr>(E);
7075 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7076 auto I = ShadowingDecls.find(D);
7077 if (I == ShadowingDecls.end())
7079 const NamedDecl *ShadowedDecl = I->second;
7080 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7081 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7082 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7083 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7085 // Avoid issuing multiple warnings about the same decl.
7086 ShadowingDecls.erase(I);
7089 /// Check for conflict between this global or extern "C" declaration and
7090 /// previous global or extern "C" declarations. This is only used in C++.
7091 template<typename T>
7092 static bool checkGlobalOrExternCConflict(
7093 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7094 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7095 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7097 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7098 // The common case: this global doesn't conflict with any extern "C"
7104 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7105 // Both the old and new declarations have C language linkage. This is a
7108 Previous.addDecl(Prev);
7112 // This is a global, non-extern "C" declaration, and there is a previous
7113 // non-global extern "C" declaration. Diagnose if this is a variable
7115 if (!isa<VarDecl>(ND))
7118 // The declaration is extern "C". Check for any declaration in the
7119 // translation unit which might conflict.
7121 // We have already performed the lookup into the translation unit.
7123 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7125 if (isa<VarDecl>(*I)) {
7131 DeclContext::lookup_result R =
7132 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7133 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7135 if (isa<VarDecl>(*I)) {
7139 // FIXME: If we have any other entity with this name in global scope,
7140 // the declaration is ill-formed, but that is a defect: it breaks the
7141 // 'stat' hack, for instance. Only variables can have mangled name
7142 // clashes with extern "C" declarations, so only they deserve a
7151 // Use the first declaration's location to ensure we point at something which
7152 // is lexically inside an extern "C" linkage-spec.
7153 assert(Prev && "should have found a previous declaration to diagnose");
7154 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7155 Prev = FD->getFirstDecl();
7157 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7159 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7161 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7166 /// Apply special rules for handling extern "C" declarations. Returns \c true
7167 /// if we have found that this is a redeclaration of some prior entity.
7169 /// Per C++ [dcl.link]p6:
7170 /// Two declarations [for a function or variable] with C language linkage
7171 /// with the same name that appear in different scopes refer to the same
7172 /// [entity]. An entity with C language linkage shall not be declared with
7173 /// the same name as an entity in global scope.
7174 template<typename T>
7175 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7176 LookupResult &Previous) {
7177 if (!S.getLangOpts().CPlusPlus) {
7178 // In C, when declaring a global variable, look for a corresponding 'extern'
7179 // variable declared in function scope. We don't need this in C++, because
7180 // we find local extern decls in the surrounding file-scope DeclContext.
7181 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7182 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7184 Previous.addDecl(Prev);
7191 // A declaration in the translation unit can conflict with an extern "C"
7193 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7194 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7196 // An extern "C" declaration can conflict with a declaration in the
7197 // translation unit or can be a redeclaration of an extern "C" declaration
7198 // in another scope.
7199 if (isIncompleteDeclExternC(S,ND))
7200 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7202 // Neither global nor extern "C": nothing to do.
7206 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7207 // If the decl is already known invalid, don't check it.
7208 if (NewVD->isInvalidDecl())
7211 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7212 QualType T = TInfo->getType();
7214 // Defer checking an 'auto' type until its initializer is attached.
7215 if (T->isUndeducedType())
7218 if (NewVD->hasAttrs())
7219 CheckAlignasUnderalignment(NewVD);
7221 if (T->isObjCObjectType()) {
7222 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7223 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7224 T = Context.getObjCObjectPointerType(T);
7228 // Emit an error if an address space was applied to decl with local storage.
7229 // This includes arrays of objects with address space qualifiers, but not
7230 // automatic variables that point to other address spaces.
7231 // ISO/IEC TR 18037 S5.1.2
7232 if (!getLangOpts().OpenCL
7233 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7234 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7235 NewVD->setInvalidDecl();
7239 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7241 if (getLangOpts().OpenCLVersion == 120 &&
7242 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7243 NewVD->isStaticLocal()) {
7244 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7245 NewVD->setInvalidDecl();
7249 if (getLangOpts().OpenCL) {
7250 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7251 if (NewVD->hasAttr<BlocksAttr>()) {
7252 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7256 if (T->isBlockPointerType()) {
7257 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7258 // can't use 'extern' storage class.
7259 if (!T.isConstQualified()) {
7260 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7262 NewVD->setInvalidDecl();
7265 if (NewVD->hasExternalStorage()) {
7266 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7267 NewVD->setInvalidDecl();
7271 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7272 // __constant address space.
7273 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7274 // variables inside a function can also be declared in the global
7276 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7277 NewVD->hasExternalStorage()) {
7278 if (!T->isSamplerT() &&
7279 !(T.getAddressSpace() == LangAS::opencl_constant ||
7280 (T.getAddressSpace() == LangAS::opencl_global &&
7281 getLangOpts().OpenCLVersion == 200))) {
7282 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7283 if (getLangOpts().OpenCLVersion == 200)
7284 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7285 << Scope << "global or constant";
7287 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7288 << Scope << "constant";
7289 NewVD->setInvalidDecl();
7293 if (T.getAddressSpace() == LangAS::opencl_global) {
7294 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7295 << 1 /*is any function*/ << "global";
7296 NewVD->setInvalidDecl();
7299 if (T.getAddressSpace() == LangAS::opencl_constant ||
7300 T.getAddressSpace() == LangAS::opencl_local) {
7301 FunctionDecl *FD = getCurFunctionDecl();
7302 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7304 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7305 if (T.getAddressSpace() == LangAS::opencl_constant)
7306 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7307 << 0 /*non-kernel only*/ << "constant";
7309 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7310 << 0 /*non-kernel only*/ << "local";
7311 NewVD->setInvalidDecl();
7314 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7315 // in the outermost scope of a kernel function.
7316 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7317 if (!getCurScope()->isFunctionScope()) {
7318 if (T.getAddressSpace() == LangAS::opencl_constant)
7319 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7322 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7324 NewVD->setInvalidDecl();
7328 } else if (T.getAddressSpace() != LangAS::Default) {
7329 // Do not allow other address spaces on automatic variable.
7330 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7331 NewVD->setInvalidDecl();
7337 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7338 && !NewVD->hasAttr<BlocksAttr>()) {
7339 if (getLangOpts().getGC() != LangOptions::NonGC)
7340 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7342 assert(!getLangOpts().ObjCAutoRefCount);
7343 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7347 bool isVM = T->isVariablyModifiedType();
7348 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7349 NewVD->hasAttr<BlocksAttr>())
7350 getCurFunction()->setHasBranchProtectedScope();
7352 if ((isVM && NewVD->hasLinkage()) ||
7353 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7354 bool SizeIsNegative;
7355 llvm::APSInt Oversized;
7356 TypeSourceInfo *FixedTInfo =
7357 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7358 SizeIsNegative, Oversized);
7359 if (!FixedTInfo && T->isVariableArrayType()) {
7360 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7361 // FIXME: This won't give the correct result for
7363 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7365 if (NewVD->isFileVarDecl())
7366 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7368 else if (NewVD->isStaticLocal())
7369 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7372 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7374 NewVD->setInvalidDecl();
7379 if (NewVD->isFileVarDecl())
7380 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7382 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7383 NewVD->setInvalidDecl();
7387 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7388 NewVD->setType(FixedTInfo->getType());
7389 NewVD->setTypeSourceInfo(FixedTInfo);
7392 if (T->isVoidType()) {
7393 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7394 // of objects and functions.
7395 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7396 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7398 NewVD->setInvalidDecl();
7403 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7404 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7405 NewVD->setInvalidDecl();
7409 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7410 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7411 NewVD->setInvalidDecl();
7415 if (NewVD->isConstexpr() && !T->isDependentType() &&
7416 RequireLiteralType(NewVD->getLocation(), T,
7417 diag::err_constexpr_var_non_literal)) {
7418 NewVD->setInvalidDecl();
7423 /// \brief Perform semantic checking on a newly-created variable
7426 /// This routine performs all of the type-checking required for a
7427 /// variable declaration once it has been built. It is used both to
7428 /// check variables after they have been parsed and their declarators
7429 /// have been translated into a declaration, and to check variables
7430 /// that have been instantiated from a template.
7432 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7434 /// Returns true if the variable declaration is a redeclaration.
7435 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7436 CheckVariableDeclarationType(NewVD);
7438 // If the decl is already known invalid, don't check it.
7439 if (NewVD->isInvalidDecl())
7442 // If we did not find anything by this name, look for a non-visible
7443 // extern "C" declaration with the same name.
7444 if (Previous.empty() &&
7445 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7446 Previous.setShadowed();
7448 if (!Previous.empty()) {
7449 MergeVarDecl(NewVD, Previous);
7456 struct FindOverriddenMethod {
7458 CXXMethodDecl *Method;
7460 /// Member lookup function that determines whether a given C++
7461 /// method overrides a method in a base class, to be used with
7462 /// CXXRecordDecl::lookupInBases().
7463 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7464 RecordDecl *BaseRecord =
7465 Specifier->getType()->getAs<RecordType>()->getDecl();
7467 DeclarationName Name = Method->getDeclName();
7469 // FIXME: Do we care about other names here too?
7470 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7471 // We really want to find the base class destructor here.
7472 QualType T = S->Context.getTypeDeclType(BaseRecord);
7473 CanQualType CT = S->Context.getCanonicalType(T);
7475 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7478 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7479 Path.Decls = Path.Decls.slice(1)) {
7480 NamedDecl *D = Path.Decls.front();
7481 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7482 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7491 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7492 } // end anonymous namespace
7494 /// \brief Report an error regarding overriding, along with any relevant
7495 /// overriden methods.
7497 /// \param DiagID the primary error to report.
7498 /// \param MD the overriding method.
7499 /// \param OEK which overrides to include as notes.
7500 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7501 OverrideErrorKind OEK = OEK_All) {
7502 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7503 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7504 E = MD->end_overridden_methods();
7506 // This check (& the OEK parameter) could be replaced by a predicate, but
7507 // without lambdas that would be overkill. This is still nicer than writing
7508 // out the diag loop 3 times.
7509 if ((OEK == OEK_All) ||
7510 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7511 (OEK == OEK_Deleted && (*I)->isDeleted()))
7512 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7516 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7517 /// and if so, check that it's a valid override and remember it.
7518 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7519 // Look for methods in base classes that this method might override.
7521 FindOverriddenMethod FOM;
7524 bool hasDeletedOverridenMethods = false;
7525 bool hasNonDeletedOverridenMethods = false;
7526 bool AddedAny = false;
7527 if (DC->lookupInBases(FOM, Paths)) {
7528 for (auto *I : Paths.found_decls()) {
7529 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7530 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7531 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7532 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7533 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7534 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7535 hasDeletedOverridenMethods |= OldMD->isDeleted();
7536 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7543 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7544 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7546 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7547 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7554 // Struct for holding all of the extra arguments needed by
7555 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7556 struct ActOnFDArgs {
7559 MultiTemplateParamsArg TemplateParamLists;
7562 } // end anonymous namespace
7566 // Callback to only accept typo corrections that have a non-zero edit distance.
7567 // Also only accept corrections that have the same parent decl.
7568 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7570 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7571 CXXRecordDecl *Parent)
7572 : Context(Context), OriginalFD(TypoFD),
7573 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7575 bool ValidateCandidate(const TypoCorrection &candidate) override {
7576 if (candidate.getEditDistance() == 0)
7579 SmallVector<unsigned, 1> MismatchedParams;
7580 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7581 CDeclEnd = candidate.end();
7582 CDecl != CDeclEnd; ++CDecl) {
7583 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7585 if (FD && !FD->hasBody() &&
7586 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7587 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7588 CXXRecordDecl *Parent = MD->getParent();
7589 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7591 } else if (!ExpectedParent) {
7601 ASTContext &Context;
7602 FunctionDecl *OriginalFD;
7603 CXXRecordDecl *ExpectedParent;
7606 } // end anonymous namespace
7608 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7609 TypoCorrectedFunctionDefinitions.insert(F);
7612 /// \brief Generate diagnostics for an invalid function redeclaration.
7614 /// This routine handles generating the diagnostic messages for an invalid
7615 /// function redeclaration, including finding possible similar declarations
7616 /// or performing typo correction if there are no previous declarations with
7619 /// Returns a NamedDecl iff typo correction was performed and substituting in
7620 /// the new declaration name does not cause new errors.
7621 static NamedDecl *DiagnoseInvalidRedeclaration(
7622 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7623 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7624 DeclarationName Name = NewFD->getDeclName();
7625 DeclContext *NewDC = NewFD->getDeclContext();
7626 SmallVector<unsigned, 1> MismatchedParams;
7627 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7628 TypoCorrection Correction;
7629 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7630 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7631 : diag::err_member_decl_does_not_match;
7632 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7633 IsLocalFriend ? Sema::LookupLocalFriendName
7634 : Sema::LookupOrdinaryName,
7635 Sema::ForRedeclaration);
7637 NewFD->setInvalidDecl();
7639 SemaRef.LookupName(Prev, S);
7641 SemaRef.LookupQualifiedName(Prev, NewDC);
7642 assert(!Prev.isAmbiguous() &&
7643 "Cannot have an ambiguity in previous-declaration lookup");
7644 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7645 if (!Prev.empty()) {
7646 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7647 Func != FuncEnd; ++Func) {
7648 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7650 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7651 // Add 1 to the index so that 0 can mean the mismatch didn't
7652 // involve a parameter
7654 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7655 NearMatches.push_back(std::make_pair(FD, ParamNum));
7658 // If the qualified name lookup yielded nothing, try typo correction
7659 } else if ((Correction = SemaRef.CorrectTypo(
7660 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7661 &ExtraArgs.D.getCXXScopeSpec(),
7662 llvm::make_unique<DifferentNameValidatorCCC>(
7663 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7664 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7665 // Set up everything for the call to ActOnFunctionDeclarator
7666 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7667 ExtraArgs.D.getIdentifierLoc());
7669 Previous.setLookupName(Correction.getCorrection());
7670 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7671 CDeclEnd = Correction.end();
7672 CDecl != CDeclEnd; ++CDecl) {
7673 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7674 if (FD && !FD->hasBody() &&
7675 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7676 Previous.addDecl(FD);
7679 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7682 // Retry building the function declaration with the new previous
7683 // declarations, and with errors suppressed.
7686 Sema::SFINAETrap Trap(SemaRef);
7688 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7689 // pieces need to verify the typo-corrected C++ declaration and hopefully
7690 // eliminate the need for the parameter pack ExtraArgs.
7691 Result = SemaRef.ActOnFunctionDeclarator(
7692 ExtraArgs.S, ExtraArgs.D,
7693 Correction.getCorrectionDecl()->getDeclContext(),
7694 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7695 ExtraArgs.AddToScope);
7697 if (Trap.hasErrorOccurred())
7702 // Determine which correction we picked.
7703 Decl *Canonical = Result->getCanonicalDecl();
7704 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7706 if ((*I)->getCanonicalDecl() == Canonical)
7707 Correction.setCorrectionDecl(*I);
7709 // Let Sema know about the correction.
7710 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7711 SemaRef.diagnoseTypo(
7713 SemaRef.PDiag(IsLocalFriend
7714 ? diag::err_no_matching_local_friend_suggest
7715 : diag::err_member_decl_does_not_match_suggest)
7716 << Name << NewDC << IsDefinition);
7720 // Pretend the typo correction never occurred
7721 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7722 ExtraArgs.D.getIdentifierLoc());
7723 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7725 Previous.setLookupName(Name);
7728 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7729 << Name << NewDC << IsDefinition << NewFD->getLocation();
7731 bool NewFDisConst = false;
7732 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7733 NewFDisConst = NewMD->isConst();
7735 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7736 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7737 NearMatch != NearMatchEnd; ++NearMatch) {
7738 FunctionDecl *FD = NearMatch->first;
7739 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7740 bool FDisConst = MD && MD->isConst();
7741 bool IsMember = MD || !IsLocalFriend;
7743 // FIXME: These notes are poorly worded for the local friend case.
7744 if (unsigned Idx = NearMatch->second) {
7745 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7746 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7747 if (Loc.isInvalid()) Loc = FD->getLocation();
7748 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7749 : diag::note_local_decl_close_param_match)
7750 << Idx << FDParam->getType()
7751 << NewFD->getParamDecl(Idx - 1)->getType();
7752 } else if (FDisConst != NewFDisConst) {
7753 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7754 << NewFDisConst << FD->getSourceRange().getEnd();
7756 SemaRef.Diag(FD->getLocation(),
7757 IsMember ? diag::note_member_def_close_match
7758 : diag::note_local_decl_close_match);
7763 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7764 switch (D.getDeclSpec().getStorageClassSpec()) {
7765 default: llvm_unreachable("Unknown storage class!");
7766 case DeclSpec::SCS_auto:
7767 case DeclSpec::SCS_register:
7768 case DeclSpec::SCS_mutable:
7769 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7770 diag::err_typecheck_sclass_func);
7771 D.getMutableDeclSpec().ClearStorageClassSpecs();
7774 case DeclSpec::SCS_unspecified: break;
7775 case DeclSpec::SCS_extern:
7776 if (D.getDeclSpec().isExternInLinkageSpec())
7779 case DeclSpec::SCS_static: {
7780 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7782 // The declaration of an identifier for a function that has
7783 // block scope shall have no explicit storage-class specifier
7784 // other than extern
7785 // See also (C++ [dcl.stc]p4).
7786 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7787 diag::err_static_block_func);
7792 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7795 // No explicit storage class has already been returned
7799 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7800 DeclContext *DC, QualType &R,
7801 TypeSourceInfo *TInfo,
7803 bool &IsVirtualOkay) {
7804 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7805 DeclarationName Name = NameInfo.getName();
7807 FunctionDecl *NewFD = nullptr;
7808 bool isInline = D.getDeclSpec().isInlineSpecified();
7810 if (!SemaRef.getLangOpts().CPlusPlus) {
7811 // Determine whether the function was written with a
7812 // prototype. This true when:
7813 // - there is a prototype in the declarator, or
7814 // - the type R of the function is some kind of typedef or other non-
7815 // attributed reference to a type name (which eventually refers to a
7818 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7819 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7821 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7822 D.getLocStart(), NameInfo, R,
7823 TInfo, SC, isInline,
7824 HasPrototype, false);
7825 if (D.isInvalidType())
7826 NewFD->setInvalidDecl();
7831 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7832 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7834 // Check that the return type is not an abstract class type.
7835 // For record types, this is done by the AbstractClassUsageDiagnoser once
7836 // the class has been completely parsed.
7837 if (!DC->isRecord() &&
7838 SemaRef.RequireNonAbstractType(
7839 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7840 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7843 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7844 // This is a C++ constructor declaration.
7845 assert(DC->isRecord() &&
7846 "Constructors can only be declared in a member context");
7848 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7849 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7850 D.getLocStart(), NameInfo,
7851 R, TInfo, isExplicit, isInline,
7852 /*isImplicitlyDeclared=*/false,
7855 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7856 // This is a C++ destructor declaration.
7857 if (DC->isRecord()) {
7858 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7859 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7860 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7861 SemaRef.Context, Record,
7863 NameInfo, R, TInfo, isInline,
7864 /*isImplicitlyDeclared=*/false);
7866 // If the class is complete, then we now create the implicit exception
7867 // specification. If the class is incomplete or dependent, we can't do
7869 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7870 Record->getDefinition() && !Record->isBeingDefined() &&
7871 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7872 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7875 IsVirtualOkay = true;
7879 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7882 // Create a FunctionDecl to satisfy the function definition parsing
7884 return FunctionDecl::Create(SemaRef.Context, DC,
7886 D.getIdentifierLoc(), Name, R, TInfo,
7888 /*hasPrototype=*/true, isConstexpr);
7891 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7892 if (!DC->isRecord()) {
7893 SemaRef.Diag(D.getIdentifierLoc(),
7894 diag::err_conv_function_not_member);
7898 SemaRef.CheckConversionDeclarator(D, R, SC);
7899 IsVirtualOkay = true;
7900 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7901 D.getLocStart(), NameInfo,
7902 R, TInfo, isInline, isExplicit,
7903 isConstexpr, SourceLocation());
7905 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7906 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7908 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7909 isExplicit, NameInfo, R, TInfo,
7911 } else if (DC->isRecord()) {
7912 // If the name of the function is the same as the name of the record,
7913 // then this must be an invalid constructor that has a return type.
7914 // (The parser checks for a return type and makes the declarator a
7915 // constructor if it has no return type).
7916 if (Name.getAsIdentifierInfo() &&
7917 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7918 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7919 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7920 << SourceRange(D.getIdentifierLoc());
7924 // This is a C++ method declaration.
7925 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7926 cast<CXXRecordDecl>(DC),
7927 D.getLocStart(), NameInfo, R,
7928 TInfo, SC, isInline,
7929 isConstexpr, SourceLocation());
7930 IsVirtualOkay = !Ret->isStatic();
7934 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7935 if (!isFriend && SemaRef.CurContext->isRecord())
7938 // Determine whether the function was written with a
7939 // prototype. This true when:
7940 // - we're in C++ (where every function has a prototype),
7941 return FunctionDecl::Create(SemaRef.Context, DC,
7943 NameInfo, R, TInfo, SC, isInline,
7944 true/*HasPrototype*/, isConstexpr);
7948 enum OpenCLParamType {
7952 InvalidAddrSpacePtrKernelParam,
7957 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7958 if (PT->isPointerType()) {
7959 QualType PointeeType = PT->getPointeeType();
7960 if (PointeeType->isPointerType())
7961 return PtrPtrKernelParam;
7962 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7963 PointeeType.getAddressSpace() == 0)
7964 return InvalidAddrSpacePtrKernelParam;
7965 return PtrKernelParam;
7968 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7969 // be used as builtin types.
7971 if (PT->isImageType())
7972 return PtrKernelParam;
7974 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
7975 return InvalidKernelParam;
7977 // OpenCL extension spec v1.2 s9.5:
7978 // This extension adds support for half scalar and vector types as built-in
7979 // types that can be used for arithmetic operations, conversions etc.
7980 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7981 return InvalidKernelParam;
7983 if (PT->isRecordType())
7984 return RecordKernelParam;
7986 return ValidKernelParam;
7989 static void checkIsValidOpenCLKernelParameter(
7993 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7994 QualType PT = Param->getType();
7996 // Cache the valid types we encounter to avoid rechecking structs that are
7998 if (ValidTypes.count(PT.getTypePtr()))
8001 switch (getOpenCLKernelParameterType(S, PT)) {
8002 case PtrPtrKernelParam:
8003 // OpenCL v1.2 s6.9.a:
8004 // A kernel function argument cannot be declared as a
8005 // pointer to a pointer type.
8006 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8010 case InvalidAddrSpacePtrKernelParam:
8011 // OpenCL v1.0 s6.5:
8012 // __kernel function arguments declared to be a pointer of a type can point
8013 // to one of the following address spaces only : __global, __local or
8015 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8019 // OpenCL v1.2 s6.9.k:
8020 // Arguments to kernel functions in a program cannot be declared with the
8021 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8022 // uintptr_t or a struct and/or union that contain fields declared to be
8023 // one of these built-in scalar types.
8025 case InvalidKernelParam:
8026 // OpenCL v1.2 s6.8 n:
8027 // A kernel function argument cannot be declared
8029 // Do not diagnose half type since it is diagnosed as invalid argument
8030 // type for any function elsewhere.
8031 if (!PT->isHalfType())
8032 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8036 case PtrKernelParam:
8037 case ValidKernelParam:
8038 ValidTypes.insert(PT.getTypePtr());
8041 case RecordKernelParam:
8045 // Track nested structs we will inspect
8046 SmallVector<const Decl *, 4> VisitStack;
8048 // Track where we are in the nested structs. Items will migrate from
8049 // VisitStack to HistoryStack as we do the DFS for bad field.
8050 SmallVector<const FieldDecl *, 4> HistoryStack;
8051 HistoryStack.push_back(nullptr);
8053 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8054 VisitStack.push_back(PD);
8056 assert(VisitStack.back() && "First decl null?");
8059 const Decl *Next = VisitStack.pop_back_val();
8061 assert(!HistoryStack.empty());
8062 // Found a marker, we have gone up a level
8063 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8064 ValidTypes.insert(Hist->getType().getTypePtr());
8069 // Adds everything except the original parameter declaration (which is not a
8070 // field itself) to the history stack.
8071 const RecordDecl *RD;
8072 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8073 HistoryStack.push_back(Field);
8074 RD = Field->getType()->castAs<RecordType>()->getDecl();
8076 RD = cast<RecordDecl>(Next);
8079 // Add a null marker so we know when we've gone back up a level
8080 VisitStack.push_back(nullptr);
8082 for (const auto *FD : RD->fields()) {
8083 QualType QT = FD->getType();
8085 if (ValidTypes.count(QT.getTypePtr()))
8088 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8089 if (ParamType == ValidKernelParam)
8092 if (ParamType == RecordKernelParam) {
8093 VisitStack.push_back(FD);
8097 // OpenCL v1.2 s6.9.p:
8098 // Arguments to kernel functions that are declared to be a struct or union
8099 // do not allow OpenCL objects to be passed as elements of the struct or
8101 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8102 ParamType == InvalidAddrSpacePtrKernelParam) {
8103 S.Diag(Param->getLocation(),
8104 diag::err_record_with_pointers_kernel_param)
8105 << PT->isUnionType()
8108 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8111 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8112 << PD->getDeclName();
8114 // We have an error, now let's go back up through history and show where
8115 // the offending field came from
8116 for (ArrayRef<const FieldDecl *>::const_iterator
8117 I = HistoryStack.begin() + 1,
8118 E = HistoryStack.end();
8120 const FieldDecl *OuterField = *I;
8121 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8122 << OuterField->getType();
8125 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8126 << QT->isPointerType()
8131 } while (!VisitStack.empty());
8134 /// Find the DeclContext in which a tag is implicitly declared if we see an
8135 /// elaborated type specifier in the specified context, and lookup finds
8137 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8138 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8139 DC = DC->getParent();
8143 /// Find the Scope in which a tag is implicitly declared if we see an
8144 /// elaborated type specifier in the specified context, and lookup finds
8146 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8147 while (S->isClassScope() ||
8148 (LangOpts.CPlusPlus &&
8149 S->isFunctionPrototypeScope()) ||
8150 ((S->getFlags() & Scope::DeclScope) == 0) ||
8151 (S->getEntity() && S->getEntity()->isTransparentContext()))
8157 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8158 TypeSourceInfo *TInfo, LookupResult &Previous,
8159 MultiTemplateParamsArg TemplateParamLists,
8161 QualType R = TInfo->getType();
8163 assert(R.getTypePtr()->isFunctionType());
8165 // TODO: consider using NameInfo for diagnostic.
8166 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8167 DeclarationName Name = NameInfo.getName();
8168 StorageClass SC = getFunctionStorageClass(*this, D);
8170 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8171 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8172 diag::err_invalid_thread)
8173 << DeclSpec::getSpecifierName(TSCS);
8175 if (D.isFirstDeclarationOfMember())
8176 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8177 D.getIdentifierLoc());
8179 bool isFriend = false;
8180 FunctionTemplateDecl *FunctionTemplate = nullptr;
8181 bool isMemberSpecialization = false;
8182 bool isFunctionTemplateSpecialization = false;
8184 bool isDependentClassScopeExplicitSpecialization = false;
8185 bool HasExplicitTemplateArgs = false;
8186 TemplateArgumentListInfo TemplateArgs;
8188 bool isVirtualOkay = false;
8190 DeclContext *OriginalDC = DC;
8191 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8193 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8195 if (!NewFD) return nullptr;
8197 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8198 NewFD->setTopLevelDeclInObjCContainer();
8200 // Set the lexical context. If this is a function-scope declaration, or has a
8201 // C++ scope specifier, or is the object of a friend declaration, the lexical
8202 // context will be different from the semantic context.
8203 NewFD->setLexicalDeclContext(CurContext);
8205 if (IsLocalExternDecl)
8206 NewFD->setLocalExternDecl();
8208 if (getLangOpts().CPlusPlus) {
8209 bool isInline = D.getDeclSpec().isInlineSpecified();
8210 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8211 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8212 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8213 bool isConcept = D.getDeclSpec().isConceptSpecified();
8214 isFriend = D.getDeclSpec().isFriendSpecified();
8215 if (isFriend && !isInline && D.isFunctionDefinition()) {
8216 // C++ [class.friend]p5
8217 // A function can be defined in a friend declaration of a
8218 // class . . . . Such a function is implicitly inline.
8219 NewFD->setImplicitlyInline();
8222 // If this is a method defined in an __interface, and is not a constructor
8223 // or an overloaded operator, then set the pure flag (isVirtual will already
8225 if (const CXXRecordDecl *Parent =
8226 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8227 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8228 NewFD->setPure(true);
8230 // C++ [class.union]p2
8231 // A union can have member functions, but not virtual functions.
8232 if (isVirtual && Parent->isUnion())
8233 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8236 SetNestedNameSpecifier(NewFD, D);
8237 isMemberSpecialization = false;
8238 isFunctionTemplateSpecialization = false;
8239 if (D.isInvalidType())
8240 NewFD->setInvalidDecl();
8242 // Match up the template parameter lists with the scope specifier, then
8243 // determine whether we have a template or a template specialization.
8244 bool Invalid = false;
8245 if (TemplateParameterList *TemplateParams =
8246 MatchTemplateParametersToScopeSpecifier(
8247 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8248 D.getCXXScopeSpec(),
8249 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8250 ? D.getName().TemplateId
8252 TemplateParamLists, isFriend, isMemberSpecialization,
8254 if (TemplateParams->size() > 0) {
8255 // This is a function template
8257 // Check that we can declare a template here.
8258 if (CheckTemplateDeclScope(S, TemplateParams))
8259 NewFD->setInvalidDecl();
8261 // A destructor cannot be a template.
8262 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8263 Diag(NewFD->getLocation(), diag::err_destructor_template);
8264 NewFD->setInvalidDecl();
8267 // If we're adding a template to a dependent context, we may need to
8268 // rebuilding some of the types used within the template parameter list,
8269 // now that we know what the current instantiation is.
8270 if (DC->isDependentContext()) {
8271 ContextRAII SavedContext(*this, DC);
8272 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8276 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8277 NewFD->getLocation(),
8278 Name, TemplateParams,
8280 FunctionTemplate->setLexicalDeclContext(CurContext);
8281 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8283 // For source fidelity, store the other template param lists.
8284 if (TemplateParamLists.size() > 1) {
8285 NewFD->setTemplateParameterListsInfo(Context,
8286 TemplateParamLists.drop_back(1));
8289 // This is a function template specialization.
8290 isFunctionTemplateSpecialization = true;
8291 // For source fidelity, store all the template param lists.
8292 if (TemplateParamLists.size() > 0)
8293 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8295 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8297 // We want to remove the "template<>", found here.
8298 SourceRange RemoveRange = TemplateParams->getSourceRange();
8300 // If we remove the template<> and the name is not a
8301 // template-id, we're actually silently creating a problem:
8302 // the friend declaration will refer to an untemplated decl,
8303 // and clearly the user wants a template specialization. So
8304 // we need to insert '<>' after the name.
8305 SourceLocation InsertLoc;
8306 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8307 InsertLoc = D.getName().getSourceRange().getEnd();
8308 InsertLoc = getLocForEndOfToken(InsertLoc);
8311 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8312 << Name << RemoveRange
8313 << FixItHint::CreateRemoval(RemoveRange)
8314 << FixItHint::CreateInsertion(InsertLoc, "<>");
8319 // All template param lists were matched against the scope specifier:
8320 // this is NOT (an explicit specialization of) a template.
8321 if (TemplateParamLists.size() > 0)
8322 // For source fidelity, store all the template param lists.
8323 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8327 NewFD->setInvalidDecl();
8328 if (FunctionTemplate)
8329 FunctionTemplate->setInvalidDecl();
8332 // C++ [dcl.fct.spec]p5:
8333 // The virtual specifier shall only be used in declarations of
8334 // nonstatic class member functions that appear within a
8335 // member-specification of a class declaration; see 10.3.
8337 if (isVirtual && !NewFD->isInvalidDecl()) {
8338 if (!isVirtualOkay) {
8339 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8340 diag::err_virtual_non_function);
8341 } else if (!CurContext->isRecord()) {
8342 // 'virtual' was specified outside of the class.
8343 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8344 diag::err_virtual_out_of_class)
8345 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8346 } else if (NewFD->getDescribedFunctionTemplate()) {
8347 // C++ [temp.mem]p3:
8348 // A member function template shall not be virtual.
8349 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8350 diag::err_virtual_member_function_template)
8351 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8353 // Okay: Add virtual to the method.
8354 NewFD->setVirtualAsWritten(true);
8357 if (getLangOpts().CPlusPlus14 &&
8358 NewFD->getReturnType()->isUndeducedType())
8359 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8362 if (getLangOpts().CPlusPlus14 &&
8363 (NewFD->isDependentContext() ||
8364 (isFriend && CurContext->isDependentContext())) &&
8365 NewFD->getReturnType()->isUndeducedType()) {
8366 // If the function template is referenced directly (for instance, as a
8367 // member of the current instantiation), pretend it has a dependent type.
8368 // This is not really justified by the standard, but is the only sane
8370 // FIXME: For a friend function, we have not marked the function as being
8371 // a friend yet, so 'isDependentContext' on the FD doesn't work.
8372 const FunctionProtoType *FPT =
8373 NewFD->getType()->castAs<FunctionProtoType>();
8375 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8376 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8377 FPT->getExtProtoInfo()));
8380 // C++ [dcl.fct.spec]p3:
8381 // The inline specifier shall not appear on a block scope function
8383 if (isInline && !NewFD->isInvalidDecl()) {
8384 if (CurContext->isFunctionOrMethod()) {
8385 // 'inline' is not allowed on block scope function declaration.
8386 Diag(D.getDeclSpec().getInlineSpecLoc(),
8387 diag::err_inline_declaration_block_scope) << Name
8388 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8392 // C++ [dcl.fct.spec]p6:
8393 // The explicit specifier shall be used only in the declaration of a
8394 // constructor or conversion function within its class definition;
8395 // see 12.3.1 and 12.3.2.
8396 if (isExplicit && !NewFD->isInvalidDecl() &&
8397 !isa<CXXDeductionGuideDecl>(NewFD)) {
8398 if (!CurContext->isRecord()) {
8399 // 'explicit' was specified outside of the class.
8400 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8401 diag::err_explicit_out_of_class)
8402 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8403 } else if (!isa<CXXConstructorDecl>(NewFD) &&
8404 !isa<CXXConversionDecl>(NewFD)) {
8405 // 'explicit' was specified on a function that wasn't a constructor
8406 // or conversion function.
8407 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8408 diag::err_explicit_non_ctor_or_conv_function)
8409 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8414 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8415 // are implicitly inline.
8416 NewFD->setImplicitlyInline();
8418 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8419 // be either constructors or to return a literal type. Therefore,
8420 // destructors cannot be declared constexpr.
8421 if (isa<CXXDestructorDecl>(NewFD))
8422 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8426 // This is a function concept.
8427 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8430 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8431 // applied only to the definition of a function template [...]
8432 if (!D.isFunctionDefinition()) {
8433 Diag(D.getDeclSpec().getConceptSpecLoc(),
8434 diag::err_function_concept_not_defined);
8435 NewFD->setInvalidDecl();
8438 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8439 // have no exception-specification and is treated as if it were specified
8440 // with noexcept(true) (15.4). [...]
8441 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8442 if (FPT->hasExceptionSpec()) {
8444 if (D.isFunctionDeclarator())
8445 Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8446 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8447 << FixItHint::CreateRemoval(Range);
8448 NewFD->setInvalidDecl();
8450 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8453 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8454 // following restrictions:
8455 // - The declared return type shall have the type bool.
8456 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8457 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8458 NewFD->setInvalidDecl();
8461 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8462 // following restrictions:
8463 // - The declaration's parameter list shall be equivalent to an empty
8465 if (FPT->getNumParams() > 0 || FPT->isVariadic())
8466 Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8469 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8470 // implicity defined to be a constexpr declaration (implicitly inline)
8471 NewFD->setImplicitlyInline();
8473 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8474 // be declared with the thread_local, inline, friend, or constexpr
8475 // specifiers, [...]
8477 Diag(D.getDeclSpec().getInlineSpecLoc(),
8478 diag::err_concept_decl_invalid_specifiers)
8480 NewFD->setInvalidDecl(true);
8484 Diag(D.getDeclSpec().getFriendSpecLoc(),
8485 diag::err_concept_decl_invalid_specifiers)
8487 NewFD->setInvalidDecl(true);
8491 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8492 diag::err_concept_decl_invalid_specifiers)
8494 NewFD->setInvalidDecl(true);
8497 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8498 // applied only to the definition of a function template or variable
8499 // template, declared in namespace scope.
8500 if (isFunctionTemplateSpecialization) {
8501 Diag(D.getDeclSpec().getConceptSpecLoc(),
8502 diag::err_concept_specified_specialization) << 1;
8503 NewFD->setInvalidDecl(true);
8508 // If __module_private__ was specified, mark the function accordingly.
8509 if (D.getDeclSpec().isModulePrivateSpecified()) {
8510 if (isFunctionTemplateSpecialization) {
8511 SourceLocation ModulePrivateLoc
8512 = D.getDeclSpec().getModulePrivateSpecLoc();
8513 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8515 << FixItHint::CreateRemoval(ModulePrivateLoc);
8517 NewFD->setModulePrivate();
8518 if (FunctionTemplate)
8519 FunctionTemplate->setModulePrivate();
8524 if (FunctionTemplate) {
8525 FunctionTemplate->setObjectOfFriendDecl();
8526 FunctionTemplate->setAccess(AS_public);
8528 NewFD->setObjectOfFriendDecl();
8529 NewFD->setAccess(AS_public);
8532 // If a function is defined as defaulted or deleted, mark it as such now.
8533 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8534 // definition kind to FDK_Definition.
8535 switch (D.getFunctionDefinitionKind()) {
8536 case FDK_Declaration:
8537 case FDK_Definition:
8541 NewFD->setDefaulted();
8545 NewFD->setDeletedAsWritten();
8549 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8550 D.isFunctionDefinition()) {
8551 // C++ [class.mfct]p2:
8552 // A member function may be defined (8.4) in its class definition, in
8553 // which case it is an inline member function (7.1.2)
8554 NewFD->setImplicitlyInline();
8557 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8558 !CurContext->isRecord()) {
8559 // C++ [class.static]p1:
8560 // A data or function member of a class may be declared static
8561 // in a class definition, in which case it is a static member of
8564 // Complain about the 'static' specifier if it's on an out-of-line
8565 // member function definition.
8566 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8567 diag::err_static_out_of_line)
8568 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8571 // C++11 [except.spec]p15:
8572 // A deallocation function with no exception-specification is treated
8573 // as if it were specified with noexcept(true).
8574 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8575 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8576 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8577 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8578 NewFD->setType(Context.getFunctionType(
8579 FPT->getReturnType(), FPT->getParamTypes(),
8580 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8583 // Filter out previous declarations that don't match the scope.
8584 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8585 D.getCXXScopeSpec().isNotEmpty() ||
8586 isMemberSpecialization ||
8587 isFunctionTemplateSpecialization);
8589 // Handle GNU asm-label extension (encoded as an attribute).
8590 if (Expr *E = (Expr*) D.getAsmLabel()) {
8591 // The parser guarantees this is a string.
8592 StringLiteral *SE = cast<StringLiteral>(E);
8593 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8594 SE->getString(), 0));
8595 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8596 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8597 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8598 if (I != ExtnameUndeclaredIdentifiers.end()) {
8599 if (isDeclExternC(NewFD)) {
8600 NewFD->addAttr(I->second);
8601 ExtnameUndeclaredIdentifiers.erase(I);
8603 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8604 << /*Variable*/0 << NewFD;
8608 // Copy the parameter declarations from the declarator D to the function
8609 // declaration NewFD, if they are available. First scavenge them into Params.
8610 SmallVector<ParmVarDecl*, 16> Params;
8612 if (D.isFunctionDeclarator(FTIIdx)) {
8613 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8615 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8616 // function that takes no arguments, not a function that takes a
8617 // single void argument.
8618 // We let through "const void" here because Sema::GetTypeForDeclarator
8619 // already checks for that case.
8620 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8621 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8622 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8623 assert(Param->getDeclContext() != NewFD && "Was set before ?");
8624 Param->setDeclContext(NewFD);
8625 Params.push_back(Param);
8627 if (Param->isInvalidDecl())
8628 NewFD->setInvalidDecl();
8632 if (!getLangOpts().CPlusPlus) {
8633 // In C, find all the tag declarations from the prototype and move them
8634 // into the function DeclContext. Remove them from the surrounding tag
8635 // injection context of the function, which is typically but not always
8637 DeclContext *PrototypeTagContext =
8638 getTagInjectionContext(NewFD->getLexicalDeclContext());
8639 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8640 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8642 // We don't want to reparent enumerators. Look at their parent enum
8645 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8646 TD = cast<EnumDecl>(ECD->getDeclContext());
8650 DeclContext *TagDC = TD->getLexicalDeclContext();
8651 if (!TagDC->containsDecl(TD))
8653 TagDC->removeDecl(TD);
8654 TD->setDeclContext(NewFD);
8657 // Preserve the lexical DeclContext if it is not the surrounding tag
8658 // injection context of the FD. In this example, the semantic context of
8659 // E will be f and the lexical context will be S, while both the
8660 // semantic and lexical contexts of S will be f:
8661 // void f(struct S { enum E { a } f; } s);
8662 if (TagDC != PrototypeTagContext)
8663 TD->setLexicalDeclContext(TagDC);
8666 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8667 // When we're declaring a function with a typedef, typeof, etc as in the
8668 // following example, we'll need to synthesize (unnamed)
8669 // parameters for use in the declaration.
8672 // typedef void fn(int);
8676 // Synthesize a parameter for each argument type.
8677 for (const auto &AI : FT->param_types()) {
8678 ParmVarDecl *Param =
8679 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8680 Param->setScopeInfo(0, Params.size());
8681 Params.push_back(Param);
8684 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8685 "Should not need args for typedef of non-prototype fn");
8688 // Finally, we know we have the right number of parameters, install them.
8689 NewFD->setParams(Params);
8691 if (D.getDeclSpec().isNoreturnSpecified())
8693 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8696 // Functions returning a variably modified type violate C99 6.7.5.2p2
8697 // because all functions have linkage.
8698 if (!NewFD->isInvalidDecl() &&
8699 NewFD->getReturnType()->isVariablyModifiedType()) {
8700 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8701 NewFD->setInvalidDecl();
8704 // Apply an implicit SectionAttr if '#pragma clang section text' is active
8705 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8706 !NewFD->hasAttr<SectionAttr>()) {
8707 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8708 PragmaClangTextSection.SectionName,
8709 PragmaClangTextSection.PragmaLocation));
8712 // Apply an implicit SectionAttr if #pragma code_seg is active.
8713 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8714 !NewFD->hasAttr<SectionAttr>()) {
8716 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8717 CodeSegStack.CurrentValue->getString(),
8718 CodeSegStack.CurrentPragmaLocation));
8719 if (UnifySection(CodeSegStack.CurrentValue->getString(),
8720 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8721 ASTContext::PSF_Read,
8723 NewFD->dropAttr<SectionAttr>();
8726 // Handle attributes.
8727 ProcessDeclAttributes(S, NewFD, D);
8729 if (getLangOpts().OpenCL) {
8730 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8731 // type declaration will generate a compilation error.
8732 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8733 if (AddressSpace == LangAS::opencl_local ||
8734 AddressSpace == LangAS::opencl_global ||
8735 AddressSpace == LangAS::opencl_constant) {
8736 Diag(NewFD->getLocation(),
8737 diag::err_opencl_return_value_with_address_space);
8738 NewFD->setInvalidDecl();
8742 if (!getLangOpts().CPlusPlus) {
8743 // Perform semantic checking on the function declaration.
8744 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8745 CheckMain(NewFD, D.getDeclSpec());
8747 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8748 CheckMSVCRTEntryPoint(NewFD);
8750 if (!NewFD->isInvalidDecl())
8751 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8752 isMemberSpecialization));
8753 else if (!Previous.empty())
8754 // Recover gracefully from an invalid redeclaration.
8755 D.setRedeclaration(true);
8756 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8757 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8758 "previous declaration set still overloaded");
8760 // Diagnose no-prototype function declarations with calling conventions that
8761 // don't support variadic calls. Only do this in C and do it after merging
8762 // possibly prototyped redeclarations.
8763 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8764 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8765 CallingConv CC = FT->getExtInfo().getCC();
8766 if (!supportsVariadicCall(CC)) {
8767 // Windows system headers sometimes accidentally use stdcall without
8768 // (void) parameters, so we relax this to a warning.
8770 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8771 Diag(NewFD->getLocation(), DiagID)
8772 << FunctionType::getNameForCallConv(CC);
8776 // C++11 [replacement.functions]p3:
8777 // The program's definitions shall not be specified as inline.
8779 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8781 // Suppress the diagnostic if the function is __attribute__((used)), since
8782 // that forces an external definition to be emitted.
8783 if (D.getDeclSpec().isInlineSpecified() &&
8784 NewFD->isReplaceableGlobalAllocationFunction() &&
8785 !NewFD->hasAttr<UsedAttr>())
8786 Diag(D.getDeclSpec().getInlineSpecLoc(),
8787 diag::ext_operator_new_delete_declared_inline)
8788 << NewFD->getDeclName();
8790 // If the declarator is a template-id, translate the parser's template
8791 // argument list into our AST format.
8792 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8793 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8794 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8795 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8796 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8797 TemplateId->NumArgs);
8798 translateTemplateArguments(TemplateArgsPtr,
8801 HasExplicitTemplateArgs = true;
8803 if (NewFD->isInvalidDecl()) {
8804 HasExplicitTemplateArgs = false;
8805 } else if (FunctionTemplate) {
8806 // Function template with explicit template arguments.
8807 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8808 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8810 HasExplicitTemplateArgs = false;
8812 assert((isFunctionTemplateSpecialization ||
8813 D.getDeclSpec().isFriendSpecified()) &&
8814 "should have a 'template<>' for this decl");
8815 // "friend void foo<>(int);" is an implicit specialization decl.
8816 isFunctionTemplateSpecialization = true;
8818 } else if (isFriend && isFunctionTemplateSpecialization) {
8819 // This combination is only possible in a recovery case; the user
8820 // wrote something like:
8821 // template <> friend void foo(int);
8822 // which we're recovering from as if the user had written:
8823 // friend void foo<>(int);
8824 // Go ahead and fake up a template id.
8825 HasExplicitTemplateArgs = true;
8826 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8827 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8830 // We do not add HD attributes to specializations here because
8831 // they may have different constexpr-ness compared to their
8832 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8833 // may end up with different effective targets. Instead, a
8834 // specialization inherits its target attributes from its template
8835 // in the CheckFunctionTemplateSpecialization() call below.
8836 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8837 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8839 // If it's a friend (and only if it's a friend), it's possible
8840 // that either the specialized function type or the specialized
8841 // template is dependent, and therefore matching will fail. In
8842 // this case, don't check the specialization yet.
8843 bool InstantiationDependent = false;
8844 if (isFunctionTemplateSpecialization && isFriend &&
8845 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8846 TemplateSpecializationType::anyDependentTemplateArguments(
8848 InstantiationDependent))) {
8849 assert(HasExplicitTemplateArgs &&
8850 "friend function specialization without template args");
8851 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8853 NewFD->setInvalidDecl();
8854 } else if (isFunctionTemplateSpecialization) {
8855 if (CurContext->isDependentContext() && CurContext->isRecord()
8857 isDependentClassScopeExplicitSpecialization = true;
8858 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8859 diag::ext_function_specialization_in_class :
8860 diag::err_function_specialization_in_class)
8861 << NewFD->getDeclName();
8862 } else if (CheckFunctionTemplateSpecialization(NewFD,
8863 (HasExplicitTemplateArgs ? &TemplateArgs
8866 NewFD->setInvalidDecl();
8869 // A storage-class-specifier shall not be specified in an explicit
8870 // specialization (14.7.3)
8871 FunctionTemplateSpecializationInfo *Info =
8872 NewFD->getTemplateSpecializationInfo();
8873 if (Info && SC != SC_None) {
8874 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8875 Diag(NewFD->getLocation(),
8876 diag::err_explicit_specialization_inconsistent_storage_class)
8878 << FixItHint::CreateRemoval(
8879 D.getDeclSpec().getStorageClassSpecLoc());
8882 Diag(NewFD->getLocation(),
8883 diag::ext_explicit_specialization_storage_class)
8884 << FixItHint::CreateRemoval(
8885 D.getDeclSpec().getStorageClassSpecLoc());
8887 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8888 if (CheckMemberSpecialization(NewFD, Previous))
8889 NewFD->setInvalidDecl();
8892 // Perform semantic checking on the function declaration.
8893 if (!isDependentClassScopeExplicitSpecialization) {
8894 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8895 CheckMain(NewFD, D.getDeclSpec());
8897 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8898 CheckMSVCRTEntryPoint(NewFD);
8900 if (!NewFD->isInvalidDecl())
8901 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8902 isMemberSpecialization));
8903 else if (!Previous.empty())
8904 // Recover gracefully from an invalid redeclaration.
8905 D.setRedeclaration(true);
8908 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8909 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8910 "previous declaration set still overloaded");
8912 NamedDecl *PrincipalDecl = (FunctionTemplate
8913 ? cast<NamedDecl>(FunctionTemplate)
8916 if (isFriend && NewFD->getPreviousDecl()) {
8917 AccessSpecifier Access = AS_public;
8918 if (!NewFD->isInvalidDecl())
8919 Access = NewFD->getPreviousDecl()->getAccess();
8921 NewFD->setAccess(Access);
8922 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8925 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8926 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8927 PrincipalDecl->setNonMemberOperator();
8929 // If we have a function template, check the template parameter
8930 // list. This will check and merge default template arguments.
8931 if (FunctionTemplate) {
8932 FunctionTemplateDecl *PrevTemplate =
8933 FunctionTemplate->getPreviousDecl();
8934 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8935 PrevTemplate ? PrevTemplate->getTemplateParameters()
8937 D.getDeclSpec().isFriendSpecified()
8938 ? (D.isFunctionDefinition()
8939 ? TPC_FriendFunctionTemplateDefinition
8940 : TPC_FriendFunctionTemplate)
8941 : (D.getCXXScopeSpec().isSet() &&
8942 DC && DC->isRecord() &&
8943 DC->isDependentContext())
8944 ? TPC_ClassTemplateMember
8945 : TPC_FunctionTemplate);
8948 if (NewFD->isInvalidDecl()) {
8949 // Ignore all the rest of this.
8950 } else if (!D.isRedeclaration()) {
8951 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8953 // Fake up an access specifier if it's supposed to be a class member.
8954 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8955 NewFD->setAccess(AS_public);
8957 // Qualified decls generally require a previous declaration.
8958 if (D.getCXXScopeSpec().isSet()) {
8959 // ...with the major exception of templated-scope or
8960 // dependent-scope friend declarations.
8962 // TODO: we currently also suppress this check in dependent
8963 // contexts because (1) the parameter depth will be off when
8964 // matching friend templates and (2) we might actually be
8965 // selecting a friend based on a dependent factor. But there
8966 // are situations where these conditions don't apply and we
8967 // can actually do this check immediately.
8969 (TemplateParamLists.size() ||
8970 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8971 CurContext->isDependentContext())) {
8974 // The user tried to provide an out-of-line definition for a
8975 // function that is a member of a class or namespace, but there
8976 // was no such member function declared (C++ [class.mfct]p2,
8977 // C++ [namespace.memdef]p2). For example:
8983 // void X::f() { } // ill-formed
8985 // Complain about this problem, and attempt to suggest close
8986 // matches (e.g., those that differ only in cv-qualifiers and
8987 // whether the parameter types are references).
8989 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8990 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8991 AddToScope = ExtraArgs.AddToScope;
8996 // Unqualified local friend declarations are required to resolve
8998 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8999 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9000 *this, Previous, NewFD, ExtraArgs, true, S)) {
9001 AddToScope = ExtraArgs.AddToScope;
9005 } else if (!D.isFunctionDefinition() &&
9006 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9007 !isFriend && !isFunctionTemplateSpecialization &&
9008 !isMemberSpecialization) {
9009 // An out-of-line member function declaration must also be a
9010 // definition (C++ [class.mfct]p2).
9011 // Note that this is not the case for explicit specializations of
9012 // function templates or member functions of class templates, per
9013 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9014 // extension for compatibility with old SWIG code which likes to
9016 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9017 << D.getCXXScopeSpec().getRange();
9021 ProcessPragmaWeak(S, NewFD);
9022 checkAttributesAfterMerging(*this, *NewFD);
9024 AddKnownFunctionAttributes(NewFD);
9026 if (NewFD->hasAttr<OverloadableAttr>() &&
9027 !NewFD->getType()->getAs<FunctionProtoType>()) {
9028 Diag(NewFD->getLocation(),
9029 diag::err_attribute_overloadable_no_prototype)
9032 // Turn this into a variadic function with no parameters.
9033 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9034 FunctionProtoType::ExtProtoInfo EPI(
9035 Context.getDefaultCallingConvention(true, false));
9036 EPI.Variadic = true;
9037 EPI.ExtInfo = FT->getExtInfo();
9039 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9043 // If there's a #pragma GCC visibility in scope, and this isn't a class
9044 // member, set the visibility of this function.
9045 if (!DC->isRecord() && NewFD->isExternallyVisible())
9046 AddPushedVisibilityAttribute(NewFD);
9048 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9049 // marking the function.
9050 AddCFAuditedAttribute(NewFD);
9052 // If this is a function definition, check if we have to apply optnone due to
9054 if(D.isFunctionDefinition())
9055 AddRangeBasedOptnone(NewFD);
9057 // If this is the first declaration of an extern C variable, update
9058 // the map of such variables.
9059 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9060 isIncompleteDeclExternC(*this, NewFD))
9061 RegisterLocallyScopedExternCDecl(NewFD, S);
9063 // Set this FunctionDecl's range up to the right paren.
9064 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9066 if (D.isRedeclaration() && !Previous.empty()) {
9067 checkDLLAttributeRedeclaration(
9068 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9069 isMemberSpecialization || isFunctionTemplateSpecialization,
9070 D.isFunctionDefinition());
9073 if (getLangOpts().CUDA) {
9074 IdentifierInfo *II = NewFD->getIdentifier();
9075 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9076 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9077 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9078 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9080 Context.setcudaConfigureCallDecl(NewFD);
9083 // Variadic functions, other than a *declaration* of printf, are not allowed
9084 // in device-side CUDA code, unless someone passed
9085 // -fcuda-allow-variadic-functions.
9086 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9087 (NewFD->hasAttr<CUDADeviceAttr>() ||
9088 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9089 !(II && II->isStr("printf") && NewFD->isExternC() &&
9090 !D.isFunctionDefinition())) {
9091 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9095 MarkUnusedFileScopedDecl(NewFD);
9097 if (getLangOpts().CPlusPlus) {
9098 if (FunctionTemplate) {
9099 if (NewFD->isInvalidDecl())
9100 FunctionTemplate->setInvalidDecl();
9101 return FunctionTemplate;
9104 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9105 CompleteMemberSpecialization(NewFD, Previous);
9108 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9109 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9110 if ((getLangOpts().OpenCLVersion >= 120)
9111 && (SC == SC_Static)) {
9112 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9116 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9117 if (!NewFD->getReturnType()->isVoidType()) {
9118 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9119 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9120 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9125 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9126 for (auto Param : NewFD->parameters())
9127 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9129 for (const ParmVarDecl *Param : NewFD->parameters()) {
9130 QualType PT = Param->getType();
9132 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9134 if (getLangOpts().OpenCLVersion >= 200) {
9135 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9136 QualType ElemTy = PipeTy->getElementType();
9137 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9138 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9145 // Here we have an function template explicit specialization at class scope.
9146 // The actually specialization will be postponed to template instatiation
9147 // time via the ClassScopeFunctionSpecializationDecl node.
9148 if (isDependentClassScopeExplicitSpecialization) {
9149 ClassScopeFunctionSpecializationDecl *NewSpec =
9150 ClassScopeFunctionSpecializationDecl::Create(
9151 Context, CurContext, SourceLocation(),
9152 cast<CXXMethodDecl>(NewFD),
9153 HasExplicitTemplateArgs, TemplateArgs);
9154 CurContext->addDecl(NewSpec);
9161 /// \brief Checks if the new declaration declared in dependent context must be
9162 /// put in the same redeclaration chain as the specified declaration.
9164 /// \param D Declaration that is checked.
9165 /// \param PrevDecl Previous declaration found with proper lookup method for the
9166 /// same declaration name.
9167 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9170 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9171 // Any declarations should be put into redeclaration chains except for
9172 // friend declaration in a dependent context that names a function in
9175 // This allows to compile code like:
9178 // template<typename T> class C1 { friend void func() { } };
9179 // template<typename T> class C2 { friend void func() { } };
9181 // This code snippet is a valid code unless both templates are instantiated.
9182 return !(D->getLexicalDeclContext()->isDependentContext() &&
9183 D->getDeclContext()->isFileContext() &&
9184 D->getFriendObjectKind() != Decl::FOK_None);
9187 /// \brief Perform semantic checking of a new function declaration.
9189 /// Performs semantic analysis of the new function declaration
9190 /// NewFD. This routine performs all semantic checking that does not
9191 /// require the actual declarator involved in the declaration, and is
9192 /// used both for the declaration of functions as they are parsed
9193 /// (called via ActOnDeclarator) and for the declaration of functions
9194 /// that have been instantiated via C++ template instantiation (called
9195 /// via InstantiateDecl).
9197 /// \param IsMemberSpecialization whether this new function declaration is
9198 /// a member specialization (that replaces any definition provided by the
9199 /// previous declaration).
9201 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9203 /// \returns true if the function declaration is a redeclaration.
9204 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9205 LookupResult &Previous,
9206 bool IsMemberSpecialization) {
9207 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9208 "Variably modified return types are not handled here");
9210 // Determine whether the type of this function should be merged with
9211 // a previous visible declaration. This never happens for functions in C++,
9212 // and always happens in C if the previous declaration was visible.
9213 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9214 !Previous.isShadowed();
9216 bool Redeclaration = false;
9217 NamedDecl *OldDecl = nullptr;
9218 bool MayNeedOverloadableChecks = false;
9220 // Merge or overload the declaration with an existing declaration of
9221 // the same name, if appropriate.
9222 if (!Previous.empty()) {
9223 // Determine whether NewFD is an overload of PrevDecl or
9224 // a declaration that requires merging. If it's an overload,
9225 // there's no more work to do here; we'll just add the new
9226 // function to the scope.
9227 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9228 NamedDecl *Candidate = Previous.getRepresentativeDecl();
9229 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9230 Redeclaration = true;
9231 OldDecl = Candidate;
9234 MayNeedOverloadableChecks = true;
9235 switch (CheckOverload(S, NewFD, Previous, OldDecl,
9236 /*NewIsUsingDecl*/ false)) {
9238 Redeclaration = true;
9241 case Ovl_NonFunction:
9242 Redeclaration = true;
9246 Redeclaration = false;
9252 // Check for a previous extern "C" declaration with this name.
9253 if (!Redeclaration &&
9254 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9255 if (!Previous.empty()) {
9256 // This is an extern "C" declaration with the same name as a previous
9257 // declaration, and thus redeclares that entity...
9258 Redeclaration = true;
9259 OldDecl = Previous.getFoundDecl();
9260 MergeTypeWithPrevious = false;
9262 // ... except in the presence of __attribute__((overloadable)).
9263 if (OldDecl->hasAttr<OverloadableAttr>() ||
9264 NewFD->hasAttr<OverloadableAttr>()) {
9265 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9266 MayNeedOverloadableChecks = true;
9267 Redeclaration = false;
9274 // C++11 [dcl.constexpr]p8:
9275 // A constexpr specifier for a non-static member function that is not
9276 // a constructor declares that member function to be const.
9278 // This needs to be delayed until we know whether this is an out-of-line
9279 // definition of a static member function.
9281 // This rule is not present in C++1y, so we produce a backwards
9282 // compatibility warning whenever it happens in C++11.
9283 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9284 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9285 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9286 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9287 CXXMethodDecl *OldMD = nullptr;
9289 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9290 if (!OldMD || !OldMD->isStatic()) {
9291 const FunctionProtoType *FPT =
9292 MD->getType()->castAs<FunctionProtoType>();
9293 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9294 EPI.TypeQuals |= Qualifiers::Const;
9295 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9296 FPT->getParamTypes(), EPI));
9298 // Warn that we did this, if we're not performing template instantiation.
9299 // In that case, we'll have warned already when the template was defined.
9300 if (!inTemplateInstantiation()) {
9301 SourceLocation AddConstLoc;
9302 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9303 .IgnoreParens().getAs<FunctionTypeLoc>())
9304 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9306 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9307 << FixItHint::CreateInsertion(AddConstLoc, " const");
9312 if (Redeclaration) {
9313 // NewFD and OldDecl represent declarations that need to be
9315 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9316 NewFD->setInvalidDecl();
9317 return Redeclaration;
9321 Previous.addDecl(OldDecl);
9323 if (FunctionTemplateDecl *OldTemplateDecl
9324 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9325 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9326 FunctionTemplateDecl *NewTemplateDecl
9327 = NewFD->getDescribedFunctionTemplate();
9328 assert(NewTemplateDecl && "Template/non-template mismatch");
9329 if (CXXMethodDecl *Method
9330 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9331 Method->setAccess(OldTemplateDecl->getAccess());
9332 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9335 // If this is an explicit specialization of a member that is a function
9336 // template, mark it as a member specialization.
9337 if (IsMemberSpecialization &&
9338 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9339 NewTemplateDecl->setMemberSpecialization();
9340 assert(OldTemplateDecl->isMemberSpecialization());
9341 // Explicit specializations of a member template do not inherit deleted
9342 // status from the parent member template that they are specializing.
9343 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9344 FunctionDecl *const OldTemplatedDecl =
9345 OldTemplateDecl->getTemplatedDecl();
9346 // FIXME: This assert will not hold in the presence of modules.
9347 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9348 // FIXME: We need an update record for this AST mutation.
9349 OldTemplatedDecl->setDeletedAsWritten(false);
9354 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9355 // This needs to happen first so that 'inline' propagates.
9356 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9357 if (isa<CXXMethodDecl>(NewFD))
9358 NewFD->setAccess(OldDecl->getAccess());
9361 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9362 !NewFD->getAttr<OverloadableAttr>()) {
9363 assert((Previous.empty() ||
9364 llvm::any_of(Previous,
9365 [](const NamedDecl *ND) {
9366 return ND->hasAttr<OverloadableAttr>();
9368 "Non-redecls shouldn't happen without overloadable present");
9370 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9371 const auto *FD = dyn_cast<FunctionDecl>(ND);
9372 return FD && !FD->hasAttr<OverloadableAttr>();
9375 if (OtherUnmarkedIter != Previous.end()) {
9376 Diag(NewFD->getLocation(),
9377 diag::err_attribute_overloadable_multiple_unmarked_overloads);
9378 Diag((*OtherUnmarkedIter)->getLocation(),
9379 diag::note_attribute_overloadable_prev_overload)
9382 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9386 // Semantic checking for this function declaration (in isolation).
9388 if (getLangOpts().CPlusPlus) {
9389 // C++-specific checks.
9390 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9391 CheckConstructor(Constructor);
9392 } else if (CXXDestructorDecl *Destructor =
9393 dyn_cast<CXXDestructorDecl>(NewFD)) {
9394 CXXRecordDecl *Record = Destructor->getParent();
9395 QualType ClassType = Context.getTypeDeclType(Record);
9397 // FIXME: Shouldn't we be able to perform this check even when the class
9398 // type is dependent? Both gcc and edg can handle that.
9399 if (!ClassType->isDependentType()) {
9400 DeclarationName Name
9401 = Context.DeclarationNames.getCXXDestructorName(
9402 Context.getCanonicalType(ClassType));
9403 if (NewFD->getDeclName() != Name) {
9404 Diag(NewFD->getLocation(), diag::err_destructor_name);
9405 NewFD->setInvalidDecl();
9406 return Redeclaration;
9409 } else if (CXXConversionDecl *Conversion
9410 = dyn_cast<CXXConversionDecl>(NewFD)) {
9411 ActOnConversionDeclarator(Conversion);
9412 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9413 if (auto *TD = Guide->getDescribedFunctionTemplate())
9414 CheckDeductionGuideTemplate(TD);
9416 // A deduction guide is not on the list of entities that can be
9417 // explicitly specialized.
9418 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9419 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9420 << /*explicit specialization*/ 1;
9423 // Find any virtual functions that this function overrides.
9424 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9425 if (!Method->isFunctionTemplateSpecialization() &&
9426 !Method->getDescribedFunctionTemplate() &&
9427 Method->isCanonicalDecl()) {
9428 if (AddOverriddenMethods(Method->getParent(), Method)) {
9429 // If the function was marked as "static", we have a problem.
9430 if (NewFD->getStorageClass() == SC_Static) {
9431 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9436 if (Method->isStatic())
9437 checkThisInStaticMemberFunctionType(Method);
9440 // Extra checking for C++ overloaded operators (C++ [over.oper]).
9441 if (NewFD->isOverloadedOperator() &&
9442 CheckOverloadedOperatorDeclaration(NewFD)) {
9443 NewFD->setInvalidDecl();
9444 return Redeclaration;
9447 // Extra checking for C++0x literal operators (C++0x [over.literal]).
9448 if (NewFD->getLiteralIdentifier() &&
9449 CheckLiteralOperatorDeclaration(NewFD)) {
9450 NewFD->setInvalidDecl();
9451 return Redeclaration;
9454 // In C++, check default arguments now that we have merged decls. Unless
9455 // the lexical context is the class, because in this case this is done
9456 // during delayed parsing anyway.
9457 if (!CurContext->isRecord())
9458 CheckCXXDefaultArguments(NewFD);
9460 // If this function declares a builtin function, check the type of this
9461 // declaration against the expected type for the builtin.
9462 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9463 ASTContext::GetBuiltinTypeError Error;
9464 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9465 QualType T = Context.GetBuiltinType(BuiltinID, Error);
9466 // If the type of the builtin differs only in its exception
9467 // specification, that's OK.
9468 // FIXME: If the types do differ in this way, it would be better to
9469 // retain the 'noexcept' form of the type.
9471 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9473 // The type of this function differs from the type of the builtin,
9474 // so forget about the builtin entirely.
9475 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9478 // If this function is declared as being extern "C", then check to see if
9479 // the function returns a UDT (class, struct, or union type) that is not C
9480 // compatible, and if it does, warn the user.
9481 // But, issue any diagnostic on the first declaration only.
9482 if (Previous.empty() && NewFD->isExternC()) {
9483 QualType R = NewFD->getReturnType();
9484 if (R->isIncompleteType() && !R->isVoidType())
9485 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9487 else if (!R.isPODType(Context) && !R->isVoidType() &&
9488 !R->isObjCObjectPointerType())
9489 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9492 // C++1z [dcl.fct]p6:
9493 // [...] whether the function has a non-throwing exception-specification
9494 // [is] part of the function type
9496 // This results in an ABI break between C++14 and C++17 for functions whose
9497 // declared type includes an exception-specification in a parameter or
9498 // return type. (Exception specifications on the function itself are OK in
9499 // most cases, and exception specifications are not permitted in most other
9500 // contexts where they could make it into a mangling.)
9501 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9502 auto HasNoexcept = [&](QualType T) -> bool {
9503 // Strip off declarator chunks that could be between us and a function
9504 // type. We don't need to look far, exception specifications are very
9505 // restricted prior to C++17.
9506 if (auto *RT = T->getAs<ReferenceType>())
9507 T = RT->getPointeeType();
9508 else if (T->isAnyPointerType())
9509 T = T->getPointeeType();
9510 else if (auto *MPT = T->getAs<MemberPointerType>())
9511 T = MPT->getPointeeType();
9512 if (auto *FPT = T->getAs<FunctionProtoType>())
9513 if (FPT->isNothrow(Context))
9518 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9519 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9520 for (QualType T : FPT->param_types())
9521 AnyNoexcept |= HasNoexcept(T);
9523 Diag(NewFD->getLocation(),
9524 diag::warn_cxx1z_compat_exception_spec_in_signature)
9528 if (!Redeclaration && LangOpts.CUDA)
9529 checkCUDATargetOverload(NewFD, Previous);
9531 return Redeclaration;
9534 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9535 // C++11 [basic.start.main]p3:
9536 // A program that [...] declares main to be inline, static or
9537 // constexpr is ill-formed.
9538 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
9539 // appear in a declaration of main.
9540 // static main is not an error under C99, but we should warn about it.
9541 // We accept _Noreturn main as an extension.
9542 if (FD->getStorageClass() == SC_Static)
9543 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9544 ? diag::err_static_main : diag::warn_static_main)
9545 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9546 if (FD->isInlineSpecified())
9547 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9548 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9549 if (DS.isNoreturnSpecified()) {
9550 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9551 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9552 Diag(NoreturnLoc, diag::ext_noreturn_main);
9553 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9554 << FixItHint::CreateRemoval(NoreturnRange);
9556 if (FD->isConstexpr()) {
9557 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9558 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9559 FD->setConstexpr(false);
9562 if (getLangOpts().OpenCL) {
9563 Diag(FD->getLocation(), diag::err_opencl_no_main)
9564 << FD->hasAttr<OpenCLKernelAttr>();
9565 FD->setInvalidDecl();
9569 QualType T = FD->getType();
9570 assert(T->isFunctionType() && "function decl is not of function type");
9571 const FunctionType* FT = T->castAs<FunctionType>();
9573 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9574 // In C with GNU extensions we allow main() to have non-integer return
9575 // type, but we should warn about the extension, and we disable the
9576 // implicit-return-zero rule.
9578 // GCC in C mode accepts qualified 'int'.
9579 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9580 FD->setHasImplicitReturnZero(true);
9582 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9583 SourceRange RTRange = FD->getReturnTypeSourceRange();
9584 if (RTRange.isValid())
9585 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9586 << FixItHint::CreateReplacement(RTRange, "int");
9589 // In C and C++, main magically returns 0 if you fall off the end;
9590 // set the flag which tells us that.
9591 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9593 // All the standards say that main() should return 'int'.
9594 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9595 FD->setHasImplicitReturnZero(true);
9597 // Otherwise, this is just a flat-out error.
9598 SourceRange RTRange = FD->getReturnTypeSourceRange();
9599 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9600 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9602 FD->setInvalidDecl(true);
9606 // Treat protoless main() as nullary.
9607 if (isa<FunctionNoProtoType>(FT)) return;
9609 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9610 unsigned nparams = FTP->getNumParams();
9611 assert(FD->getNumParams() == nparams);
9613 bool HasExtraParameters = (nparams > 3);
9615 if (FTP->isVariadic()) {
9616 Diag(FD->getLocation(), diag::ext_variadic_main);
9617 // FIXME: if we had information about the location of the ellipsis, we
9618 // could add a FixIt hint to remove it as a parameter.
9621 // Darwin passes an undocumented fourth argument of type char**. If
9622 // other platforms start sprouting these, the logic below will start
9624 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9625 HasExtraParameters = false;
9627 if (HasExtraParameters) {
9628 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9629 FD->setInvalidDecl(true);
9633 // FIXME: a lot of the following diagnostics would be improved
9634 // if we had some location information about types.
9637 Context.getPointerType(Context.getPointerType(Context.CharTy));
9638 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9640 for (unsigned i = 0; i < nparams; ++i) {
9641 QualType AT = FTP->getParamType(i);
9643 bool mismatch = true;
9645 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9647 else if (Expected[i] == CharPP) {
9648 // As an extension, the following forms are okay:
9650 // char const * const *
9653 QualifierCollector qs;
9654 const PointerType* PT;
9655 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9656 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9657 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9660 mismatch = !qs.empty();
9665 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9666 // TODO: suggest replacing given type with expected type
9667 FD->setInvalidDecl(true);
9671 if (nparams == 1 && !FD->isInvalidDecl()) {
9672 Diag(FD->getLocation(), diag::warn_main_one_arg);
9675 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9676 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9677 FD->setInvalidDecl();
9681 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9682 QualType T = FD->getType();
9683 assert(T->isFunctionType() && "function decl is not of function type");
9684 const FunctionType *FT = T->castAs<FunctionType>();
9686 // Set an implicit return of 'zero' if the function can return some integral,
9687 // enumeration, pointer or nullptr type.
9688 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9689 FT->getReturnType()->isAnyPointerType() ||
9690 FT->getReturnType()->isNullPtrType())
9691 // DllMain is exempt because a return value of zero means it failed.
9692 if (FD->getName() != "DllMain")
9693 FD->setHasImplicitReturnZero(true);
9695 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9696 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9697 FD->setInvalidDecl();
9701 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9702 // FIXME: Need strict checking. In C89, we need to check for
9703 // any assignment, increment, decrement, function-calls, or
9704 // commas outside of a sizeof. In C99, it's the same list,
9705 // except that the aforementioned are allowed in unevaluated
9706 // expressions. Everything else falls under the
9707 // "may accept other forms of constant expressions" exception.
9708 // (We never end up here for C++, so the constant expression
9709 // rules there don't matter.)
9710 const Expr *Culprit;
9711 if (Init->isConstantInitializer(Context, false, &Culprit))
9713 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9714 << Culprit->getSourceRange();
9719 // Visits an initialization expression to see if OrigDecl is evaluated in
9720 // its own initialization and throws a warning if it does.
9721 class SelfReferenceChecker
9722 : public EvaluatedExprVisitor<SelfReferenceChecker> {
9727 bool isReferenceType;
9730 llvm::SmallVector<unsigned, 4> InitFieldIndex;
9733 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9735 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9736 S(S), OrigDecl(OrigDecl) {
9738 isRecordType = false;
9739 isReferenceType = false;
9741 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9742 isPODType = VD->getType().isPODType(S.Context);
9743 isRecordType = VD->getType()->isRecordType();
9744 isReferenceType = VD->getType()->isReferenceType();
9748 // For most expressions, just call the visitor. For initializer lists,
9749 // track the index of the field being initialized since fields are
9750 // initialized in order allowing use of previously initialized fields.
9751 void CheckExpr(Expr *E) {
9752 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9758 // Track and increment the index here.
9760 InitFieldIndex.push_back(0);
9761 for (auto Child : InitList->children()) {
9762 CheckExpr(cast<Expr>(Child));
9763 ++InitFieldIndex.back();
9765 InitFieldIndex.pop_back();
9768 // Returns true if MemberExpr is checked and no further checking is needed.
9769 // Returns false if additional checking is required.
9770 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9771 llvm::SmallVector<FieldDecl*, 4> Fields;
9773 bool ReferenceField = false;
9775 // Get the field memebers used.
9776 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9777 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9780 Fields.push_back(FD);
9781 if (FD->getType()->isReferenceType())
9782 ReferenceField = true;
9783 Base = ME->getBase()->IgnoreParenImpCasts();
9786 // Keep checking only if the base Decl is the same.
9787 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9788 if (!DRE || DRE->getDecl() != OrigDecl)
9791 // A reference field can be bound to an unininitialized field.
9792 if (CheckReference && !ReferenceField)
9795 // Convert FieldDecls to their index number.
9796 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9797 for (const FieldDecl *I : llvm::reverse(Fields))
9798 UsedFieldIndex.push_back(I->getFieldIndex());
9800 // See if a warning is needed by checking the first difference in index
9801 // numbers. If field being used has index less than the field being
9802 // initialized, then the use is safe.
9803 for (auto UsedIter = UsedFieldIndex.begin(),
9804 UsedEnd = UsedFieldIndex.end(),
9805 OrigIter = InitFieldIndex.begin(),
9806 OrigEnd = InitFieldIndex.end();
9807 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9808 if (*UsedIter < *OrigIter)
9810 if (*UsedIter > *OrigIter)
9814 // TODO: Add a different warning which will print the field names.
9815 HandleDeclRefExpr(DRE);
9819 // For most expressions, the cast is directly above the DeclRefExpr.
9820 // For conditional operators, the cast can be outside the conditional
9821 // operator if both expressions are DeclRefExpr's.
9822 void HandleValue(Expr *E) {
9823 E = E->IgnoreParens();
9824 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9825 HandleDeclRefExpr(DRE);
9829 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9830 Visit(CO->getCond());
9831 HandleValue(CO->getTrueExpr());
9832 HandleValue(CO->getFalseExpr());
9836 if (BinaryConditionalOperator *BCO =
9837 dyn_cast<BinaryConditionalOperator>(E)) {
9838 Visit(BCO->getCond());
9839 HandleValue(BCO->getFalseExpr());
9843 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9844 HandleValue(OVE->getSourceExpr());
9848 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9849 if (BO->getOpcode() == BO_Comma) {
9850 Visit(BO->getLHS());
9851 HandleValue(BO->getRHS());
9856 if (isa<MemberExpr>(E)) {
9858 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9859 false /*CheckReference*/))
9863 Expr *Base = E->IgnoreParenImpCasts();
9864 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9865 // Check for static member variables and don't warn on them.
9866 if (!isa<FieldDecl>(ME->getMemberDecl()))
9868 Base = ME->getBase()->IgnoreParenImpCasts();
9870 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9871 HandleDeclRefExpr(DRE);
9878 // Reference types not handled in HandleValue are handled here since all
9879 // uses of references are bad, not just r-value uses.
9880 void VisitDeclRefExpr(DeclRefExpr *E) {
9881 if (isReferenceType)
9882 HandleDeclRefExpr(E);
9885 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9886 if (E->getCastKind() == CK_LValueToRValue) {
9887 HandleValue(E->getSubExpr());
9891 Inherited::VisitImplicitCastExpr(E);
9894 void VisitMemberExpr(MemberExpr *E) {
9896 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9900 // Don't warn on arrays since they can be treated as pointers.
9901 if (E->getType()->canDecayToPointerType()) return;
9903 // Warn when a non-static method call is followed by non-static member
9904 // field accesses, which is followed by a DeclRefExpr.
9905 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9906 bool Warn = (MD && !MD->isStatic());
9907 Expr *Base = E->getBase()->IgnoreParenImpCasts();
9908 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9909 if (!isa<FieldDecl>(ME->getMemberDecl()))
9911 Base = ME->getBase()->IgnoreParenImpCasts();
9914 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9916 HandleDeclRefExpr(DRE);
9920 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9921 // Visit that expression.
9925 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9926 Expr *Callee = E->getCallee();
9928 if (isa<UnresolvedLookupExpr>(Callee))
9929 return Inherited::VisitCXXOperatorCallExpr(E);
9932 for (auto Arg: E->arguments())
9933 HandleValue(Arg->IgnoreParenImpCasts());
9936 void VisitUnaryOperator(UnaryOperator *E) {
9937 // For POD record types, addresses of its own members are well-defined.
9938 if (E->getOpcode() == UO_AddrOf && isRecordType &&
9939 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9941 HandleValue(E->getSubExpr());
9945 if (E->isIncrementDecrementOp()) {
9946 HandleValue(E->getSubExpr());
9950 Inherited::VisitUnaryOperator(E);
9953 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9955 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9956 if (E->getConstructor()->isCopyConstructor()) {
9957 Expr *ArgExpr = E->getArg(0);
9958 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9959 if (ILE->getNumInits() == 1)
9960 ArgExpr = ILE->getInit(0);
9961 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9962 if (ICE->getCastKind() == CK_NoOp)
9963 ArgExpr = ICE->getSubExpr();
9964 HandleValue(ArgExpr);
9967 Inherited::VisitCXXConstructExpr(E);
9970 void VisitCallExpr(CallExpr *E) {
9971 // Treat std::move as a use.
9972 if (E->getNumArgs() == 1) {
9973 if (FunctionDecl *FD = E->getDirectCallee()) {
9974 if (FD->isInStdNamespace() && FD->getIdentifier() &&
9975 FD->getIdentifier()->isStr("move")) {
9976 HandleValue(E->getArg(0));
9982 Inherited::VisitCallExpr(E);
9985 void VisitBinaryOperator(BinaryOperator *E) {
9986 if (E->isCompoundAssignmentOp()) {
9987 HandleValue(E->getLHS());
9992 Inherited::VisitBinaryOperator(E);
9995 // A custom visitor for BinaryConditionalOperator is needed because the
9996 // regular visitor would check the condition and true expression separately
9997 // but both point to the same place giving duplicate diagnostics.
9998 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9999 Visit(E->getCond());
10000 Visit(E->getFalseExpr());
10003 void HandleDeclRefExpr(DeclRefExpr *DRE) {
10004 Decl* ReferenceDecl = DRE->getDecl();
10005 if (OrigDecl != ReferenceDecl) return;
10007 if (isReferenceType) {
10008 diag = diag::warn_uninit_self_reference_in_reference_init;
10009 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10010 diag = diag::warn_static_self_reference_in_init;
10011 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10012 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10013 DRE->getDecl()->getType()->isRecordType()) {
10014 diag = diag::warn_uninit_self_reference_in_init;
10016 // Local variables will be handled by the CFG analysis.
10020 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10022 << DRE->getNameInfo().getName()
10023 << OrigDecl->getLocation()
10024 << DRE->getSourceRange());
10028 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10029 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10031 // Parameters arguments are occassionially constructed with itself,
10032 // for instance, in recursive functions. Skip them.
10033 if (isa<ParmVarDecl>(OrigDecl))
10036 E = E->IgnoreParens();
10038 // Skip checking T a = a where T is not a record or reference type.
10039 // Doing so is a way to silence uninitialized warnings.
10040 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10041 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10042 if (ICE->getCastKind() == CK_LValueToRValue)
10043 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10044 if (DRE->getDecl() == OrigDecl)
10047 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10049 } // end anonymous namespace
10052 // Simple wrapper to add the name of a variable or (if no variable is
10053 // available) a DeclarationName into a diagnostic.
10054 struct VarDeclOrName {
10056 DeclarationName Name;
10058 friend const Sema::SemaDiagnosticBuilder &
10059 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10060 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10063 } // end anonymous namespace
10065 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10066 DeclarationName Name, QualType Type,
10067 TypeSourceInfo *TSI,
10068 SourceRange Range, bool DirectInit,
10070 bool IsInitCapture = !VDecl;
10071 assert((!VDecl || !VDecl->isInitCapture()) &&
10072 "init captures are expected to be deduced prior to initialization");
10074 VarDeclOrName VN{VDecl, Name};
10076 DeducedType *Deduced = Type->getContainedDeducedType();
10077 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10079 // C++11 [dcl.spec.auto]p3
10081 assert(VDecl && "no init for init capture deduction?");
10082 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10083 << VDecl->getDeclName() << Type;
10087 ArrayRef<Expr*> DeduceInits = Init;
10089 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10090 DeduceInits = PL->exprs();
10093 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10094 assert(VDecl && "non-auto type for init capture deduction?");
10095 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10096 InitializationKind Kind = InitializationKind::CreateForInit(
10097 VDecl->getLocation(), DirectInit, Init);
10098 // FIXME: Initialization should not be taking a mutable list of inits.
10099 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10100 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10105 if (auto *IL = dyn_cast<InitListExpr>(Init))
10106 DeduceInits = IL->inits();
10109 // Deduction only works if we have exactly one source expression.
10110 if (DeduceInits.empty()) {
10111 // It isn't possible to write this directly, but it is possible to
10112 // end up in this situation with "auto x(some_pack...);"
10113 Diag(Init->getLocStart(), IsInitCapture
10114 ? diag::err_init_capture_no_expression
10115 : diag::err_auto_var_init_no_expression)
10116 << VN << Type << Range;
10120 if (DeduceInits.size() > 1) {
10121 Diag(DeduceInits[1]->getLocStart(),
10122 IsInitCapture ? diag::err_init_capture_multiple_expressions
10123 : diag::err_auto_var_init_multiple_expressions)
10124 << VN << Type << Range;
10128 Expr *DeduceInit = DeduceInits[0];
10129 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10130 Diag(Init->getLocStart(), IsInitCapture
10131 ? diag::err_init_capture_paren_braces
10132 : diag::err_auto_var_init_paren_braces)
10133 << isa<InitListExpr>(Init) << VN << Type << Range;
10137 // Expressions default to 'id' when we're in a debugger.
10138 bool DefaultedAnyToId = false;
10139 if (getLangOpts().DebuggerCastResultToId &&
10140 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10141 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10142 if (Result.isInvalid()) {
10145 Init = Result.get();
10146 DefaultedAnyToId = true;
10149 // C++ [dcl.decomp]p1:
10150 // If the assignment-expression [...] has array type A and no ref-qualifier
10151 // is present, e has type cv A
10152 if (VDecl && isa<DecompositionDecl>(VDecl) &&
10153 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10154 DeduceInit->getType()->isConstantArrayType())
10155 return Context.getQualifiedType(DeduceInit->getType(),
10156 Type.getQualifiers());
10158 QualType DeducedType;
10159 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10160 if (!IsInitCapture)
10161 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10162 else if (isa<InitListExpr>(Init))
10163 Diag(Range.getBegin(),
10164 diag::err_init_capture_deduction_failure_from_init_list)
10166 << (DeduceInit->getType().isNull() ? TSI->getType()
10167 : DeduceInit->getType())
10168 << DeduceInit->getSourceRange();
10170 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10171 << VN << TSI->getType()
10172 << (DeduceInit->getType().isNull() ? TSI->getType()
10173 : DeduceInit->getType())
10174 << DeduceInit->getSourceRange();
10177 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10178 // 'id' instead of a specific object type prevents most of our usual
10180 // We only want to warn outside of template instantiations, though:
10181 // inside a template, the 'id' could have come from a parameter.
10182 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10183 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10184 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10185 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10188 return DeducedType;
10191 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10193 QualType DeducedType = deduceVarTypeFromInitializer(
10194 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10195 VDecl->getSourceRange(), DirectInit, Init);
10196 if (DeducedType.isNull()) {
10197 VDecl->setInvalidDecl();
10201 VDecl->setType(DeducedType);
10202 assert(VDecl->isLinkageValid());
10204 // In ARC, infer lifetime.
10205 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10206 VDecl->setInvalidDecl();
10208 // If this is a redeclaration, check that the type we just deduced matches
10209 // the previously declared type.
10210 if (VarDecl *Old = VDecl->getPreviousDecl()) {
10211 // We never need to merge the type, because we cannot form an incomplete
10212 // array of auto, nor deduce such a type.
10213 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10216 // Check the deduced type is valid for a variable declaration.
10217 CheckVariableDeclarationType(VDecl);
10218 return VDecl->isInvalidDecl();
10221 /// AddInitializerToDecl - Adds the initializer Init to the
10222 /// declaration dcl. If DirectInit is true, this is C++ direct
10223 /// initialization rather than copy initialization.
10224 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10225 // If there is no declaration, there was an error parsing it. Just ignore
10226 // the initializer.
10227 if (!RealDecl || RealDecl->isInvalidDecl()) {
10228 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10232 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10233 // Pure-specifiers are handled in ActOnPureSpecifier.
10234 Diag(Method->getLocation(), diag::err_member_function_initialization)
10235 << Method->getDeclName() << Init->getSourceRange();
10236 Method->setInvalidDecl();
10240 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10242 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10243 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10244 RealDecl->setInvalidDecl();
10248 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10249 if (VDecl->getType()->isUndeducedType()) {
10250 // Attempt typo correction early so that the type of the init expression can
10251 // be deduced based on the chosen correction if the original init contains a
10253 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10254 if (!Res.isUsable()) {
10255 RealDecl->setInvalidDecl();
10260 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10264 // dllimport cannot be used on variable definitions.
10265 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10266 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10267 VDecl->setInvalidDecl();
10271 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10272 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10273 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10274 VDecl->setInvalidDecl();
10278 if (!VDecl->getType()->isDependentType()) {
10279 // A definition must end up with a complete type, which means it must be
10280 // complete with the restriction that an array type might be completed by
10281 // the initializer; note that later code assumes this restriction.
10282 QualType BaseDeclType = VDecl->getType();
10283 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10284 BaseDeclType = Array->getElementType();
10285 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10286 diag::err_typecheck_decl_incomplete_type)) {
10287 RealDecl->setInvalidDecl();
10291 // The variable can not have an abstract class type.
10292 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10293 diag::err_abstract_type_in_decl,
10294 AbstractVariableType))
10295 VDecl->setInvalidDecl();
10298 // If adding the initializer will turn this declaration into a definition,
10299 // and we already have a definition for this variable, diagnose or otherwise
10300 // handle the situation.
10302 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10303 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10304 !VDecl->isThisDeclarationADemotedDefinition() &&
10305 checkVarDeclRedefinition(Def, VDecl))
10308 if (getLangOpts().CPlusPlus) {
10309 // C++ [class.static.data]p4
10310 // If a static data member is of const integral or const
10311 // enumeration type, its declaration in the class definition can
10312 // specify a constant-initializer which shall be an integral
10313 // constant expression (5.19). In that case, the member can appear
10314 // in integral constant expressions. The member shall still be
10315 // defined in a namespace scope if it is used in the program and the
10316 // namespace scope definition shall not contain an initializer.
10318 // We already performed a redefinition check above, but for static
10319 // data members we also need to check whether there was an in-class
10320 // declaration with an initializer.
10321 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10322 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10323 << VDecl->getDeclName();
10324 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10325 diag::note_previous_initializer)
10330 if (VDecl->hasLocalStorage())
10331 getCurFunction()->setHasBranchProtectedScope();
10333 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10334 VDecl->setInvalidDecl();
10339 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10340 // a kernel function cannot be initialized."
10341 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10342 Diag(VDecl->getLocation(), diag::err_local_cant_init);
10343 VDecl->setInvalidDecl();
10347 // Get the decls type and save a reference for later, since
10348 // CheckInitializerTypes may change it.
10349 QualType DclT = VDecl->getType(), SavT = DclT;
10351 // Expressions default to 'id' when we're in a debugger
10352 // and we are assigning it to a variable of Objective-C pointer type.
10353 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10354 Init->getType() == Context.UnknownAnyTy) {
10355 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10356 if (Result.isInvalid()) {
10357 VDecl->setInvalidDecl();
10360 Init = Result.get();
10363 // Perform the initialization.
10364 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10365 if (!VDecl->isInvalidDecl()) {
10366 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10367 InitializationKind Kind = InitializationKind::CreateForInit(
10368 VDecl->getLocation(), DirectInit, Init);
10370 MultiExprArg Args = Init;
10372 Args = MultiExprArg(CXXDirectInit->getExprs(),
10373 CXXDirectInit->getNumExprs());
10375 // Try to correct any TypoExprs in the initialization arguments.
10376 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10377 ExprResult Res = CorrectDelayedTyposInExpr(
10378 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10379 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10380 return Init.Failed() ? ExprError() : E;
10382 if (Res.isInvalid()) {
10383 VDecl->setInvalidDecl();
10384 } else if (Res.get() != Args[Idx]) {
10385 Args[Idx] = Res.get();
10388 if (VDecl->isInvalidDecl())
10391 InitializationSequence InitSeq(*this, Entity, Kind, Args,
10392 /*TopLevelOfInitList=*/false,
10393 /*TreatUnavailableAsInvalid=*/false);
10394 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10395 if (Result.isInvalid()) {
10396 VDecl->setInvalidDecl();
10400 Init = Result.getAs<Expr>();
10403 // Check for self-references within variable initializers.
10404 // Variables declared within a function/method body (except for references)
10405 // are handled by a dataflow analysis.
10406 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10407 VDecl->getType()->isReferenceType()) {
10408 CheckSelfReference(*this, RealDecl, Init, DirectInit);
10411 // If the type changed, it means we had an incomplete type that was
10412 // completed by the initializer. For example:
10413 // int ary[] = { 1, 3, 5 };
10414 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10415 if (!VDecl->isInvalidDecl() && (DclT != SavT))
10416 VDecl->setType(DclT);
10418 if (!VDecl->isInvalidDecl()) {
10419 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10421 if (VDecl->hasAttr<BlocksAttr>())
10422 checkRetainCycles(VDecl, Init);
10424 // It is safe to assign a weak reference into a strong variable.
10425 // Although this code can still have problems:
10426 // id x = self.weakProp;
10427 // id y = self.weakProp;
10428 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10429 // paths through the function. This should be revisited if
10430 // -Wrepeated-use-of-weak is made flow-sensitive.
10431 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10432 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10433 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10434 Init->getLocStart()))
10435 getCurFunction()->markSafeWeakUse(Init);
10438 // The initialization is usually a full-expression.
10440 // FIXME: If this is a braced initialization of an aggregate, it is not
10441 // an expression, and each individual field initializer is a separate
10442 // full-expression. For instance, in:
10444 // struct Temp { ~Temp(); };
10445 // struct S { S(Temp); };
10446 // struct T { S a, b; } t = { Temp(), Temp() }
10448 // we should destroy the first Temp before constructing the second.
10449 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10451 VDecl->isConstexpr());
10452 if (Result.isInvalid()) {
10453 VDecl->setInvalidDecl();
10456 Init = Result.get();
10458 // Attach the initializer to the decl.
10459 VDecl->setInit(Init);
10461 if (VDecl->isLocalVarDecl()) {
10462 // Don't check the initializer if the declaration is malformed.
10463 if (VDecl->isInvalidDecl()) {
10466 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10467 // This is true even in OpenCL C++.
10468 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10469 CheckForConstantInitializer(Init, DclT);
10471 // Otherwise, C++ does not restrict the initializer.
10472 } else if (getLangOpts().CPlusPlus) {
10475 // C99 6.7.8p4: All the expressions in an initializer for an object that has
10476 // static storage duration shall be constant expressions or string literals.
10477 } else if (VDecl->getStorageClass() == SC_Static) {
10478 CheckForConstantInitializer(Init, DclT);
10480 // C89 is stricter than C99 for aggregate initializers.
10481 // C89 6.5.7p3: All the expressions [...] in an initializer list
10482 // for an object that has aggregate or union type shall be
10483 // constant expressions.
10484 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10485 isa<InitListExpr>(Init)) {
10486 const Expr *Culprit;
10487 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10488 Diag(Culprit->getExprLoc(),
10489 diag::ext_aggregate_init_not_constant)
10490 << Culprit->getSourceRange();
10493 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10494 VDecl->getLexicalDeclContext()->isRecord()) {
10495 // This is an in-class initialization for a static data member, e.g.,
10498 // static const int value = 17;
10501 // C++ [class.mem]p4:
10502 // A member-declarator can contain a constant-initializer only
10503 // if it declares a static member (9.4) of const integral or
10504 // const enumeration type, see 9.4.2.
10506 // C++11 [class.static.data]p3:
10507 // If a non-volatile non-inline const static data member is of integral
10508 // or enumeration type, its declaration in the class definition can
10509 // specify a brace-or-equal-initializer in which every initializer-clause
10510 // that is an assignment-expression is a constant expression. A static
10511 // data member of literal type can be declared in the class definition
10512 // with the constexpr specifier; if so, its declaration shall specify a
10513 // brace-or-equal-initializer in which every initializer-clause that is
10514 // an assignment-expression is a constant expression.
10516 // Do nothing on dependent types.
10517 if (DclT->isDependentType()) {
10519 // Allow any 'static constexpr' members, whether or not they are of literal
10520 // type. We separately check that every constexpr variable is of literal
10522 } else if (VDecl->isConstexpr()) {
10524 // Require constness.
10525 } else if (!DclT.isConstQualified()) {
10526 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10527 << Init->getSourceRange();
10528 VDecl->setInvalidDecl();
10530 // We allow integer constant expressions in all cases.
10531 } else if (DclT->isIntegralOrEnumerationType()) {
10532 // Check whether the expression is a constant expression.
10533 SourceLocation Loc;
10534 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10535 // In C++11, a non-constexpr const static data member with an
10536 // in-class initializer cannot be volatile.
10537 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10538 else if (Init->isValueDependent())
10539 ; // Nothing to check.
10540 else if (Init->isIntegerConstantExpr(Context, &Loc))
10541 ; // Ok, it's an ICE!
10542 else if (Init->isEvaluatable(Context)) {
10543 // If we can constant fold the initializer through heroics, accept it,
10544 // but report this as a use of an extension for -pedantic.
10545 Diag(Loc, diag::ext_in_class_initializer_non_constant)
10546 << Init->getSourceRange();
10548 // Otherwise, this is some crazy unknown case. Report the issue at the
10549 // location provided by the isIntegerConstantExpr failed check.
10550 Diag(Loc, diag::err_in_class_initializer_non_constant)
10551 << Init->getSourceRange();
10552 VDecl->setInvalidDecl();
10555 // We allow foldable floating-point constants as an extension.
10556 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10557 // In C++98, this is a GNU extension. In C++11, it is not, but we support
10558 // it anyway and provide a fixit to add the 'constexpr'.
10559 if (getLangOpts().CPlusPlus11) {
10560 Diag(VDecl->getLocation(),
10561 diag::ext_in_class_initializer_float_type_cxx11)
10562 << DclT << Init->getSourceRange();
10563 Diag(VDecl->getLocStart(),
10564 diag::note_in_class_initializer_float_type_cxx11)
10565 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10567 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10568 << DclT << Init->getSourceRange();
10570 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10571 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10572 << Init->getSourceRange();
10573 VDecl->setInvalidDecl();
10577 // Suggest adding 'constexpr' in C++11 for literal types.
10578 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10579 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10580 << DclT << Init->getSourceRange()
10581 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10582 VDecl->setConstexpr(true);
10585 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10586 << DclT << Init->getSourceRange();
10587 VDecl->setInvalidDecl();
10589 } else if (VDecl->isFileVarDecl()) {
10590 // In C, extern is typically used to avoid tentative definitions when
10591 // declaring variables in headers, but adding an intializer makes it a
10592 // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10593 // In C++, extern is often used to give implictly static const variables
10594 // external linkage, so don't warn in that case. If selectany is present,
10595 // this might be header code intended for C and C++ inclusion, so apply the
10597 if (VDecl->getStorageClass() == SC_Extern &&
10598 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10599 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10600 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10601 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10602 Diag(VDecl->getLocation(), diag::warn_extern_init);
10604 // C99 6.7.8p4. All file scoped initializers need to be constant.
10605 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10606 CheckForConstantInitializer(Init, DclT);
10609 // We will represent direct-initialization similarly to copy-initialization:
10610 // int x(1); -as-> int x = 1;
10611 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10613 // Clients that want to distinguish between the two forms, can check for
10614 // direct initializer using VarDecl::getInitStyle().
10615 // A major benefit is that clients that don't particularly care about which
10616 // exactly form was it (like the CodeGen) can handle both cases without
10617 // special case code.
10620 // The form of initialization (using parentheses or '=') is generally
10621 // insignificant, but does matter when the entity being initialized has a
10623 if (CXXDirectInit) {
10624 assert(DirectInit && "Call-style initializer must be direct init.");
10625 VDecl->setInitStyle(VarDecl::CallInit);
10626 } else if (DirectInit) {
10627 // This must be list-initialization. No other way is direct-initialization.
10628 VDecl->setInitStyle(VarDecl::ListInit);
10631 CheckCompleteVariableDeclaration(VDecl);
10634 /// ActOnInitializerError - Given that there was an error parsing an
10635 /// initializer for the given declaration, try to return to some form
10637 void Sema::ActOnInitializerError(Decl *D) {
10638 // Our main concern here is re-establishing invariants like "a
10639 // variable's type is either dependent or complete".
10640 if (!D || D->isInvalidDecl()) return;
10642 VarDecl *VD = dyn_cast<VarDecl>(D);
10645 // Bindings are not usable if we can't make sense of the initializer.
10646 if (auto *DD = dyn_cast<DecompositionDecl>(D))
10647 for (auto *BD : DD->bindings())
10648 BD->setInvalidDecl();
10650 // Auto types are meaningless if we can't make sense of the initializer.
10651 if (ParsingInitForAutoVars.count(D)) {
10652 D->setInvalidDecl();
10656 QualType Ty = VD->getType();
10657 if (Ty->isDependentType()) return;
10659 // Require a complete type.
10660 if (RequireCompleteType(VD->getLocation(),
10661 Context.getBaseElementType(Ty),
10662 diag::err_typecheck_decl_incomplete_type)) {
10663 VD->setInvalidDecl();
10667 // Require a non-abstract type.
10668 if (RequireNonAbstractType(VD->getLocation(), Ty,
10669 diag::err_abstract_type_in_decl,
10670 AbstractVariableType)) {
10671 VD->setInvalidDecl();
10675 // Don't bother complaining about constructors or destructors,
10679 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10680 // If there is no declaration, there was an error parsing it. Just ignore it.
10684 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10685 QualType Type = Var->getType();
10687 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10688 if (isa<DecompositionDecl>(RealDecl)) {
10689 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10690 Var->setInvalidDecl();
10694 if (Type->isUndeducedType() &&
10695 DeduceVariableDeclarationType(Var, false, nullptr))
10698 // C++11 [class.static.data]p3: A static data member can be declared with
10699 // the constexpr specifier; if so, its declaration shall specify
10700 // a brace-or-equal-initializer.
10701 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10702 // the definition of a variable [...] or the declaration of a static data
10704 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10705 !Var->isThisDeclarationADemotedDefinition()) {
10706 if (Var->isStaticDataMember()) {
10707 // C++1z removes the relevant rule; the in-class declaration is always
10708 // a definition there.
10709 if (!getLangOpts().CPlusPlus1z) {
10710 Diag(Var->getLocation(),
10711 diag::err_constexpr_static_mem_var_requires_init)
10712 << Var->getDeclName();
10713 Var->setInvalidDecl();
10717 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10718 Var->setInvalidDecl();
10723 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
10724 // definition having the concept specifier is called a variable concept. A
10725 // concept definition refers to [...] a variable concept and its initializer.
10726 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10727 if (VTD->isConcept()) {
10728 Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10729 Var->setInvalidDecl();
10734 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10736 if (!Var->isInvalidDecl() &&
10737 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10738 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10739 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10740 Var->setInvalidDecl();
10744 switch (Var->isThisDeclarationADefinition()) {
10745 case VarDecl::Definition:
10746 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10749 // We have an out-of-line definition of a static data member
10750 // that has an in-class initializer, so we type-check this like
10755 case VarDecl::DeclarationOnly:
10756 // It's only a declaration.
10758 // Block scope. C99 6.7p7: If an identifier for an object is
10759 // declared with no linkage (C99 6.2.2p6), the type for the
10760 // object shall be complete.
10761 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10762 !Var->hasLinkage() && !Var->isInvalidDecl() &&
10763 RequireCompleteType(Var->getLocation(), Type,
10764 diag::err_typecheck_decl_incomplete_type))
10765 Var->setInvalidDecl();
10767 // Make sure that the type is not abstract.
10768 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10769 RequireNonAbstractType(Var->getLocation(), Type,
10770 diag::err_abstract_type_in_decl,
10771 AbstractVariableType))
10772 Var->setInvalidDecl();
10773 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10774 Var->getStorageClass() == SC_PrivateExtern) {
10775 Diag(Var->getLocation(), diag::warn_private_extern);
10776 Diag(Var->getLocation(), diag::note_private_extern);
10781 case VarDecl::TentativeDefinition:
10782 // File scope. C99 6.9.2p2: A declaration of an identifier for an
10783 // object that has file scope without an initializer, and without a
10784 // storage-class specifier or with the storage-class specifier "static",
10785 // constitutes a tentative definition. Note: A tentative definition with
10786 // external linkage is valid (C99 6.2.2p5).
10787 if (!Var->isInvalidDecl()) {
10788 if (const IncompleteArrayType *ArrayT
10789 = Context.getAsIncompleteArrayType(Type)) {
10790 if (RequireCompleteType(Var->getLocation(),
10791 ArrayT->getElementType(),
10792 diag::err_illegal_decl_array_incomplete_type))
10793 Var->setInvalidDecl();
10794 } else if (Var->getStorageClass() == SC_Static) {
10795 // C99 6.9.2p3: If the declaration of an identifier for an object is
10796 // a tentative definition and has internal linkage (C99 6.2.2p3), the
10797 // declared type shall not be an incomplete type.
10798 // NOTE: code such as the following
10799 // static struct s;
10800 // struct s { int a; };
10801 // is accepted by gcc. Hence here we issue a warning instead of
10802 // an error and we do not invalidate the static declaration.
10803 // NOTE: to avoid multiple warnings, only check the first declaration.
10804 if (Var->isFirstDecl())
10805 RequireCompleteType(Var->getLocation(), Type,
10806 diag::ext_typecheck_decl_incomplete_type);
10810 // Record the tentative definition; we're done.
10811 if (!Var->isInvalidDecl())
10812 TentativeDefinitions.push_back(Var);
10816 // Provide a specific diagnostic for uninitialized variable
10817 // definitions with incomplete array type.
10818 if (Type->isIncompleteArrayType()) {
10819 Diag(Var->getLocation(),
10820 diag::err_typecheck_incomplete_array_needs_initializer);
10821 Var->setInvalidDecl();
10825 // Provide a specific diagnostic for uninitialized variable
10826 // definitions with reference type.
10827 if (Type->isReferenceType()) {
10828 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10829 << Var->getDeclName()
10830 << SourceRange(Var->getLocation(), Var->getLocation());
10831 Var->setInvalidDecl();
10835 // Do not attempt to type-check the default initializer for a
10836 // variable with dependent type.
10837 if (Type->isDependentType())
10840 if (Var->isInvalidDecl())
10843 if (!Var->hasAttr<AliasAttr>()) {
10844 if (RequireCompleteType(Var->getLocation(),
10845 Context.getBaseElementType(Type),
10846 diag::err_typecheck_decl_incomplete_type)) {
10847 Var->setInvalidDecl();
10854 // The variable can not have an abstract class type.
10855 if (RequireNonAbstractType(Var->getLocation(), Type,
10856 diag::err_abstract_type_in_decl,
10857 AbstractVariableType)) {
10858 Var->setInvalidDecl();
10862 // Check for jumps past the implicit initializer. C++0x
10863 // clarifies that this applies to a "variable with automatic
10864 // storage duration", not a "local variable".
10865 // C++11 [stmt.dcl]p3
10866 // A program that jumps from a point where a variable with automatic
10867 // storage duration is not in scope to a point where it is in scope is
10868 // ill-formed unless the variable has scalar type, class type with a
10869 // trivial default constructor and a trivial destructor, a cv-qualified
10870 // version of one of these types, or an array of one of the preceding
10871 // types and is declared without an initializer.
10872 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10873 if (const RecordType *Record
10874 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10875 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10876 // Mark the function for further checking even if the looser rules of
10877 // C++11 do not require such checks, so that we can diagnose
10878 // incompatibilities with C++98.
10879 if (!CXXRecord->isPOD())
10880 getCurFunction()->setHasBranchProtectedScope();
10884 // C++03 [dcl.init]p9:
10885 // If no initializer is specified for an object, and the
10886 // object is of (possibly cv-qualified) non-POD class type (or
10887 // array thereof), the object shall be default-initialized; if
10888 // the object is of const-qualified type, the underlying class
10889 // type shall have a user-declared default
10890 // constructor. Otherwise, if no initializer is specified for
10891 // a non- static object, the object and its subobjects, if
10892 // any, have an indeterminate initial value); if the object
10893 // or any of its subobjects are of const-qualified type, the
10894 // program is ill-formed.
10895 // C++0x [dcl.init]p11:
10896 // If no initializer is specified for an object, the object is
10897 // default-initialized; [...].
10898 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10899 InitializationKind Kind
10900 = InitializationKind::CreateDefault(Var->getLocation());
10902 InitializationSequence InitSeq(*this, Entity, Kind, None);
10903 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10904 if (Init.isInvalid())
10905 Var->setInvalidDecl();
10906 else if (Init.get()) {
10907 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10908 // This is important for template substitution.
10909 Var->setInitStyle(VarDecl::CallInit);
10912 CheckCompleteVariableDeclaration(Var);
10916 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10917 // If there is no declaration, there was an error parsing it. Ignore it.
10921 VarDecl *VD = dyn_cast<VarDecl>(D);
10923 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10924 D->setInvalidDecl();
10928 VD->setCXXForRangeDecl(true);
10930 // for-range-declaration cannot be given a storage class specifier.
10932 switch (VD->getStorageClass()) {
10941 case SC_PrivateExtern:
10952 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10953 << VD->getDeclName() << Error;
10954 D->setInvalidDecl();
10959 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10960 IdentifierInfo *Ident,
10961 ParsedAttributes &Attrs,
10962 SourceLocation AttrEnd) {
10963 // C++1y [stmt.iter]p1:
10964 // A range-based for statement of the form
10965 // for ( for-range-identifier : for-range-initializer ) statement
10966 // is equivalent to
10967 // for ( auto&& for-range-identifier : for-range-initializer ) statement
10968 DeclSpec DS(Attrs.getPool().getFactory());
10970 const char *PrevSpec;
10972 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10973 getPrintingPolicy());
10975 Declarator D(DS, Declarator::ForContext);
10976 D.SetIdentifier(Ident, IdentLoc);
10977 D.takeAttributes(Attrs, AttrEnd);
10979 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10980 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10981 EmptyAttrs, IdentLoc);
10982 Decl *Var = ActOnDeclarator(S, D);
10983 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10984 FinalizeDeclaration(Var);
10985 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10986 AttrEnd.isValid() ? AttrEnd : IdentLoc);
10989 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10990 if (var->isInvalidDecl()) return;
10992 if (getLangOpts().OpenCL) {
10993 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10995 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10997 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10999 var->setInvalidDecl();
11004 // In Objective-C, don't allow jumps past the implicit initialization of a
11005 // local retaining variable.
11006 if (getLangOpts().ObjC1 &&
11007 var->hasLocalStorage()) {
11008 switch (var->getType().getObjCLifetime()) {
11009 case Qualifiers::OCL_None:
11010 case Qualifiers::OCL_ExplicitNone:
11011 case Qualifiers::OCL_Autoreleasing:
11014 case Qualifiers::OCL_Weak:
11015 case Qualifiers::OCL_Strong:
11016 getCurFunction()->setHasBranchProtectedScope();
11021 // Warn about externally-visible variables being defined without a
11022 // prior declaration. We only want to do this for global
11023 // declarations, but we also specifically need to avoid doing it for
11024 // class members because the linkage of an anonymous class can
11025 // change if it's later given a typedef name.
11026 if (var->isThisDeclarationADefinition() &&
11027 var->getDeclContext()->getRedeclContext()->isFileContext() &&
11028 var->isExternallyVisible() && var->hasLinkage() &&
11029 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11030 var->getLocation())) {
11031 // Find a previous declaration that's not a definition.
11032 VarDecl *prev = var->getPreviousDecl();
11033 while (prev && prev->isThisDeclarationADefinition())
11034 prev = prev->getPreviousDecl();
11037 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11040 // Cache the result of checking for constant initialization.
11041 Optional<bool> CacheHasConstInit;
11042 const Expr *CacheCulprit;
11043 auto checkConstInit = [&]() mutable {
11044 if (!CacheHasConstInit)
11045 CacheHasConstInit = var->getInit()->isConstantInitializer(
11046 Context, var->getType()->isReferenceType(), &CacheCulprit);
11047 return *CacheHasConstInit;
11050 if (var->getTLSKind() == VarDecl::TLS_Static) {
11051 if (var->getType().isDestructedType()) {
11052 // GNU C++98 edits for __thread, [basic.start.term]p3:
11053 // The type of an object with thread storage duration shall not
11054 // have a non-trivial destructor.
11055 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11056 if (getLangOpts().CPlusPlus11)
11057 Diag(var->getLocation(), diag::note_use_thread_local);
11058 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11059 if (!checkConstInit()) {
11060 // GNU C++98 edits for __thread, [basic.start.init]p4:
11061 // An object of thread storage duration shall not require dynamic
11063 // FIXME: Need strict checking here.
11064 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11065 << CacheCulprit->getSourceRange();
11066 if (getLangOpts().CPlusPlus11)
11067 Diag(var->getLocation(), diag::note_use_thread_local);
11072 // Apply section attributes and pragmas to global variables.
11073 bool GlobalStorage = var->hasGlobalStorage();
11074 if (GlobalStorage && var->isThisDeclarationADefinition() &&
11075 !inTemplateInstantiation()) {
11076 PragmaStack<StringLiteral *> *Stack = nullptr;
11077 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11078 if (var->getType().isConstQualified())
11079 Stack = &ConstSegStack;
11080 else if (!var->getInit()) {
11081 Stack = &BSSSegStack;
11082 SectionFlags |= ASTContext::PSF_Write;
11084 Stack = &DataSegStack;
11085 SectionFlags |= ASTContext::PSF_Write;
11087 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11088 var->addAttr(SectionAttr::CreateImplicit(
11089 Context, SectionAttr::Declspec_allocate,
11090 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11092 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11093 if (UnifySection(SA->getName(), SectionFlags, var))
11094 var->dropAttr<SectionAttr>();
11096 // Apply the init_seg attribute if this has an initializer. If the
11097 // initializer turns out to not be dynamic, we'll end up ignoring this
11099 if (CurInitSeg && var->getInit())
11100 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11104 // All the following checks are C++ only.
11105 if (!getLangOpts().CPlusPlus) {
11106 // If this variable must be emitted, add it as an initializer for the
11108 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11109 Context.addModuleInitializer(ModuleScopes.back().Module, var);
11113 if (auto *DD = dyn_cast<DecompositionDecl>(var))
11114 CheckCompleteDecompositionDeclaration(DD);
11116 QualType type = var->getType();
11117 if (type->isDependentType()) return;
11119 // __block variables might require us to capture a copy-initializer.
11120 if (var->hasAttr<BlocksAttr>()) {
11121 // It's currently invalid to ever have a __block variable with an
11122 // array type; should we diagnose that here?
11124 // Regardless, we don't want to ignore array nesting when
11125 // constructing this copy.
11126 if (type->isStructureOrClassType()) {
11127 EnterExpressionEvaluationContext scope(
11128 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11129 SourceLocation poi = var->getLocation();
11130 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11132 = PerformMoveOrCopyInitialization(
11133 InitializedEntity::InitializeBlock(poi, type, false),
11134 var, var->getType(), varRef, /*AllowNRVO=*/true);
11135 if (!result.isInvalid()) {
11136 result = MaybeCreateExprWithCleanups(result);
11137 Expr *init = result.getAs<Expr>();
11138 Context.setBlockVarCopyInits(var, init);
11143 Expr *Init = var->getInit();
11144 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11145 QualType baseType = Context.getBaseElementType(type);
11147 if (Init && !Init->isValueDependent()) {
11148 if (var->isConstexpr()) {
11149 SmallVector<PartialDiagnosticAt, 8> Notes;
11150 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11151 SourceLocation DiagLoc = var->getLocation();
11152 // If the note doesn't add any useful information other than a source
11153 // location, fold it into the primary diagnostic.
11154 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11155 diag::note_invalid_subexpr_in_const_expr) {
11156 DiagLoc = Notes[0].first;
11159 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11160 << var << Init->getSourceRange();
11161 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11162 Diag(Notes[I].first, Notes[I].second);
11164 } else if (var->isUsableInConstantExpressions(Context)) {
11165 // Check whether the initializer of a const variable of integral or
11166 // enumeration type is an ICE now, since we can't tell whether it was
11167 // initialized by a constant expression if we check later.
11168 var->checkInitIsICE();
11171 // Don't emit further diagnostics about constexpr globals since they
11172 // were just diagnosed.
11173 if (!var->isConstexpr() && GlobalStorage &&
11174 var->hasAttr<RequireConstantInitAttr>()) {
11175 // FIXME: Need strict checking in C++03 here.
11176 bool DiagErr = getLangOpts().CPlusPlus11
11177 ? !var->checkInitIsICE() : !checkConstInit();
11179 auto attr = var->getAttr<RequireConstantInitAttr>();
11180 Diag(var->getLocation(), diag::err_require_constant_init_failed)
11181 << Init->getSourceRange();
11182 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11183 << attr->getRange();
11184 if (getLangOpts().CPlusPlus11) {
11186 SmallVector<PartialDiagnosticAt, 8> Notes;
11187 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11188 for (auto &it : Notes)
11189 Diag(it.first, it.second);
11191 Diag(CacheCulprit->getExprLoc(),
11192 diag::note_invalid_subexpr_in_const_expr)
11193 << CacheCulprit->getSourceRange();
11197 else if (!var->isConstexpr() && IsGlobal &&
11198 !getDiagnostics().isIgnored(diag::warn_global_constructor,
11199 var->getLocation())) {
11200 // Warn about globals which don't have a constant initializer. Don't
11201 // warn about globals with a non-trivial destructor because we already
11202 // warned about them.
11203 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11204 if (!(RD && !RD->hasTrivialDestructor())) {
11205 if (!checkConstInit())
11206 Diag(var->getLocation(), diag::warn_global_constructor)
11207 << Init->getSourceRange();
11212 // Require the destructor.
11213 if (const RecordType *recordType = baseType->getAs<RecordType>())
11214 FinalizeVarWithDestructor(var, recordType);
11216 // If this variable must be emitted, add it as an initializer for the current
11218 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11219 Context.addModuleInitializer(ModuleScopes.back().Module, var);
11222 /// \brief Determines if a variable's alignment is dependent.
11223 static bool hasDependentAlignment(VarDecl *VD) {
11224 if (VD->getType()->isDependentType())
11226 for (auto *I : VD->specific_attrs<AlignedAttr>())
11227 if (I->isAlignmentDependent())
11232 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11233 /// any semantic actions necessary after any initializer has been attached.
11234 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11235 // Note that we are no longer parsing the initializer for this declaration.
11236 ParsingInitForAutoVars.erase(ThisDecl);
11238 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11242 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11243 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11244 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11245 if (PragmaClangBSSSection.Valid)
11246 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11247 PragmaClangBSSSection.SectionName,
11248 PragmaClangBSSSection.PragmaLocation));
11249 if (PragmaClangDataSection.Valid)
11250 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11251 PragmaClangDataSection.SectionName,
11252 PragmaClangDataSection.PragmaLocation));
11253 if (PragmaClangRodataSection.Valid)
11254 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11255 PragmaClangRodataSection.SectionName,
11256 PragmaClangRodataSection.PragmaLocation));
11259 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11260 for (auto *BD : DD->bindings()) {
11261 FinalizeDeclaration(BD);
11265 checkAttributesAfterMerging(*this, *VD);
11267 // Perform TLS alignment check here after attributes attached to the variable
11268 // which may affect the alignment have been processed. Only perform the check
11269 // if the target has a maximum TLS alignment (zero means no constraints).
11270 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11271 // Protect the check so that it's not performed on dependent types and
11272 // dependent alignments (we can't determine the alignment in that case).
11273 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11274 !VD->isInvalidDecl()) {
11275 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11276 if (Context.getDeclAlign(VD) > MaxAlignChars) {
11277 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11278 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11279 << (unsigned)MaxAlignChars.getQuantity();
11284 if (VD->isStaticLocal()) {
11285 if (FunctionDecl *FD =
11286 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11287 // Static locals inherit dll attributes from their function.
11288 if (Attr *A = getDLLAttr(FD)) {
11289 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11290 NewAttr->setInherited(true);
11291 VD->addAttr(NewAttr);
11293 // CUDA E.2.9.4: Within the body of a __device__ or __global__
11294 // function, only __shared__ variables may be declared with
11295 // static storage class.
11296 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11297 CUDADiagIfDeviceCode(VD->getLocation(),
11298 diag::err_device_static_local_var)
11299 << CurrentCUDATarget())
11300 VD->setInvalidDecl();
11304 // Perform check for initializers of device-side global variables.
11305 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11306 // 7.5). We must also apply the same checks to all __shared__
11307 // variables whether they are local or not. CUDA also allows
11308 // constant initializers for __constant__ and __device__ variables.
11309 if (getLangOpts().CUDA) {
11310 const Expr *Init = VD->getInit();
11311 if (Init && VD->hasGlobalStorage()) {
11312 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11313 VD->hasAttr<CUDASharedAttr>()) {
11314 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11315 bool AllowedInit = false;
11316 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11318 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11319 // We'll allow constant initializers even if it's a non-empty
11320 // constructor according to CUDA rules. This deviates from NVCC,
11321 // but allows us to handle things like constexpr constructors.
11322 if (!AllowedInit &&
11323 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11324 AllowedInit = VD->getInit()->isConstantInitializer(
11325 Context, VD->getType()->isReferenceType());
11327 // Also make sure that destructor, if there is one, is empty.
11329 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11331 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11333 if (!AllowedInit) {
11334 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11335 ? diag::err_shared_var_init
11336 : diag::err_dynamic_var_init)
11337 << Init->getSourceRange();
11338 VD->setInvalidDecl();
11341 // This is a host-side global variable. Check that the initializer is
11342 // callable from the host side.
11343 const FunctionDecl *InitFn = nullptr;
11344 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11345 InitFn = CE->getConstructor();
11346 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11347 InitFn = CE->getDirectCallee();
11350 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11351 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11352 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11353 << InitFnTarget << InitFn;
11354 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11355 VD->setInvalidDecl();
11362 // Grab the dllimport or dllexport attribute off of the VarDecl.
11363 const InheritableAttr *DLLAttr = getDLLAttr(VD);
11365 // Imported static data members cannot be defined out-of-line.
11366 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11367 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11368 VD->isThisDeclarationADefinition()) {
11369 // We allow definitions of dllimport class template static data members
11371 CXXRecordDecl *Context =
11372 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11373 bool IsClassTemplateMember =
11374 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11375 Context->getDescribedClassTemplate();
11377 Diag(VD->getLocation(),
11378 IsClassTemplateMember
11379 ? diag::warn_attribute_dllimport_static_field_definition
11380 : diag::err_attribute_dllimport_static_field_definition);
11381 Diag(IA->getLocation(), diag::note_attribute);
11382 if (!IsClassTemplateMember)
11383 VD->setInvalidDecl();
11387 // dllimport/dllexport variables cannot be thread local, their TLS index
11388 // isn't exported with the variable.
11389 if (DLLAttr && VD->getTLSKind()) {
11390 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11391 if (F && getDLLAttr(F)) {
11392 assert(VD->isStaticLocal());
11393 // But if this is a static local in a dlimport/dllexport function, the
11394 // function will never be inlined, which means the var would never be
11395 // imported, so having it marked import/export is safe.
11397 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11399 VD->setInvalidDecl();
11403 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11404 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11405 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11406 VD->dropAttr<UsedAttr>();
11410 const DeclContext *DC = VD->getDeclContext();
11411 // If there's a #pragma GCC visibility in scope, and this isn't a class
11412 // member, set the visibility of this variable.
11413 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11414 AddPushedVisibilityAttribute(VD);
11416 // FIXME: Warn on unused var template partial specializations.
11417 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11418 MarkUnusedFileScopedDecl(VD);
11420 // Now we have parsed the initializer and can update the table of magic
11422 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11423 !VD->getType()->isIntegralOrEnumerationType())
11426 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11427 const Expr *MagicValueExpr = VD->getInit();
11428 if (!MagicValueExpr) {
11431 llvm::APSInt MagicValueInt;
11432 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11433 Diag(I->getRange().getBegin(),
11434 diag::err_type_tag_for_datatype_not_ice)
11435 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11438 if (MagicValueInt.getActiveBits() > 64) {
11439 Diag(I->getRange().getBegin(),
11440 diag::err_type_tag_for_datatype_too_large)
11441 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11444 uint64_t MagicValue = MagicValueInt.getZExtValue();
11445 RegisterTypeTagForDatatype(I->getArgumentKind(),
11447 I->getMatchingCType(),
11448 I->getLayoutCompatible(),
11449 I->getMustBeNull());
11453 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11454 auto *VD = dyn_cast<VarDecl>(DD);
11455 return VD && !VD->getType()->hasAutoForTrailingReturnType();
11458 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11459 ArrayRef<Decl *> Group) {
11460 SmallVector<Decl*, 8> Decls;
11462 if (DS.isTypeSpecOwned())
11463 Decls.push_back(DS.getRepAsDecl());
11465 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11466 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11467 bool DiagnosedMultipleDecomps = false;
11468 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11469 bool DiagnosedNonDeducedAuto = false;
11471 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11472 if (Decl *D = Group[i]) {
11473 // For declarators, there are some additional syntactic-ish checks we need
11475 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11476 if (!FirstDeclaratorInGroup)
11477 FirstDeclaratorInGroup = DD;
11478 if (!FirstDecompDeclaratorInGroup)
11479 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11480 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11481 !hasDeducedAuto(DD))
11482 FirstNonDeducedAutoInGroup = DD;
11484 if (FirstDeclaratorInGroup != DD) {
11485 // A decomposition declaration cannot be combined with any other
11486 // declaration in the same group.
11487 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11488 Diag(FirstDecompDeclaratorInGroup->getLocation(),
11489 diag::err_decomp_decl_not_alone)
11490 << FirstDeclaratorInGroup->getSourceRange()
11491 << DD->getSourceRange();
11492 DiagnosedMultipleDecomps = true;
11495 // A declarator that uses 'auto' in any way other than to declare a
11496 // variable with a deduced type cannot be combined with any other
11497 // declarator in the same group.
11498 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11499 Diag(FirstNonDeducedAutoInGroup->getLocation(),
11500 diag::err_auto_non_deduced_not_alone)
11501 << FirstNonDeducedAutoInGroup->getType()
11502 ->hasAutoForTrailingReturnType()
11503 << FirstDeclaratorInGroup->getSourceRange()
11504 << DD->getSourceRange();
11505 DiagnosedNonDeducedAuto = true;
11510 Decls.push_back(D);
11514 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11515 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11516 handleTagNumbering(Tag, S);
11517 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11518 getLangOpts().CPlusPlus)
11519 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11523 return BuildDeclaratorGroup(Decls);
11526 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11527 /// group, performing any necessary semantic checking.
11528 Sema::DeclGroupPtrTy
11529 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11530 // C++14 [dcl.spec.auto]p7: (DR1347)
11531 // If the type that replaces the placeholder type is not the same in each
11532 // deduction, the program is ill-formed.
11533 if (Group.size() > 1) {
11535 VarDecl *DeducedDecl = nullptr;
11536 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11537 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11538 if (!D || D->isInvalidDecl())
11540 DeducedType *DT = D->getType()->getContainedDeducedType();
11541 if (!DT || DT->getDeducedType().isNull())
11543 if (Deduced.isNull()) {
11544 Deduced = DT->getDeducedType();
11546 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11547 auto *AT = dyn_cast<AutoType>(DT);
11548 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11549 diag::err_auto_different_deductions)
11550 << (AT ? (unsigned)AT->getKeyword() : 3)
11551 << Deduced << DeducedDecl->getDeclName()
11552 << DT->getDeducedType() << D->getDeclName()
11553 << DeducedDecl->getInit()->getSourceRange()
11554 << D->getInit()->getSourceRange();
11555 D->setInvalidDecl();
11561 ActOnDocumentableDecls(Group);
11563 return DeclGroupPtrTy::make(
11564 DeclGroupRef::Create(Context, Group.data(), Group.size()));
11567 void Sema::ActOnDocumentableDecl(Decl *D) {
11568 ActOnDocumentableDecls(D);
11571 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11572 // Don't parse the comment if Doxygen diagnostics are ignored.
11573 if (Group.empty() || !Group[0])
11576 if (Diags.isIgnored(diag::warn_doc_param_not_found,
11577 Group[0]->getLocation()) &&
11578 Diags.isIgnored(diag::warn_unknown_comment_command_name,
11579 Group[0]->getLocation()))
11582 if (Group.size() >= 2) {
11583 // This is a decl group. Normally it will contain only declarations
11584 // produced from declarator list. But in case we have any definitions or
11585 // additional declaration references:
11586 // 'typedef struct S {} S;'
11587 // 'typedef struct S *S;'
11589 // FinalizeDeclaratorGroup adds these as separate declarations.
11590 Decl *MaybeTagDecl = Group[0];
11591 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11592 Group = Group.slice(1);
11596 // See if there are any new comments that are not attached to a decl.
11597 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11598 if (!Comments.empty() &&
11599 !Comments.back()->isAttached()) {
11600 // There is at least one comment that not attached to a decl.
11601 // Maybe it should be attached to one of these decls?
11603 // Note that this way we pick up not only comments that precede the
11604 // declaration, but also comments that *follow* the declaration -- thanks to
11605 // the lookahead in the lexer: we've consumed the semicolon and looked
11606 // ahead through comments.
11607 for (unsigned i = 0, e = Group.size(); i != e; ++i)
11608 Context.getCommentForDecl(Group[i], &PP);
11612 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11613 /// to introduce parameters into function prototype scope.
11614 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11615 const DeclSpec &DS = D.getDeclSpec();
11617 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11619 // C++03 [dcl.stc]p2 also permits 'auto'.
11620 StorageClass SC = SC_None;
11621 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11623 } else if (getLangOpts().CPlusPlus &&
11624 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11626 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11627 Diag(DS.getStorageClassSpecLoc(),
11628 diag::err_invalid_storage_class_in_func_decl);
11629 D.getMutableDeclSpec().ClearStorageClassSpecs();
11632 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11633 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11634 << DeclSpec::getSpecifierName(TSCS);
11635 if (DS.isInlineSpecified())
11636 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11637 << getLangOpts().CPlusPlus1z;
11638 if (DS.isConstexprSpecified())
11639 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11641 if (DS.isConceptSpecified())
11642 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11644 DiagnoseFunctionSpecifiers(DS);
11646 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11647 QualType parmDeclType = TInfo->getType();
11649 if (getLangOpts().CPlusPlus) {
11650 // Check that there are no default arguments inside the type of this
11652 CheckExtraCXXDefaultArguments(D);
11654 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11655 if (D.getCXXScopeSpec().isSet()) {
11656 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11657 << D.getCXXScopeSpec().getRange();
11658 D.getCXXScopeSpec().clear();
11662 // Ensure we have a valid name
11663 IdentifierInfo *II = nullptr;
11665 II = D.getIdentifier();
11667 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11668 << GetNameForDeclarator(D).getName();
11669 D.setInvalidType(true);
11673 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11675 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11678 if (R.isSingleResult()) {
11679 NamedDecl *PrevDecl = R.getFoundDecl();
11680 if (PrevDecl->isTemplateParameter()) {
11681 // Maybe we will complain about the shadowed template parameter.
11682 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11683 // Just pretend that we didn't see the previous declaration.
11684 PrevDecl = nullptr;
11685 } else if (S->isDeclScope(PrevDecl)) {
11686 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11687 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11689 // Recover by removing the name
11691 D.SetIdentifier(nullptr, D.getIdentifierLoc());
11692 D.setInvalidType(true);
11697 // Temporarily put parameter variables in the translation unit, not
11698 // the enclosing context. This prevents them from accidentally
11699 // looking like class members in C++.
11700 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11702 D.getIdentifierLoc(), II,
11703 parmDeclType, TInfo,
11706 if (D.isInvalidType())
11707 New->setInvalidDecl();
11709 assert(S->isFunctionPrototypeScope());
11710 assert(S->getFunctionPrototypeDepth() >= 1);
11711 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11712 S->getNextFunctionPrototypeIndex());
11714 // Add the parameter declaration into this scope.
11717 IdResolver.AddDecl(New);
11719 ProcessDeclAttributes(S, New, D);
11721 if (D.getDeclSpec().isModulePrivateSpecified())
11722 Diag(New->getLocation(), diag::err_module_private_local)
11723 << 1 << New->getDeclName()
11724 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11725 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11727 if (New->hasAttr<BlocksAttr>()) {
11728 Diag(New->getLocation(), diag::err_block_on_nonlocal);
11733 /// \brief Synthesizes a variable for a parameter arising from a
11735 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11736 SourceLocation Loc,
11738 /* FIXME: setting StartLoc == Loc.
11739 Would it be worth to modify callers so as to provide proper source
11740 location for the unnamed parameters, embedding the parameter's type? */
11741 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11742 T, Context.getTrivialTypeSourceInfo(T, Loc),
11744 Param->setImplicit();
11748 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11749 // Don't diagnose unused-parameter errors in template instantiations; we
11750 // will already have done so in the template itself.
11751 if (inTemplateInstantiation())
11754 for (const ParmVarDecl *Parameter : Parameters) {
11755 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11756 !Parameter->hasAttr<UnusedAttr>()) {
11757 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11758 << Parameter->getDeclName();
11763 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11764 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11765 if (LangOpts.NumLargeByValueCopy == 0) // No check.
11768 // Warn if the return value is pass-by-value and larger than the specified
11770 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11771 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11772 if (Size > LangOpts.NumLargeByValueCopy)
11773 Diag(D->getLocation(), diag::warn_return_value_size)
11774 << D->getDeclName() << Size;
11777 // Warn if any parameter is pass-by-value and larger than the specified
11779 for (const ParmVarDecl *Parameter : Parameters) {
11780 QualType T = Parameter->getType();
11781 if (T->isDependentType() || !T.isPODType(Context))
11783 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11784 if (Size > LangOpts.NumLargeByValueCopy)
11785 Diag(Parameter->getLocation(), diag::warn_parameter_size)
11786 << Parameter->getDeclName() << Size;
11790 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11791 SourceLocation NameLoc, IdentifierInfo *Name,
11792 QualType T, TypeSourceInfo *TSInfo,
11794 // In ARC, infer a lifetime qualifier for appropriate parameter types.
11795 if (getLangOpts().ObjCAutoRefCount &&
11796 T.getObjCLifetime() == Qualifiers::OCL_None &&
11797 T->isObjCLifetimeType()) {
11799 Qualifiers::ObjCLifetime lifetime;
11801 // Special cases for arrays:
11802 // - if it's const, use __unsafe_unretained
11803 // - otherwise, it's an error
11804 if (T->isArrayType()) {
11805 if (!T.isConstQualified()) {
11806 DelayedDiagnostics.add(
11807 sema::DelayedDiagnostic::makeForbiddenType(
11808 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11810 lifetime = Qualifiers::OCL_ExplicitNone;
11812 lifetime = T->getObjCARCImplicitLifetime();
11814 T = Context.getLifetimeQualifiedType(T, lifetime);
11817 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11818 Context.getAdjustedParameterType(T),
11819 TSInfo, SC, nullptr);
11821 // Parameters can not be abstract class types.
11822 // For record types, this is done by the AbstractClassUsageDiagnoser once
11823 // the class has been completely parsed.
11824 if (!CurContext->isRecord() &&
11825 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11826 AbstractParamType))
11827 New->setInvalidDecl();
11829 // Parameter declarators cannot be interface types. All ObjC objects are
11830 // passed by reference.
11831 if (T->isObjCObjectType()) {
11832 SourceLocation TypeEndLoc =
11833 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11835 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11836 << FixItHint::CreateInsertion(TypeEndLoc, "*");
11837 T = Context.getObjCObjectPointerType(T);
11841 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11842 // duration shall not be qualified by an address-space qualifier."
11843 // Since all parameters have automatic store duration, they can not have
11844 // an address space.
11845 if (T.getAddressSpace() != 0) {
11846 // OpenCL allows function arguments declared to be an array of a type
11847 // to be qualified with an address space.
11848 if (!(getLangOpts().OpenCL && T->isArrayType())) {
11849 Diag(NameLoc, diag::err_arg_with_address_space);
11850 New->setInvalidDecl();
11857 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11858 SourceLocation LocAfterDecls) {
11859 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11861 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11862 // for a K&R function.
11863 if (!FTI.hasPrototype) {
11864 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11866 if (FTI.Params[i].Param == nullptr) {
11867 SmallString<256> Code;
11868 llvm::raw_svector_ostream(Code)
11869 << " int " << FTI.Params[i].Ident->getName() << ";\n";
11870 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11871 << FTI.Params[i].Ident
11872 << FixItHint::CreateInsertion(LocAfterDecls, Code);
11874 // Implicitly declare the argument as type 'int' for lack of a better
11876 AttributeFactory attrs;
11877 DeclSpec DS(attrs);
11878 const char* PrevSpec; // unused
11879 unsigned DiagID; // unused
11880 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11881 DiagID, Context.getPrintingPolicy());
11882 // Use the identifier location for the type source range.
11883 DS.SetRangeStart(FTI.Params[i].IdentLoc);
11884 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11885 Declarator ParamD(DS, Declarator::KNRTypeListContext);
11886 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11887 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11894 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11895 MultiTemplateParamsArg TemplateParameterLists,
11896 SkipBodyInfo *SkipBody) {
11897 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11898 assert(D.isFunctionDeclarator() && "Not a function declarator!");
11899 Scope *ParentScope = FnBodyScope->getParent();
11901 D.setFunctionDefinitionKind(FDK_Definition);
11902 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11903 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11906 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11907 Consumer.HandleInlineFunctionDefinition(D);
11910 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11911 const FunctionDecl*& PossibleZeroParamPrototype) {
11912 // Don't warn about invalid declarations.
11913 if (FD->isInvalidDecl())
11916 // Or declarations that aren't global.
11917 if (!FD->isGlobal())
11920 // Don't warn about C++ member functions.
11921 if (isa<CXXMethodDecl>(FD))
11924 // Don't warn about 'main'.
11928 // Don't warn about inline functions.
11929 if (FD->isInlined())
11932 // Don't warn about function templates.
11933 if (FD->getDescribedFunctionTemplate())
11936 // Don't warn about function template specializations.
11937 if (FD->isFunctionTemplateSpecialization())
11940 // Don't warn for OpenCL kernels.
11941 if (FD->hasAttr<OpenCLKernelAttr>())
11944 // Don't warn on explicitly deleted functions.
11945 if (FD->isDeleted())
11948 bool MissingPrototype = true;
11949 for (const FunctionDecl *Prev = FD->getPreviousDecl();
11950 Prev; Prev = Prev->getPreviousDecl()) {
11951 // Ignore any declarations that occur in function or method
11952 // scope, because they aren't visible from the header.
11953 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11956 MissingPrototype = !Prev->getType()->isFunctionProtoType();
11957 if (FD->getNumParams() == 0)
11958 PossibleZeroParamPrototype = Prev;
11962 return MissingPrototype;
11966 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11967 const FunctionDecl *EffectiveDefinition,
11968 SkipBodyInfo *SkipBody) {
11969 const FunctionDecl *Definition = EffectiveDefinition;
11971 if (!FD->isDefined(Definition))
11974 if (canRedefineFunction(Definition, getLangOpts()))
11977 // Don't emit an error when this is redefinition of a typo-corrected
11979 if (TypoCorrectedFunctionDefinitions.count(Definition))
11982 // If we don't have a visible definition of the function, and it's inline or
11983 // a template, skip the new definition.
11984 if (SkipBody && !hasVisibleDefinition(Definition) &&
11985 (Definition->getFormalLinkage() == InternalLinkage ||
11986 Definition->isInlined() ||
11987 Definition->getDescribedFunctionTemplate() ||
11988 Definition->getNumTemplateParameterLists())) {
11989 SkipBody->ShouldSkip = true;
11990 if (auto *TD = Definition->getDescribedFunctionTemplate())
11991 makeMergedDefinitionVisible(TD);
11992 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
11996 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11997 Definition->getStorageClass() == SC_Extern)
11998 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11999 << FD->getDeclName() << getLangOpts().CPlusPlus;
12001 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12003 Diag(Definition->getLocation(), diag::note_previous_definition);
12004 FD->setInvalidDecl();
12007 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12009 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12011 LambdaScopeInfo *LSI = S.PushLambdaScope();
12012 LSI->CallOperator = CallOperator;
12013 LSI->Lambda = LambdaClass;
12014 LSI->ReturnType = CallOperator->getReturnType();
12015 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12017 if (LCD == LCD_None)
12018 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12019 else if (LCD == LCD_ByCopy)
12020 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12021 else if (LCD == LCD_ByRef)
12022 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12023 DeclarationNameInfo DNI = CallOperator->getNameInfo();
12025 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12026 LSI->Mutable = !CallOperator->isConst();
12028 // Add the captures to the LSI so they can be noted as already
12029 // captured within tryCaptureVar.
12030 auto I = LambdaClass->field_begin();
12031 for (const auto &C : LambdaClass->captures()) {
12032 if (C.capturesVariable()) {
12033 VarDecl *VD = C.getCapturedVar();
12034 if (VD->isInitCapture())
12035 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12036 QualType CaptureType = VD->getType();
12037 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12038 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12039 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12040 /*EllipsisLoc*/C.isPackExpansion()
12041 ? C.getEllipsisLoc() : SourceLocation(),
12042 CaptureType, /*Expr*/ nullptr);
12044 } else if (C.capturesThis()) {
12045 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12047 C.getCaptureKind() == LCK_StarThis);
12049 LSI->addVLATypeCapture(C.getLocation(), I->getType());
12055 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12056 SkipBodyInfo *SkipBody) {
12059 FunctionDecl *FD = nullptr;
12061 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12062 FD = FunTmpl->getTemplatedDecl();
12064 FD = cast<FunctionDecl>(D);
12066 // Check for defining attributes before the check for redefinition.
12067 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12068 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12069 FD->dropAttr<AliasAttr>();
12070 FD->setInvalidDecl();
12072 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12073 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12074 FD->dropAttr<IFuncAttr>();
12075 FD->setInvalidDecl();
12078 // See if this is a redefinition.
12079 if (!FD->isLateTemplateParsed()) {
12080 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12082 // If we're skipping the body, we're done. Don't enter the scope.
12083 if (SkipBody && SkipBody->ShouldSkip)
12087 // Mark this function as "will have a body eventually". This lets users to
12088 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12090 FD->setWillHaveBody();
12092 // If we are instantiating a generic lambda call operator, push
12093 // a LambdaScopeInfo onto the function stack. But use the information
12094 // that's already been calculated (ActOnLambdaExpr) to prime the current
12095 // LambdaScopeInfo.
12096 // When the template operator is being specialized, the LambdaScopeInfo,
12097 // has to be properly restored so that tryCaptureVariable doesn't try
12098 // and capture any new variables. In addition when calculating potential
12099 // captures during transformation of nested lambdas, it is necessary to
12100 // have the LSI properly restored.
12101 if (isGenericLambdaCallOperatorSpecialization(FD)) {
12102 assert(inTemplateInstantiation() &&
12103 "There should be an active template instantiation on the stack "
12104 "when instantiating a generic lambda!");
12105 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12107 // Enter a new function scope
12108 PushFunctionScope();
12111 // Builtin functions cannot be defined.
12112 if (unsigned BuiltinID = FD->getBuiltinID()) {
12113 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12114 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12115 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12116 FD->setInvalidDecl();
12120 // The return type of a function definition must be complete
12121 // (C99 6.9.1p3, C++ [dcl.fct]p6).
12122 QualType ResultType = FD->getReturnType();
12123 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12124 !FD->isInvalidDecl() &&
12125 RequireCompleteType(FD->getLocation(), ResultType,
12126 diag::err_func_def_incomplete_result))
12127 FD->setInvalidDecl();
12130 PushDeclContext(FnBodyScope, FD);
12132 // Check the validity of our function parameters
12133 CheckParmsForFunctionDef(FD->parameters(),
12134 /*CheckParameterNames=*/true);
12136 // Add non-parameter declarations already in the function to the current
12139 for (Decl *NPD : FD->decls()) {
12140 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12143 assert(!isa<ParmVarDecl>(NonParmDecl) &&
12144 "parameters should not be in newly created FD yet");
12146 // If the decl has a name, make it accessible in the current scope.
12147 if (NonParmDecl->getDeclName())
12148 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12150 // Similarly, dive into enums and fish their constants out, making them
12151 // accessible in this scope.
12152 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12153 for (auto *EI : ED->enumerators())
12154 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12159 // Introduce our parameters into the function scope
12160 for (auto Param : FD->parameters()) {
12161 Param->setOwningFunction(FD);
12163 // If this has an identifier, add it to the scope stack.
12164 if (Param->getIdentifier() && FnBodyScope) {
12165 CheckShadow(FnBodyScope, Param);
12167 PushOnScopeChains(Param, FnBodyScope);
12171 // Ensure that the function's exception specification is instantiated.
12172 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12173 ResolveExceptionSpec(D->getLocation(), FPT);
12175 // dllimport cannot be applied to non-inline function definitions.
12176 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12177 !FD->isTemplateInstantiation()) {
12178 assert(!FD->hasAttr<DLLExportAttr>());
12179 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12180 FD->setInvalidDecl();
12183 // We want to attach documentation to original Decl (which might be
12184 // a function template).
12185 ActOnDocumentableDecl(D);
12186 if (getCurLexicalContext()->isObjCContainer() &&
12187 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12188 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12189 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12194 /// \brief Given the set of return statements within a function body,
12195 /// compute the variables that are subject to the named return value
12198 /// Each of the variables that is subject to the named return value
12199 /// optimization will be marked as NRVO variables in the AST, and any
12200 /// return statement that has a marked NRVO variable as its NRVO candidate can
12201 /// use the named return value optimization.
12203 /// This function applies a very simplistic algorithm for NRVO: if every return
12204 /// statement in the scope of a variable has the same NRVO candidate, that
12205 /// candidate is an NRVO variable.
12206 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12207 ReturnStmt **Returns = Scope->Returns.data();
12209 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12210 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12211 if (!NRVOCandidate->isNRVOVariable())
12212 Returns[I]->setNRVOCandidate(nullptr);
12217 bool Sema::canDelayFunctionBody(const Declarator &D) {
12218 // We can't delay parsing the body of a constexpr function template (yet).
12219 if (D.getDeclSpec().isConstexprSpecified())
12222 // We can't delay parsing the body of a function template with a deduced
12223 // return type (yet).
12224 if (D.getDeclSpec().hasAutoTypeSpec()) {
12225 // If the placeholder introduces a non-deduced trailing return type,
12226 // we can still delay parsing it.
12227 if (D.getNumTypeObjects()) {
12228 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12229 if (Outer.Kind == DeclaratorChunk::Function &&
12230 Outer.Fun.hasTrailingReturnType()) {
12231 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12232 return Ty.isNull() || !Ty->isUndeducedType();
12241 bool Sema::canSkipFunctionBody(Decl *D) {
12242 // We cannot skip the body of a function (or function template) which is
12243 // constexpr, since we may need to evaluate its body in order to parse the
12244 // rest of the file.
12245 // We cannot skip the body of a function with an undeduced return type,
12246 // because any callers of that function need to know the type.
12247 if (const FunctionDecl *FD = D->getAsFunction())
12248 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12250 return Consumer.shouldSkipFunctionBody(D);
12253 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12254 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12255 FD->setHasSkippedBody();
12256 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12257 MD->setHasSkippedBody();
12261 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12262 return ActOnFinishFunctionBody(D, BodyArg, false);
12265 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12266 bool IsInstantiation) {
12267 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12269 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12270 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12272 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12273 CheckCompletedCoroutineBody(FD, Body);
12277 FD->setWillHaveBody(false);
12279 if (getLangOpts().CPlusPlus14) {
12280 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12281 FD->getReturnType()->isUndeducedType()) {
12282 // If the function has a deduced result type but contains no 'return'
12283 // statements, the result type as written must be exactly 'auto', and
12284 // the deduced result type is 'void'.
12285 if (!FD->getReturnType()->getAs<AutoType>()) {
12286 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12287 << FD->getReturnType();
12288 FD->setInvalidDecl();
12290 // Substitute 'void' for the 'auto' in the type.
12291 TypeLoc ResultType = getReturnTypeLoc(FD);
12292 Context.adjustDeducedFunctionResultType(
12293 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12296 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12297 // In C++11, we don't use 'auto' deduction rules for lambda call
12298 // operators because we don't support return type deduction.
12299 auto *LSI = getCurLambda();
12300 if (LSI->HasImplicitReturnType) {
12301 deduceClosureReturnType(*LSI);
12303 // C++11 [expr.prim.lambda]p4:
12304 // [...] if there are no return statements in the compound-statement
12305 // [the deduced type is] the type void
12307 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12309 // Update the return type to the deduced type.
12310 const FunctionProtoType *Proto =
12311 FD->getType()->getAs<FunctionProtoType>();
12312 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12313 Proto->getExtProtoInfo()));
12317 // The only way to be included in UndefinedButUsed is if there is an
12318 // ODR use before the definition. Avoid the expensive map lookup if this
12319 // is the first declaration.
12320 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12321 if (!FD->isExternallyVisible())
12322 UndefinedButUsed.erase(FD);
12323 else if (FD->isInlined() &&
12324 !LangOpts.GNUInline &&
12325 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12326 UndefinedButUsed.erase(FD);
12329 // If the function implicitly returns zero (like 'main') or is naked,
12330 // don't complain about missing return statements.
12331 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12332 WP.disableCheckFallThrough();
12334 // MSVC permits the use of pure specifier (=0) on function definition,
12335 // defined at class scope, warn about this non-standard construct.
12336 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12337 Diag(FD->getLocation(), diag::ext_pure_function_definition);
12339 if (!FD->isInvalidDecl()) {
12340 // Don't diagnose unused parameters of defaulted or deleted functions.
12341 if (!FD->isDeleted() && !FD->isDefaulted())
12342 DiagnoseUnusedParameters(FD->parameters());
12343 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12344 FD->getReturnType(), FD);
12346 // If this is a structor, we need a vtable.
12347 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12348 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12349 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12350 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12352 // Try to apply the named return value optimization. We have to check
12353 // if we can do this here because lambdas keep return statements around
12354 // to deduce an implicit return type.
12355 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12356 !FD->isDependentContext())
12357 computeNRVO(Body, getCurFunction());
12360 // GNU warning -Wmissing-prototypes:
12361 // Warn if a global function is defined without a previous
12362 // prototype declaration. This warning is issued even if the
12363 // definition itself provides a prototype. The aim is to detect
12364 // global functions that fail to be declared in header files.
12365 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12366 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12367 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12369 if (PossibleZeroParamPrototype) {
12370 // We found a declaration that is not a prototype,
12371 // but that could be a zero-parameter prototype
12372 if (TypeSourceInfo *TI =
12373 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12374 TypeLoc TL = TI->getTypeLoc();
12375 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12376 Diag(PossibleZeroParamPrototype->getLocation(),
12377 diag::note_declaration_not_a_prototype)
12378 << PossibleZeroParamPrototype
12379 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12383 // GNU warning -Wstrict-prototypes
12384 // Warn if K&R function is defined without a previous declaration.
12385 // This warning is issued only if the definition itself does not provide
12386 // a prototype. Only K&R definitions do not provide a prototype.
12387 // An empty list in a function declarator that is part of a definition
12388 // of that function specifies that the function has no parameters
12389 // (C99 6.7.5.3p14)
12390 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12391 !LangOpts.CPlusPlus) {
12392 TypeSourceInfo *TI = FD->getTypeSourceInfo();
12393 TypeLoc TL = TI->getTypeLoc();
12394 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12395 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12399 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12400 const CXXMethodDecl *KeyFunction;
12401 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12403 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12404 MD == KeyFunction->getCanonicalDecl()) {
12405 // Update the key-function state if necessary for this ABI.
12406 if (FD->isInlined() &&
12407 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12408 Context.setNonKeyFunction(MD);
12410 // If the newly-chosen key function is already defined, then we
12411 // need to mark the vtable as used retroactively.
12412 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12413 const FunctionDecl *Definition;
12414 if (KeyFunction && KeyFunction->isDefined(Definition))
12415 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12417 // We just defined they key function; mark the vtable as used.
12418 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12423 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12424 "Function parsing confused");
12425 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12426 assert(MD == getCurMethodDecl() && "Method parsing confused");
12428 if (!MD->isInvalidDecl()) {
12429 DiagnoseUnusedParameters(MD->parameters());
12430 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12431 MD->getReturnType(), MD);
12434 computeNRVO(Body, getCurFunction());
12436 if (getCurFunction()->ObjCShouldCallSuper) {
12437 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12438 << MD->getSelector().getAsString();
12439 getCurFunction()->ObjCShouldCallSuper = false;
12441 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12442 const ObjCMethodDecl *InitMethod = nullptr;
12443 bool isDesignated =
12444 MD->isDesignatedInitializerForTheInterface(&InitMethod);
12445 assert(isDesignated && InitMethod);
12446 (void)isDesignated;
12448 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12449 auto IFace = MD->getClassInterface();
12452 auto SuperD = IFace->getSuperClass();
12455 return SuperD->getIdentifier() ==
12456 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12458 // Don't issue this warning for unavailable inits or direct subclasses
12460 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12461 Diag(MD->getLocation(),
12462 diag::warn_objc_designated_init_missing_super_call);
12463 Diag(InitMethod->getLocation(),
12464 diag::note_objc_designated_init_marked_here);
12466 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12468 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12469 // Don't issue this warning for unavaialable inits.
12470 if (!MD->isUnavailable())
12471 Diag(MD->getLocation(),
12472 diag::warn_objc_secondary_init_missing_init_call);
12473 getCurFunction()->ObjCWarnForNoInitDelegation = false;
12479 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12480 DiagnoseUnguardedAvailabilityViolations(dcl);
12482 assert(!getCurFunction()->ObjCShouldCallSuper &&
12483 "This should only be set for ObjC methods, which should have been "
12484 "handled in the block above.");
12486 // Verify and clean out per-function state.
12487 if (Body && (!FD || !FD->isDefaulted())) {
12488 // C++ constructors that have function-try-blocks can't have return
12489 // statements in the handlers of that block. (C++ [except.handle]p14)
12491 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12492 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12494 // Verify that gotos and switch cases don't jump into scopes illegally.
12495 if (getCurFunction()->NeedsScopeChecking() &&
12496 !PP.isCodeCompletionEnabled())
12497 DiagnoseInvalidJumps(Body);
12499 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12500 if (!Destructor->getParent()->isDependentType())
12501 CheckDestructor(Destructor);
12503 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12504 Destructor->getParent());
12507 // If any errors have occurred, clear out any temporaries that may have
12508 // been leftover. This ensures that these temporaries won't be picked up for
12509 // deletion in some later function.
12510 if (getDiagnostics().hasErrorOccurred() ||
12511 getDiagnostics().getSuppressAllDiagnostics()) {
12512 DiscardCleanupsInEvaluationContext();
12514 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12515 !isa<FunctionTemplateDecl>(dcl)) {
12516 // Since the body is valid, issue any analysis-based warnings that are
12518 ActivePolicy = &WP;
12521 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12522 (!CheckConstexprFunctionDecl(FD) ||
12523 !CheckConstexprFunctionBody(FD, Body)))
12524 FD->setInvalidDecl();
12526 if (FD && FD->hasAttr<NakedAttr>()) {
12527 for (const Stmt *S : Body->children()) {
12528 // Allow local register variables without initializer as they don't
12529 // require prologue.
12530 bool RegisterVariables = false;
12531 if (auto *DS = dyn_cast<DeclStmt>(S)) {
12532 for (const auto *Decl : DS->decls()) {
12533 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12534 RegisterVariables =
12535 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12536 if (!RegisterVariables)
12541 if (RegisterVariables)
12543 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12544 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12545 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12546 FD->setInvalidDecl();
12552 assert(ExprCleanupObjects.size() ==
12553 ExprEvalContexts.back().NumCleanupObjects &&
12554 "Leftover temporaries in function");
12555 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12556 assert(MaybeODRUseExprs.empty() &&
12557 "Leftover expressions for odr-use checking");
12560 if (!IsInstantiation)
12563 PopFunctionScopeInfo(ActivePolicy, dcl);
12564 // If any errors have occurred, clear out any temporaries that may have
12565 // been leftover. This ensures that these temporaries won't be picked up for
12566 // deletion in some later function.
12567 if (getDiagnostics().hasErrorOccurred()) {
12568 DiscardCleanupsInEvaluationContext();
12574 /// When we finish delayed parsing of an attribute, we must attach it to the
12576 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12577 ParsedAttributes &Attrs) {
12578 // Always attach attributes to the underlying decl.
12579 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12580 D = TD->getTemplatedDecl();
12581 ProcessDeclAttributeList(S, D, Attrs.getList());
12583 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12584 if (Method->isStatic())
12585 checkThisInStaticMemberFunctionAttributes(Method);
12588 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12589 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12590 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12591 IdentifierInfo &II, Scope *S) {
12592 // Before we produce a declaration for an implicitly defined
12593 // function, see whether there was a locally-scoped declaration of
12594 // this name as a function or variable. If so, use that
12595 // (non-visible) declaration, and complain about it.
12596 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12597 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12598 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12599 return ExternCPrev;
12602 // Extension in C99. Legal in C90, but warn about it.
12604 if (II.getName().startswith("__builtin_"))
12605 diag_id = diag::warn_builtin_unknown;
12606 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12607 else if (getLangOpts().OpenCL)
12608 diag_id = diag::err_opencl_implicit_function_decl;
12609 else if (getLangOpts().C99)
12610 diag_id = diag::ext_implicit_function_decl;
12612 diag_id = diag::warn_implicit_function_decl;
12613 Diag(Loc, diag_id) << &II;
12615 // Because typo correction is expensive, only do it if the implicit
12616 // function declaration is going to be treated as an error.
12617 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12618 TypoCorrection Corrected;
12620 (Corrected = CorrectTypo(
12621 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12622 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12623 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12624 /*ErrorRecovery*/false);
12627 // Set a Declarator for the implicit definition: int foo();
12629 AttributeFactory attrFactory;
12630 DeclSpec DS(attrFactory);
12632 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12633 Context.getPrintingPolicy());
12634 (void)Error; // Silence warning.
12635 assert(!Error && "Error setting up implicit decl!");
12636 SourceLocation NoLoc;
12637 Declarator D(DS, Declarator::BlockContext);
12638 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12639 /*IsAmbiguous=*/false,
12640 /*LParenLoc=*/NoLoc,
12641 /*Params=*/nullptr,
12643 /*EllipsisLoc=*/NoLoc,
12644 /*RParenLoc=*/NoLoc,
12646 /*RefQualifierIsLvalueRef=*/true,
12647 /*RefQualifierLoc=*/NoLoc,
12648 /*ConstQualifierLoc=*/NoLoc,
12649 /*VolatileQualifierLoc=*/NoLoc,
12650 /*RestrictQualifierLoc=*/NoLoc,
12651 /*MutableLoc=*/NoLoc,
12653 /*ESpecRange=*/SourceRange(),
12654 /*Exceptions=*/nullptr,
12655 /*ExceptionRanges=*/nullptr,
12656 /*NumExceptions=*/0,
12657 /*NoexceptExpr=*/nullptr,
12658 /*ExceptionSpecTokens=*/nullptr,
12659 /*DeclsInPrototype=*/None,
12661 DS.getAttributes(),
12663 D.SetIdentifier(&II, Loc);
12665 // Insert this function into translation-unit scope.
12667 DeclContext *PrevDC = CurContext;
12668 CurContext = Context.getTranslationUnitDecl();
12670 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12673 CurContext = PrevDC;
12675 AddKnownFunctionAttributes(FD);
12680 /// \brief Adds any function attributes that we know a priori based on
12681 /// the declaration of this function.
12683 /// These attributes can apply both to implicitly-declared builtins
12684 /// (like __builtin___printf_chk) or to library-declared functions
12685 /// like NSLog or printf.
12687 /// We need to check for duplicate attributes both here and where user-written
12688 /// attributes are applied to declarations.
12689 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12690 if (FD->isInvalidDecl())
12693 // If this is a built-in function, map its builtin attributes to
12694 // actual attributes.
12695 if (unsigned BuiltinID = FD->getBuiltinID()) {
12696 // Handle printf-formatting attributes.
12697 unsigned FormatIdx;
12699 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12700 if (!FD->hasAttr<FormatAttr>()) {
12701 const char *fmt = "printf";
12702 unsigned int NumParams = FD->getNumParams();
12703 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12704 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12706 FD->addAttr(FormatAttr::CreateImplicit(Context,
12707 &Context.Idents.get(fmt),
12709 HasVAListArg ? 0 : FormatIdx+2,
12710 FD->getLocation()));
12713 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12715 if (!FD->hasAttr<FormatAttr>())
12716 FD->addAttr(FormatAttr::CreateImplicit(Context,
12717 &Context.Idents.get("scanf"),
12719 HasVAListArg ? 0 : FormatIdx+2,
12720 FD->getLocation()));
12723 // Mark const if we don't care about errno and that is the only
12724 // thing preventing the function from being const. This allows
12725 // IRgen to use LLVM intrinsics for such functions.
12726 if (!getLangOpts().MathErrno &&
12727 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12728 if (!FD->hasAttr<ConstAttr>())
12729 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12732 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12733 !FD->hasAttr<ReturnsTwiceAttr>())
12734 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12735 FD->getLocation()));
12736 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12737 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12738 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12739 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12740 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12741 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12742 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12743 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12744 // Add the appropriate attribute, depending on the CUDA compilation mode
12745 // and which target the builtin belongs to. For example, during host
12746 // compilation, aux builtins are __device__, while the rest are __host__.
12747 if (getLangOpts().CUDAIsDevice !=
12748 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12749 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12751 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12755 // If C++ exceptions are enabled but we are told extern "C" functions cannot
12756 // throw, add an implicit nothrow attribute to any extern "C" function we come
12758 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12759 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12760 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12761 if (!FPT || FPT->getExceptionSpecType() == EST_None)
12762 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12765 IdentifierInfo *Name = FD->getIdentifier();
12768 if ((!getLangOpts().CPlusPlus &&
12769 FD->getDeclContext()->isTranslationUnit()) ||
12770 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12771 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12772 LinkageSpecDecl::lang_c)) {
12773 // Okay: this could be a libc/libm/Objective-C function we know
12778 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12779 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12780 // target-specific builtins, perhaps?
12781 if (!FD->hasAttr<FormatAttr>())
12782 FD->addAttr(FormatAttr::CreateImplicit(Context,
12783 &Context.Idents.get("printf"), 2,
12784 Name->isStr("vasprintf") ? 0 : 3,
12785 FD->getLocation()));
12788 if (Name->isStr("__CFStringMakeConstantString")) {
12789 // We already have a __builtin___CFStringMakeConstantString,
12790 // but builds that use -fno-constant-cfstrings don't go through that.
12791 if (!FD->hasAttr<FormatArgAttr>())
12792 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12793 FD->getLocation()));
12797 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12798 TypeSourceInfo *TInfo) {
12799 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12800 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12803 assert(D.isInvalidType() && "no declarator info for valid type");
12804 TInfo = Context.getTrivialTypeSourceInfo(T);
12807 // Scope manipulation handled by caller.
12808 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12810 D.getIdentifierLoc(),
12814 // Bail out immediately if we have an invalid declaration.
12815 if (D.isInvalidType()) {
12816 NewTD->setInvalidDecl();
12820 if (D.getDeclSpec().isModulePrivateSpecified()) {
12821 if (CurContext->isFunctionOrMethod())
12822 Diag(NewTD->getLocation(), diag::err_module_private_local)
12823 << 2 << NewTD->getDeclName()
12824 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12825 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12827 NewTD->setModulePrivate();
12830 // C++ [dcl.typedef]p8:
12831 // If the typedef declaration defines an unnamed class (or
12832 // enum), the first typedef-name declared by the declaration
12833 // to be that class type (or enum type) is used to denote the
12834 // class type (or enum type) for linkage purposes only.
12835 // We need to check whether the type was declared in the declaration.
12836 switch (D.getDeclSpec().getTypeSpecType()) {
12839 case TST_interface:
12842 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12843 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12854 /// \brief Check that this is a valid underlying type for an enum declaration.
12855 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12856 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12857 QualType T = TI->getType();
12859 if (T->isDependentType())
12862 if (const BuiltinType *BT = T->getAs<BuiltinType>())
12863 if (BT->isInteger())
12866 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12870 /// Check whether this is a valid redeclaration of a previous enumeration.
12871 /// \return true if the redeclaration was invalid.
12872 bool Sema::CheckEnumRedeclaration(
12873 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12874 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12875 bool IsFixed = !EnumUnderlyingTy.isNull();
12877 if (IsScoped != Prev->isScoped()) {
12878 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12879 << Prev->isScoped();
12880 Diag(Prev->getLocation(), diag::note_previous_declaration);
12884 if (IsFixed && Prev->isFixed()) {
12885 if (!EnumUnderlyingTy->isDependentType() &&
12886 !Prev->getIntegerType()->isDependentType() &&
12887 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12888 Prev->getIntegerType())) {
12889 // TODO: Highlight the underlying type of the redeclaration.
12890 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12891 << EnumUnderlyingTy << Prev->getIntegerType();
12892 Diag(Prev->getLocation(), diag::note_previous_declaration)
12893 << Prev->getIntegerTypeRange();
12896 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12898 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12900 } else if (IsFixed != Prev->isFixed()) {
12901 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12902 << Prev->isFixed();
12903 Diag(Prev->getLocation(), diag::note_previous_declaration);
12910 /// \brief Get diagnostic %select index for tag kind for
12911 /// redeclaration diagnostic message.
12912 /// WARNING: Indexes apply to particular diagnostics only!
12914 /// \returns diagnostic %select index.
12915 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12917 case TTK_Struct: return 0;
12918 case TTK_Interface: return 1;
12919 case TTK_Class: return 2;
12920 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12924 /// \brief Determine if tag kind is a class-key compatible with
12925 /// class for redeclaration (class, struct, or __interface).
12927 /// \returns true iff the tag kind is compatible.
12928 static bool isClassCompatTagKind(TagTypeKind Tag)
12930 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12933 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12935 if (isa<TypedefDecl>(PrevDecl))
12936 return NTK_Typedef;
12937 else if (isa<TypeAliasDecl>(PrevDecl))
12938 return NTK_TypeAlias;
12939 else if (isa<ClassTemplateDecl>(PrevDecl))
12940 return NTK_Template;
12941 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12942 return NTK_TypeAliasTemplate;
12943 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12944 return NTK_TemplateTemplateArgument;
12947 case TTK_Interface:
12949 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12951 return NTK_NonUnion;
12953 return NTK_NonEnum;
12955 llvm_unreachable("invalid TTK");
12958 /// \brief Determine whether a tag with a given kind is acceptable
12959 /// as a redeclaration of the given tag declaration.
12961 /// \returns true if the new tag kind is acceptable, false otherwise.
12962 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12963 TagTypeKind NewTag, bool isDefinition,
12964 SourceLocation NewTagLoc,
12965 const IdentifierInfo *Name) {
12966 // C++ [dcl.type.elab]p3:
12967 // The class-key or enum keyword present in the
12968 // elaborated-type-specifier shall agree in kind with the
12969 // declaration to which the name in the elaborated-type-specifier
12970 // refers. This rule also applies to the form of
12971 // elaborated-type-specifier that declares a class-name or
12972 // friend class since it can be construed as referring to the
12973 // definition of the class. Thus, in any
12974 // elaborated-type-specifier, the enum keyword shall be used to
12975 // refer to an enumeration (7.2), the union class-key shall be
12976 // used to refer to a union (clause 9), and either the class or
12977 // struct class-key shall be used to refer to a class (clause 9)
12978 // declared using the class or struct class-key.
12979 TagTypeKind OldTag = Previous->getTagKind();
12980 if (!isDefinition || !isClassCompatTagKind(NewTag))
12981 if (OldTag == NewTag)
12984 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12985 // Warn about the struct/class tag mismatch.
12986 bool isTemplate = false;
12987 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12988 isTemplate = Record->getDescribedClassTemplate();
12990 if (inTemplateInstantiation()) {
12991 // In a template instantiation, do not offer fix-its for tag mismatches
12992 // since they usually mess up the template instead of fixing the problem.
12993 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12994 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12995 << getRedeclDiagFromTagKind(OldTag);
12999 if (isDefinition) {
13000 // On definitions, check previous tags and issue a fix-it for each
13001 // one that doesn't match the current tag.
13002 if (Previous->getDefinition()) {
13003 // Don't suggest fix-its for redefinitions.
13007 bool previousMismatch = false;
13008 for (auto I : Previous->redecls()) {
13009 if (I->getTagKind() != NewTag) {
13010 if (!previousMismatch) {
13011 previousMismatch = true;
13012 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13013 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13014 << getRedeclDiagFromTagKind(I->getTagKind());
13016 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13017 << getRedeclDiagFromTagKind(NewTag)
13018 << FixItHint::CreateReplacement(I->getInnerLocStart(),
13019 TypeWithKeyword::getTagTypeKindName(NewTag));
13025 // Check for a previous definition. If current tag and definition
13026 // are same type, do nothing. If no definition, but disagree with
13027 // with previous tag type, give a warning, but no fix-it.
13028 const TagDecl *Redecl = Previous->getDefinition() ?
13029 Previous->getDefinition() : Previous;
13030 if (Redecl->getTagKind() == NewTag) {
13034 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13035 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13036 << getRedeclDiagFromTagKind(OldTag);
13037 Diag(Redecl->getLocation(), diag::note_previous_use);
13039 // If there is a previous definition, suggest a fix-it.
13040 if (Previous->getDefinition()) {
13041 Diag(NewTagLoc, diag::note_struct_class_suggestion)
13042 << getRedeclDiagFromTagKind(Redecl->getTagKind())
13043 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13044 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13052 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13053 /// from an outer enclosing namespace or file scope inside a friend declaration.
13054 /// This should provide the commented out code in the following snippet:
13058 /// struct Y { friend struct /*N::*/ X; };
13061 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13062 SourceLocation NameLoc) {
13063 // While the decl is in a namespace, do repeated lookup of that name and see
13064 // if we get the same namespace back. If we do not, continue until
13065 // translation unit scope, at which point we have a fully qualified NNS.
13066 SmallVector<IdentifierInfo *, 4> Namespaces;
13067 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13068 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13069 // This tag should be declared in a namespace, which can only be enclosed by
13070 // other namespaces. Bail if there's an anonymous namespace in the chain.
13071 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13072 if (!Namespace || Namespace->isAnonymousNamespace())
13073 return FixItHint();
13074 IdentifierInfo *II = Namespace->getIdentifier();
13075 Namespaces.push_back(II);
13076 NamedDecl *Lookup = SemaRef.LookupSingleName(
13077 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13078 if (Lookup == Namespace)
13082 // Once we have all the namespaces, reverse them to go outermost first, and
13084 SmallString<64> Insertion;
13085 llvm::raw_svector_ostream OS(Insertion);
13086 if (DC->isTranslationUnit())
13088 std::reverse(Namespaces.begin(), Namespaces.end());
13089 for (auto *II : Namespaces)
13090 OS << II->getName() << "::";
13091 return FixItHint::CreateInsertion(NameLoc, Insertion);
13094 /// \brief Determine whether a tag originally declared in context \p OldDC can
13095 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13096 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13097 /// using-declaration).
13098 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13099 DeclContext *NewDC) {
13100 OldDC = OldDC->getRedeclContext();
13101 NewDC = NewDC->getRedeclContext();
13103 if (OldDC->Equals(NewDC))
13106 // In MSVC mode, we allow a redeclaration if the contexts are related (either
13107 // encloses the other).
13108 if (S.getLangOpts().MSVCCompat &&
13109 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13115 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
13116 /// former case, Name will be non-null. In the later case, Name will be null.
13117 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13118 /// reference/declaration/definition of a tag.
13120 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13121 /// trailing-type-specifier) other than one in an alias-declaration.
13123 /// \param SkipBody If non-null, will be set to indicate if the caller should
13124 /// skip the definition of this tag and treat it as if it were a declaration.
13125 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13126 SourceLocation KWLoc, CXXScopeSpec &SS,
13127 IdentifierInfo *Name, SourceLocation NameLoc,
13128 AttributeList *Attr, AccessSpecifier AS,
13129 SourceLocation ModulePrivateLoc,
13130 MultiTemplateParamsArg TemplateParameterLists,
13131 bool &OwnedDecl, bool &IsDependent,
13132 SourceLocation ScopedEnumKWLoc,
13133 bool ScopedEnumUsesClassTag,
13134 TypeResult UnderlyingType,
13135 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13136 SkipBodyInfo *SkipBody) {
13137 // If this is not a definition, it must have a name.
13138 IdentifierInfo *OrigName = Name;
13139 assert((Name != nullptr || TUK == TUK_Definition) &&
13140 "Nameless record must be a definition!");
13141 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13144 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13145 bool ScopedEnum = ScopedEnumKWLoc.isValid();
13147 // FIXME: Check member specializations more carefully.
13148 bool isMemberSpecialization = false;
13149 bool Invalid = false;
13151 // We only need to do this matching if we have template parameters
13152 // or a scope specifier, which also conveniently avoids this work
13153 // for non-C++ cases.
13154 if (TemplateParameterLists.size() > 0 ||
13155 (SS.isNotEmpty() && TUK != TUK_Reference)) {
13156 if (TemplateParameterList *TemplateParams =
13157 MatchTemplateParametersToScopeSpecifier(
13158 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13159 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13160 if (Kind == TTK_Enum) {
13161 Diag(KWLoc, diag::err_enum_template);
13165 if (TemplateParams->size() > 0) {
13166 // This is a declaration or definition of a class template (which may
13167 // be a member of another template).
13173 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13174 SS, Name, NameLoc, Attr,
13175 TemplateParams, AS,
13177 /*FriendLoc*/SourceLocation(),
13178 TemplateParameterLists.size()-1,
13179 TemplateParameterLists.data(),
13181 return Result.get();
13183 // The "template<>" header is extraneous.
13184 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13185 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13186 isMemberSpecialization = true;
13191 // Figure out the underlying type if this a enum declaration. We need to do
13192 // this early, because it's needed to detect if this is an incompatible
13194 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13195 bool EnumUnderlyingIsImplicit = false;
13197 if (Kind == TTK_Enum) {
13198 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13199 // No underlying type explicitly specified, or we failed to parse the
13200 // type, default to int.
13201 EnumUnderlying = Context.IntTy.getTypePtr();
13202 else if (UnderlyingType.get()) {
13203 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13204 // integral type; any cv-qualification is ignored.
13205 TypeSourceInfo *TI = nullptr;
13206 GetTypeFromParser(UnderlyingType.get(), &TI);
13207 EnumUnderlying = TI;
13209 if (CheckEnumUnderlyingType(TI))
13210 // Recover by falling back to int.
13211 EnumUnderlying = Context.IntTy.getTypePtr();
13213 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13214 UPPC_FixedUnderlyingType))
13215 EnumUnderlying = Context.IntTy.getTypePtr();
13217 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13218 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13219 // Microsoft enums are always of int type.
13220 EnumUnderlying = Context.IntTy.getTypePtr();
13221 EnumUnderlyingIsImplicit = true;
13226 DeclContext *SearchDC = CurContext;
13227 DeclContext *DC = CurContext;
13228 bool isStdBadAlloc = false;
13229 bool isStdAlignValT = false;
13231 RedeclarationKind Redecl = ForRedeclaration;
13232 if (TUK == TUK_Friend || TUK == TUK_Reference)
13233 Redecl = NotForRedeclaration;
13235 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13236 /// implemented asks for structural equivalence checking, the returned decl
13237 /// here is passed back to the parser, allowing the tag body to be parsed.
13238 auto createTagFromNewDecl = [&]() -> TagDecl * {
13239 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13240 // If there is an identifier, use the location of the identifier as the
13241 // location of the decl, otherwise use the location of the struct/union
13243 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13244 TagDecl *New = nullptr;
13246 if (Kind == TTK_Enum) {
13247 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13248 ScopedEnum, ScopedEnumUsesClassTag,
13249 !EnumUnderlying.isNull());
13250 // If this is an undefined enum, bail.
13251 if (TUK != TUK_Definition && !Invalid)
13253 if (EnumUnderlying) {
13254 EnumDecl *ED = cast<EnumDecl>(New);
13255 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13256 ED->setIntegerTypeSourceInfo(TI);
13258 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13259 ED->setPromotionType(ED->getIntegerType());
13261 } else { // struct/union
13262 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13266 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13267 // Add alignment attributes if necessary; these attributes are checked
13268 // when the ASTContext lays out the structure.
13270 // It is important for implementing the correct semantics that this
13271 // happen here (in ActOnTag). The #pragma pack stack is
13272 // maintained as a result of parser callbacks which can occur at
13273 // many points during the parsing of a struct declaration (because
13274 // the #pragma tokens are effectively skipped over during the
13275 // parsing of the struct).
13276 if (TUK == TUK_Definition) {
13277 AddAlignmentAttributesForRecord(RD);
13278 AddMsStructLayoutForRecord(RD);
13284 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13285 if (Name && SS.isNotEmpty()) {
13286 // We have a nested-name tag ('struct foo::bar').
13288 // Check for invalid 'foo::'.
13289 if (SS.isInvalid()) {
13291 goto CreateNewDecl;
13294 // If this is a friend or a reference to a class in a dependent
13295 // context, don't try to make a decl for it.
13296 if (TUK == TUK_Friend || TUK == TUK_Reference) {
13297 DC = computeDeclContext(SS, false);
13299 IsDependent = true;
13303 DC = computeDeclContext(SS, true);
13305 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13311 if (RequireCompleteDeclContext(SS, DC))
13315 // Look-up name inside 'foo::'.
13316 LookupQualifiedName(Previous, DC);
13318 if (Previous.isAmbiguous())
13321 if (Previous.empty()) {
13322 // Name lookup did not find anything. However, if the
13323 // nested-name-specifier refers to the current instantiation,
13324 // and that current instantiation has any dependent base
13325 // classes, we might find something at instantiation time: treat
13326 // this as a dependent elaborated-type-specifier.
13327 // But this only makes any sense for reference-like lookups.
13328 if (Previous.wasNotFoundInCurrentInstantiation() &&
13329 (TUK == TUK_Reference || TUK == TUK_Friend)) {
13330 IsDependent = true;
13334 // A tag 'foo::bar' must already exist.
13335 Diag(NameLoc, diag::err_not_tag_in_scope)
13336 << Kind << Name << DC << SS.getRange();
13339 goto CreateNewDecl;
13342 // C++14 [class.mem]p14:
13343 // If T is the name of a class, then each of the following shall have a
13344 // name different from T:
13345 // -- every member of class T that is itself a type
13346 if (TUK != TUK_Reference && TUK != TUK_Friend &&
13347 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13350 // If this is a named struct, check to see if there was a previous forward
13351 // declaration or definition.
13352 // FIXME: We're looking into outer scopes here, even when we
13353 // shouldn't be. Doing so can result in ambiguities that we
13354 // shouldn't be diagnosing.
13355 LookupName(Previous, S);
13357 // When declaring or defining a tag, ignore ambiguities introduced
13358 // by types using'ed into this scope.
13359 if (Previous.isAmbiguous() &&
13360 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13361 LookupResult::Filter F = Previous.makeFilter();
13362 while (F.hasNext()) {
13363 NamedDecl *ND = F.next();
13364 if (!ND->getDeclContext()->getRedeclContext()->Equals(
13365 SearchDC->getRedeclContext()))
13371 // C++11 [namespace.memdef]p3:
13372 // If the name in a friend declaration is neither qualified nor
13373 // a template-id and the declaration is a function or an
13374 // elaborated-type-specifier, the lookup to determine whether
13375 // the entity has been previously declared shall not consider
13376 // any scopes outside the innermost enclosing namespace.
13378 // MSVC doesn't implement the above rule for types, so a friend tag
13379 // declaration may be a redeclaration of a type declared in an enclosing
13380 // scope. They do implement this rule for friend functions.
13382 // Does it matter that this should be by scope instead of by
13383 // semantic context?
13384 if (!Previous.empty() && TUK == TUK_Friend) {
13385 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13386 LookupResult::Filter F = Previous.makeFilter();
13387 bool FriendSawTagOutsideEnclosingNamespace = false;
13388 while (F.hasNext()) {
13389 NamedDecl *ND = F.next();
13390 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13391 if (DC->isFileContext() &&
13392 !EnclosingNS->Encloses(ND->getDeclContext())) {
13393 if (getLangOpts().MSVCCompat)
13394 FriendSawTagOutsideEnclosingNamespace = true;
13401 // Diagnose this MSVC extension in the easy case where lookup would have
13402 // unambiguously found something outside the enclosing namespace.
13403 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13404 NamedDecl *ND = Previous.getFoundDecl();
13405 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13406 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13410 // Note: there used to be some attempt at recovery here.
13411 if (Previous.isAmbiguous())
13414 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13415 // FIXME: This makes sure that we ignore the contexts associated
13416 // with C structs, unions, and enums when looking for a matching
13417 // tag declaration or definition. See the similar lookup tweak
13418 // in Sema::LookupName; is there a better way to deal with this?
13419 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13420 SearchDC = SearchDC->getParent();
13424 if (Previous.isSingleResult() &&
13425 Previous.getFoundDecl()->isTemplateParameter()) {
13426 // Maybe we will complain about the shadowed template parameter.
13427 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13428 // Just pretend that we didn't see the previous declaration.
13432 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13433 DC->Equals(getStdNamespace())) {
13434 if (Name->isStr("bad_alloc")) {
13435 // This is a declaration of or a reference to "std::bad_alloc".
13436 isStdBadAlloc = true;
13438 // If std::bad_alloc has been implicitly declared (but made invisible to
13439 // name lookup), fill in this implicit declaration as the previous
13440 // declaration, so that the declarations get chained appropriately.
13441 if (Previous.empty() && StdBadAlloc)
13442 Previous.addDecl(getStdBadAlloc());
13443 } else if (Name->isStr("align_val_t")) {
13444 isStdAlignValT = true;
13445 if (Previous.empty() && StdAlignValT)
13446 Previous.addDecl(getStdAlignValT());
13450 // If we didn't find a previous declaration, and this is a reference
13451 // (or friend reference), move to the correct scope. In C++, we
13452 // also need to do a redeclaration lookup there, just in case
13453 // there's a shadow friend decl.
13454 if (Name && Previous.empty() &&
13455 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13456 if (Invalid) goto CreateNewDecl;
13457 assert(SS.isEmpty());
13459 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13460 // C++ [basic.scope.pdecl]p5:
13461 // -- for an elaborated-type-specifier of the form
13463 // class-key identifier
13465 // if the elaborated-type-specifier is used in the
13466 // decl-specifier-seq or parameter-declaration-clause of a
13467 // function defined in namespace scope, the identifier is
13468 // declared as a class-name in the namespace that contains
13469 // the declaration; otherwise, except as a friend
13470 // declaration, the identifier is declared in the smallest
13471 // non-class, non-function-prototype scope that contains the
13474 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13475 // C structs and unions.
13477 // It is an error in C++ to declare (rather than define) an enum
13478 // type, including via an elaborated type specifier. We'll
13479 // diagnose that later; for now, declare the enum in the same
13480 // scope as we would have picked for any other tag type.
13482 // GNU C also supports this behavior as part of its incomplete
13483 // enum types extension, while GNU C++ does not.
13485 // Find the context where we'll be declaring the tag.
13486 // FIXME: We would like to maintain the current DeclContext as the
13487 // lexical context,
13488 SearchDC = getTagInjectionContext(SearchDC);
13490 // Find the scope where we'll be declaring the tag.
13491 S = getTagInjectionScope(S, getLangOpts());
13493 assert(TUK == TUK_Friend);
13494 // C++ [namespace.memdef]p3:
13495 // If a friend declaration in a non-local class first declares a
13496 // class or function, the friend class or function is a member of
13497 // the innermost enclosing namespace.
13498 SearchDC = SearchDC->getEnclosingNamespaceContext();
13501 // In C++, we need to do a redeclaration lookup to properly
13502 // diagnose some problems.
13503 // FIXME: redeclaration lookup is also used (with and without C++) to find a
13504 // hidden declaration so that we don't get ambiguity errors when using a
13505 // type declared by an elaborated-type-specifier. In C that is not correct
13506 // and we should instead merge compatible types found by lookup.
13507 if (getLangOpts().CPlusPlus) {
13508 Previous.setRedeclarationKind(ForRedeclaration);
13509 LookupQualifiedName(Previous, SearchDC);
13511 Previous.setRedeclarationKind(ForRedeclaration);
13512 LookupName(Previous, S);
13516 // If we have a known previous declaration to use, then use it.
13517 if (Previous.empty() && SkipBody && SkipBody->Previous)
13518 Previous.addDecl(SkipBody->Previous);
13520 if (!Previous.empty()) {
13521 NamedDecl *PrevDecl = Previous.getFoundDecl();
13522 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13524 // It's okay to have a tag decl in the same scope as a typedef
13525 // which hides a tag decl in the same scope. Finding this
13526 // insanity with a redeclaration lookup can only actually happen
13529 // This is also okay for elaborated-type-specifiers, which is
13530 // technically forbidden by the current standard but which is
13531 // okay according to the likely resolution of an open issue;
13532 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13533 if (getLangOpts().CPlusPlus) {
13534 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13535 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13536 TagDecl *Tag = TT->getDecl();
13537 if (Tag->getDeclName() == Name &&
13538 Tag->getDeclContext()->getRedeclContext()
13539 ->Equals(TD->getDeclContext()->getRedeclContext())) {
13542 Previous.addDecl(Tag);
13543 Previous.resolveKind();
13549 // If this is a redeclaration of a using shadow declaration, it must
13550 // declare a tag in the same context. In MSVC mode, we allow a
13551 // redefinition if either context is within the other.
13552 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13553 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13554 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13555 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13556 !(OldTag && isAcceptableTagRedeclContext(
13557 *this, OldTag->getDeclContext(), SearchDC))) {
13558 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13559 Diag(Shadow->getTargetDecl()->getLocation(),
13560 diag::note_using_decl_target);
13561 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13563 // Recover by ignoring the old declaration.
13565 goto CreateNewDecl;
13569 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13570 // If this is a use of a previous tag, or if the tag is already declared
13571 // in the same scope (so that the definition/declaration completes or
13572 // rementions the tag), reuse the decl.
13573 if (TUK == TUK_Reference || TUK == TUK_Friend ||
13574 isDeclInScope(DirectPrevDecl, SearchDC, S,
13575 SS.isNotEmpty() || isMemberSpecialization)) {
13576 // Make sure that this wasn't declared as an enum and now used as a
13577 // struct or something similar.
13578 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13579 TUK == TUK_Definition, KWLoc,
13581 bool SafeToContinue
13582 = (PrevTagDecl->getTagKind() != TTK_Enum &&
13584 if (SafeToContinue)
13585 Diag(KWLoc, diag::err_use_with_wrong_tag)
13587 << FixItHint::CreateReplacement(SourceRange(KWLoc),
13588 PrevTagDecl->getKindName());
13590 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13591 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13593 if (SafeToContinue)
13594 Kind = PrevTagDecl->getTagKind();
13596 // Recover by making this an anonymous redefinition.
13603 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13604 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13606 // If this is an elaborated-type-specifier for a scoped enumeration,
13607 // the 'class' keyword is not necessary and not permitted.
13608 if (TUK == TUK_Reference || TUK == TUK_Friend) {
13610 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13611 << PrevEnum->isScoped()
13612 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13613 return PrevTagDecl;
13616 QualType EnumUnderlyingTy;
13617 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13618 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13619 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13620 EnumUnderlyingTy = QualType(T, 0);
13622 // All conflicts with previous declarations are recovered by
13623 // returning the previous declaration, unless this is a definition,
13624 // in which case we want the caller to bail out.
13625 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13626 ScopedEnum, EnumUnderlyingTy,
13627 EnumUnderlyingIsImplicit, PrevEnum))
13628 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13631 // C++11 [class.mem]p1:
13632 // A member shall not be declared twice in the member-specification,
13633 // except that a nested class or member class template can be declared
13634 // and then later defined.
13635 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13636 S->isDeclScope(PrevDecl)) {
13637 Diag(NameLoc, diag::ext_member_redeclared);
13638 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13642 // If this is a use, just return the declaration we found, unless
13643 // we have attributes.
13644 if (TUK == TUK_Reference || TUK == TUK_Friend) {
13646 // FIXME: Diagnose these attributes. For now, we create a new
13647 // declaration to hold them.
13648 } else if (TUK == TUK_Reference &&
13649 (PrevTagDecl->getFriendObjectKind() ==
13650 Decl::FOK_Undeclared ||
13651 PrevDecl->getOwningModule() != getCurrentModule()) &&
13653 // This declaration is a reference to an existing entity, but
13654 // has different visibility from that entity: it either makes
13655 // a friend visible or it makes a type visible in a new module.
13656 // In either case, create a new declaration. We only do this if
13657 // the declaration would have meant the same thing if no prior
13658 // declaration were found, that is, if it was found in the same
13659 // scope where we would have injected a declaration.
13660 if (!getTagInjectionContext(CurContext)->getRedeclContext()
13661 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13662 return PrevTagDecl;
13663 // This is in the injected scope, create a new declaration in
13665 S = getTagInjectionScope(S, getLangOpts());
13667 return PrevTagDecl;
13671 // Diagnose attempts to redefine a tag.
13672 if (TUK == TUK_Definition) {
13673 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13674 // If we're defining a specialization and the previous definition
13675 // is from an implicit instantiation, don't emit an error
13676 // here; we'll catch this in the general case below.
13677 bool IsExplicitSpecializationAfterInstantiation = false;
13678 if (isMemberSpecialization) {
13679 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13680 IsExplicitSpecializationAfterInstantiation =
13681 RD->getTemplateSpecializationKind() !=
13682 TSK_ExplicitSpecialization;
13683 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13684 IsExplicitSpecializationAfterInstantiation =
13685 ED->getTemplateSpecializationKind() !=
13686 TSK_ExplicitSpecialization;
13689 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
13690 // not keep more that one definition around (merge them). However,
13691 // ensure the decl passes the structural compatibility check in
13692 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
13693 NamedDecl *Hidden = nullptr;
13694 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
13695 // There is a definition of this tag, but it is not visible. We
13696 // explicitly make use of C++'s one definition rule here, and
13697 // assume that this definition is identical to the hidden one
13698 // we already have. Make the existing definition visible and
13699 // use it in place of this one.
13700 if (!getLangOpts().CPlusPlus) {
13701 // Postpone making the old definition visible until after we
13702 // complete parsing the new one and do the structural
13704 SkipBody->CheckSameAsPrevious = true;
13705 SkipBody->New = createTagFromNewDecl();
13706 SkipBody->Previous = Hidden;
13708 SkipBody->ShouldSkip = true;
13709 makeMergedDefinitionVisible(Hidden);
13712 } else if (!IsExplicitSpecializationAfterInstantiation) {
13713 // A redeclaration in function prototype scope in C isn't
13714 // visible elsewhere, so merely issue a warning.
13715 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13716 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13718 Diag(NameLoc, diag::err_redefinition) << Name;
13719 notePreviousDefinition(Def,
13720 NameLoc.isValid() ? NameLoc : KWLoc);
13721 // If this is a redefinition, recover by making this
13722 // struct be anonymous, which will make any later
13723 // references get the previous definition.
13729 // If the type is currently being defined, complain
13730 // about a nested redefinition.
13731 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13732 if (TD->isBeingDefined()) {
13733 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13734 Diag(PrevTagDecl->getLocation(),
13735 diag::note_previous_definition);
13742 // Okay, this is definition of a previously declared or referenced
13743 // tag. We're going to create a new Decl for it.
13746 // Okay, we're going to make a redeclaration. If this is some kind
13747 // of reference, make sure we build the redeclaration in the same DC
13748 // as the original, and ignore the current access specifier.
13749 if (TUK == TUK_Friend || TUK == TUK_Reference) {
13750 SearchDC = PrevTagDecl->getDeclContext();
13754 // If we get here we have (another) forward declaration or we
13755 // have a definition. Just create a new decl.
13758 // If we get here, this is a definition of a new tag type in a nested
13759 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13760 // new decl/type. We set PrevDecl to NULL so that the entities
13761 // have distinct types.
13764 // If we get here, we're going to create a new Decl. If PrevDecl
13765 // is non-NULL, it's a definition of the tag declared by
13766 // PrevDecl. If it's NULL, we have a new definition.
13768 // Otherwise, PrevDecl is not a tag, but was found with tag
13769 // lookup. This is only actually possible in C++, where a few
13770 // things like templates still live in the tag namespace.
13772 // Use a better diagnostic if an elaborated-type-specifier
13773 // found the wrong kind of type on the first
13774 // (non-redeclaration) lookup.
13775 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13776 !Previous.isForRedeclaration()) {
13777 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13778 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13780 Diag(PrevDecl->getLocation(), diag::note_declared_at);
13783 // Otherwise, only diagnose if the declaration is in scope.
13784 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13785 SS.isNotEmpty() || isMemberSpecialization)) {
13788 // Diagnose implicit declarations introduced by elaborated types.
13789 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13790 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13791 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13792 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13795 // Otherwise it's a declaration. Call out a particularly common
13797 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13799 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13800 Diag(NameLoc, diag::err_tag_definition_of_typedef)
13801 << Name << Kind << TND->getUnderlyingType();
13802 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13805 // Otherwise, diagnose.
13807 // The tag name clashes with something else in the target scope,
13808 // issue an error and recover by making this tag be anonymous.
13809 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13810 notePreviousDefinition(PrevDecl, NameLoc);
13815 // The existing declaration isn't relevant to us; we're in a
13816 // new scope, so clear out the previous declaration.
13823 TagDecl *PrevDecl = nullptr;
13824 if (Previous.isSingleResult())
13825 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13827 // If there is an identifier, use the location of the identifier as the
13828 // location of the decl, otherwise use the location of the struct/union
13830 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13832 // Otherwise, create a new declaration. If there is a previous
13833 // declaration of the same entity, the two will be linked via
13837 bool IsForwardReference = false;
13838 if (Kind == TTK_Enum) {
13839 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13840 // enum X { A, B, C } D; D should chain to X.
13841 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13842 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13843 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13845 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13846 StdAlignValT = cast<EnumDecl>(New);
13848 // If this is an undefined enum, warn.
13849 if (TUK != TUK_Definition && !Invalid) {
13851 if (!EnumUnderlyingIsImplicit &&
13852 (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13853 cast<EnumDecl>(New)->isFixed()) {
13854 // C++0x: 7.2p2: opaque-enum-declaration.
13855 // Conflicts are diagnosed above. Do nothing.
13857 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13858 Diag(Loc, diag::ext_forward_ref_enum_def)
13860 Diag(Def->getLocation(), diag::note_previous_definition);
13862 unsigned DiagID = diag::ext_forward_ref_enum;
13863 if (getLangOpts().MSVCCompat)
13864 DiagID = diag::ext_ms_forward_ref_enum;
13865 else if (getLangOpts().CPlusPlus)
13866 DiagID = diag::err_forward_ref_enum;
13869 // If this is a forward-declared reference to an enumeration, make a
13870 // note of it; we won't actually be introducing the declaration into
13871 // the declaration context.
13872 if (TUK == TUK_Reference)
13873 IsForwardReference = true;
13877 if (EnumUnderlying) {
13878 EnumDecl *ED = cast<EnumDecl>(New);
13879 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13880 ED->setIntegerTypeSourceInfo(TI);
13882 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13883 ED->setPromotionType(ED->getIntegerType());
13886 // struct/union/class
13888 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13889 // struct X { int A; } D; D should chain to X.
13890 if (getLangOpts().CPlusPlus) {
13891 // FIXME: Look for a way to use RecordDecl for simple structs.
13892 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13893 cast_or_null<CXXRecordDecl>(PrevDecl));
13895 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13896 StdBadAlloc = cast<CXXRecordDecl>(New);
13898 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13899 cast_or_null<RecordDecl>(PrevDecl));
13902 // C++11 [dcl.type]p3:
13903 // A type-specifier-seq shall not define a class or enumeration [...].
13904 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
13905 TUK == TUK_Definition) {
13906 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13907 << Context.getTagDeclType(New);
13911 // Maybe add qualifier info.
13912 if (SS.isNotEmpty()) {
13914 // If this is either a declaration or a definition, check the
13915 // nested-name-specifier against the current context. We don't do this
13916 // for explicit specializations, because they have similar checking
13917 // (with more specific diagnostics) in the call to
13918 // CheckMemberSpecialization, below.
13919 if (!isMemberSpecialization &&
13920 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13921 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13924 New->setQualifierInfo(SS.getWithLocInContext(Context));
13925 if (TemplateParameterLists.size() > 0) {
13926 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13933 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13934 // Add alignment attributes if necessary; these attributes are checked when
13935 // the ASTContext lays out the structure.
13937 // It is important for implementing the correct semantics that this
13938 // happen here (in ActOnTag). The #pragma pack stack is
13939 // maintained as a result of parser callbacks which can occur at
13940 // many points during the parsing of a struct declaration (because
13941 // the #pragma tokens are effectively skipped over during the
13942 // parsing of the struct).
13943 if (TUK == TUK_Definition) {
13944 AddAlignmentAttributesForRecord(RD);
13945 AddMsStructLayoutForRecord(RD);
13949 if (ModulePrivateLoc.isValid()) {
13950 if (isMemberSpecialization)
13951 Diag(New->getLocation(), diag::err_module_private_specialization)
13953 << FixItHint::CreateRemoval(ModulePrivateLoc);
13954 // __module_private__ does not apply to local classes. However, we only
13955 // diagnose this as an error when the declaration specifiers are
13956 // freestanding. Here, we just ignore the __module_private__.
13957 else if (!SearchDC->isFunctionOrMethod())
13958 New->setModulePrivate();
13961 // If this is a specialization of a member class (of a class template),
13962 // check the specialization.
13963 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13966 // If we're declaring or defining a tag in function prototype scope in C,
13967 // note that this type can only be used within the function and add it to
13968 // the list of decls to inject into the function definition scope.
13969 if ((Name || Kind == TTK_Enum) &&
13970 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13971 if (getLangOpts().CPlusPlus) {
13972 // C++ [dcl.fct]p6:
13973 // Types shall not be defined in return or parameter types.
13974 if (TUK == TUK_Definition && !IsTypeSpecifier) {
13975 Diag(Loc, diag::err_type_defined_in_param_type)
13979 } else if (!PrevDecl) {
13980 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13985 New->setInvalidDecl();
13987 // Set the lexical context. If the tag has a C++ scope specifier, the
13988 // lexical context will be different from the semantic context.
13989 New->setLexicalDeclContext(CurContext);
13991 // Mark this as a friend decl if applicable.
13992 // In Microsoft mode, a friend declaration also acts as a forward
13993 // declaration so we always pass true to setObjectOfFriendDecl to make
13994 // the tag name visible.
13995 if (TUK == TUK_Friend)
13996 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13998 // Set the access specifier.
13999 if (!Invalid && SearchDC->isRecord())
14000 SetMemberAccessSpecifier(New, PrevDecl, AS);
14002 if (TUK == TUK_Definition)
14003 New->startDefinition();
14006 ProcessDeclAttributeList(S, New, Attr);
14007 AddPragmaAttributes(S, New);
14009 // If this has an identifier, add it to the scope stack.
14010 if (TUK == TUK_Friend) {
14011 // We might be replacing an existing declaration in the lookup tables;
14012 // if so, borrow its access specifier.
14014 New->setAccess(PrevDecl->getAccess());
14016 DeclContext *DC = New->getDeclContext()->getRedeclContext();
14017 DC->makeDeclVisibleInContext(New);
14018 if (Name) // can be null along some error paths
14019 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14020 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14022 S = getNonFieldDeclScope(S);
14023 PushOnScopeChains(New, S, !IsForwardReference);
14024 if (IsForwardReference)
14025 SearchDC->makeDeclVisibleInContext(New);
14027 CurContext->addDecl(New);
14030 // If this is the C FILE type, notify the AST context.
14031 if (IdentifierInfo *II = New->getIdentifier())
14032 if (!New->isInvalidDecl() &&
14033 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14035 Context.setFILEDecl(New);
14038 mergeDeclAttributes(New, PrevDecl);
14040 // If there's a #pragma GCC visibility in scope, set the visibility of this
14042 AddPushedVisibilityAttribute(New);
14044 if (isMemberSpecialization && !New->isInvalidDecl())
14045 CompleteMemberSpecialization(New, Previous);
14048 // In C++, don't return an invalid declaration. We can't recover well from
14049 // the cases where we make the type anonymous.
14050 if (Invalid && getLangOpts().CPlusPlus) {
14051 if (New->isBeingDefined())
14052 if (auto RD = dyn_cast<RecordDecl>(New))
14053 RD->completeDefinition();
14060 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14061 AdjustDeclIfTemplate(TagD);
14062 TagDecl *Tag = cast<TagDecl>(TagD);
14064 // Enter the tag context.
14065 PushDeclContext(S, Tag);
14067 ActOnDocumentableDecl(TagD);
14069 // If there's a #pragma GCC visibility in scope, set the visibility of this
14071 AddPushedVisibilityAttribute(Tag);
14074 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14075 SkipBodyInfo &SkipBody) {
14076 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14079 // Make the previous decl visible.
14080 makeMergedDefinitionVisible(SkipBody.Previous);
14084 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14085 assert(isa<ObjCContainerDecl>(IDecl) &&
14086 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14087 DeclContext *OCD = cast<DeclContext>(IDecl);
14088 assert(getContainingDC(OCD) == CurContext &&
14089 "The next DeclContext should be lexically contained in the current one.");
14094 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14095 SourceLocation FinalLoc,
14096 bool IsFinalSpelledSealed,
14097 SourceLocation LBraceLoc) {
14098 AdjustDeclIfTemplate(TagD);
14099 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14101 FieldCollector->StartClass();
14103 if (!Record->getIdentifier())
14106 if (FinalLoc.isValid())
14107 Record->addAttr(new (Context)
14108 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14111 // [...] The class-name is also inserted into the scope of the
14112 // class itself; this is known as the injected-class-name. For
14113 // purposes of access checking, the injected-class-name is treated
14114 // as if it were a public member name.
14115 CXXRecordDecl *InjectedClassName
14116 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14117 Record->getLocStart(), Record->getLocation(),
14118 Record->getIdentifier(),
14119 /*PrevDecl=*/nullptr,
14120 /*DelayTypeCreation=*/true);
14121 Context.getTypeDeclType(InjectedClassName, Record);
14122 InjectedClassName->setImplicit();
14123 InjectedClassName->setAccess(AS_public);
14124 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14125 InjectedClassName->setDescribedClassTemplate(Template);
14126 PushOnScopeChains(InjectedClassName, S);
14127 assert(InjectedClassName->isInjectedClassName() &&
14128 "Broken injected-class-name");
14131 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14132 SourceRange BraceRange) {
14133 AdjustDeclIfTemplate(TagD);
14134 TagDecl *Tag = cast<TagDecl>(TagD);
14135 Tag->setBraceRange(BraceRange);
14137 // Make sure we "complete" the definition even it is invalid.
14138 if (Tag->isBeingDefined()) {
14139 assert(Tag->isInvalidDecl() && "We should already have completed it");
14140 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14141 RD->completeDefinition();
14144 if (isa<CXXRecordDecl>(Tag)) {
14145 FieldCollector->FinishClass();
14148 // Exit this scope of this tag's definition.
14151 if (getCurLexicalContext()->isObjCContainer() &&
14152 Tag->getDeclContext()->isFileContext())
14153 Tag->setTopLevelDeclInObjCContainer();
14155 // Notify the consumer that we've defined a tag.
14156 if (!Tag->isInvalidDecl())
14157 Consumer.HandleTagDeclDefinition(Tag);
14160 void Sema::ActOnObjCContainerFinishDefinition() {
14161 // Exit this scope of this interface definition.
14165 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14166 assert(DC == CurContext && "Mismatch of container contexts");
14167 OriginalLexicalContext = DC;
14168 ActOnObjCContainerFinishDefinition();
14171 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14172 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14173 OriginalLexicalContext = nullptr;
14176 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14177 AdjustDeclIfTemplate(TagD);
14178 TagDecl *Tag = cast<TagDecl>(TagD);
14179 Tag->setInvalidDecl();
14181 // Make sure we "complete" the definition even it is invalid.
14182 if (Tag->isBeingDefined()) {
14183 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14184 RD->completeDefinition();
14187 // We're undoing ActOnTagStartDefinition here, not
14188 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14189 // the FieldCollector.
14194 // Note that FieldName may be null for anonymous bitfields.
14195 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14196 IdentifierInfo *FieldName,
14197 QualType FieldTy, bool IsMsStruct,
14198 Expr *BitWidth, bool *ZeroWidth) {
14199 // Default to true; that shouldn't confuse checks for emptiness
14203 // C99 6.7.2.1p4 - verify the field type.
14204 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14205 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14206 // Handle incomplete types with specific error.
14207 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14208 return ExprError();
14210 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14211 << FieldName << FieldTy << BitWidth->getSourceRange();
14212 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14213 << FieldTy << BitWidth->getSourceRange();
14214 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14215 UPPC_BitFieldWidth))
14216 return ExprError();
14218 // If the bit-width is type- or value-dependent, don't try to check
14220 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14223 llvm::APSInt Value;
14224 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14225 if (ICE.isInvalid())
14227 BitWidth = ICE.get();
14229 if (Value != 0 && ZeroWidth)
14230 *ZeroWidth = false;
14232 // Zero-width bitfield is ok for anonymous field.
14233 if (Value == 0 && FieldName)
14234 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14236 if (Value.isSigned() && Value.isNegative()) {
14238 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14239 << FieldName << Value.toString(10);
14240 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14241 << Value.toString(10);
14244 if (!FieldTy->isDependentType()) {
14245 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14246 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14247 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14249 // Over-wide bitfields are an error in C or when using the MSVC bitfield
14251 bool CStdConstraintViolation =
14252 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14253 bool MSBitfieldViolation =
14254 Value.ugt(TypeStorageSize) &&
14255 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14256 if (CStdConstraintViolation || MSBitfieldViolation) {
14257 unsigned DiagWidth =
14258 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14260 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14261 << FieldName << (unsigned)Value.getZExtValue()
14262 << !CStdConstraintViolation << DiagWidth;
14264 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14265 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14269 // Warn on types where the user might conceivably expect to get all
14270 // specified bits as value bits: that's all integral types other than
14272 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14274 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14275 << FieldName << (unsigned)Value.getZExtValue()
14276 << (unsigned)TypeWidth;
14278 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14279 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14286 /// ActOnField - Each field of a C struct/union is passed into this in order
14287 /// to create a FieldDecl object for it.
14288 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14289 Declarator &D, Expr *BitfieldWidth) {
14290 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14291 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14292 /*InitStyle=*/ICIS_NoInit, AS_public);
14296 /// HandleField - Analyze a field of a C struct or a C++ data member.
14298 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14299 SourceLocation DeclStart,
14300 Declarator &D, Expr *BitWidth,
14301 InClassInitStyle InitStyle,
14302 AccessSpecifier AS) {
14303 if (D.isDecompositionDeclarator()) {
14304 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14305 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14306 << Decomp.getSourceRange();
14310 IdentifierInfo *II = D.getIdentifier();
14311 SourceLocation Loc = DeclStart;
14312 if (II) Loc = D.getIdentifierLoc();
14314 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14315 QualType T = TInfo->getType();
14316 if (getLangOpts().CPlusPlus) {
14317 CheckExtraCXXDefaultArguments(D);
14319 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14320 UPPC_DataMemberType)) {
14321 D.setInvalidType();
14323 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14327 // TR 18037 does not allow fields to be declared with address spaces.
14328 if (T.getQualifiers().hasAddressSpace()) {
14329 Diag(Loc, diag::err_field_with_address_space);
14330 D.setInvalidType();
14333 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14334 // used as structure or union field: image, sampler, event or block types.
14335 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14336 T->isSamplerT() || T->isBlockPointerType())) {
14337 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14338 D.setInvalidType();
14341 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14343 if (D.getDeclSpec().isInlineSpecified())
14344 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14345 << getLangOpts().CPlusPlus1z;
14346 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14347 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14348 diag::err_invalid_thread)
14349 << DeclSpec::getSpecifierName(TSCS);
14351 // Check to see if this name was declared as a member previously
14352 NamedDecl *PrevDecl = nullptr;
14353 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14354 LookupName(Previous, S);
14355 switch (Previous.getResultKind()) {
14356 case LookupResult::Found:
14357 case LookupResult::FoundUnresolvedValue:
14358 PrevDecl = Previous.getAsSingle<NamedDecl>();
14361 case LookupResult::FoundOverloaded:
14362 PrevDecl = Previous.getRepresentativeDecl();
14365 case LookupResult::NotFound:
14366 case LookupResult::NotFoundInCurrentInstantiation:
14367 case LookupResult::Ambiguous:
14370 Previous.suppressDiagnostics();
14372 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14373 // Maybe we will complain about the shadowed template parameter.
14374 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14375 // Just pretend that we didn't see the previous declaration.
14376 PrevDecl = nullptr;
14379 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14380 PrevDecl = nullptr;
14383 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14384 SourceLocation TSSL = D.getLocStart();
14386 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14387 TSSL, AS, PrevDecl, &D);
14389 if (NewFD->isInvalidDecl())
14390 Record->setInvalidDecl();
14392 if (D.getDeclSpec().isModulePrivateSpecified())
14393 NewFD->setModulePrivate();
14395 if (NewFD->isInvalidDecl() && PrevDecl) {
14396 // Don't introduce NewFD into scope; there's already something
14397 // with the same name in the same scope.
14399 PushOnScopeChains(NewFD, S);
14401 Record->addDecl(NewFD);
14406 /// \brief Build a new FieldDecl and check its well-formedness.
14408 /// This routine builds a new FieldDecl given the fields name, type,
14409 /// record, etc. \p PrevDecl should refer to any previous declaration
14410 /// with the same name and in the same scope as the field to be
14413 /// \returns a new FieldDecl.
14415 /// \todo The Declarator argument is a hack. It will be removed once
14416 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14417 TypeSourceInfo *TInfo,
14418 RecordDecl *Record, SourceLocation Loc,
14419 bool Mutable, Expr *BitWidth,
14420 InClassInitStyle InitStyle,
14421 SourceLocation TSSL,
14422 AccessSpecifier AS, NamedDecl *PrevDecl,
14424 IdentifierInfo *II = Name.getAsIdentifierInfo();
14425 bool InvalidDecl = false;
14426 if (D) InvalidDecl = D->isInvalidType();
14428 // If we receive a broken type, recover by assuming 'int' and
14429 // marking this declaration as invalid.
14431 InvalidDecl = true;
14435 QualType EltTy = Context.getBaseElementType(T);
14436 if (!EltTy->isDependentType()) {
14437 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14438 // Fields of incomplete type force their record to be invalid.
14439 Record->setInvalidDecl();
14440 InvalidDecl = true;
14443 EltTy->isIncompleteType(&Def);
14444 if (Def && Def->isInvalidDecl()) {
14445 Record->setInvalidDecl();
14446 InvalidDecl = true;
14451 // OpenCL v1.2 s6.9.c: bitfields are not supported.
14452 if (BitWidth && getLangOpts().OpenCL) {
14453 Diag(Loc, diag::err_opencl_bitfields);
14454 InvalidDecl = true;
14457 // C99 6.7.2.1p8: A member of a structure or union may have any type other
14458 // than a variably modified type.
14459 if (!InvalidDecl && T->isVariablyModifiedType()) {
14460 bool SizeIsNegative;
14461 llvm::APSInt Oversized;
14463 TypeSourceInfo *FixedTInfo =
14464 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14468 Diag(Loc, diag::warn_illegal_constant_array_size);
14469 TInfo = FixedTInfo;
14470 T = FixedTInfo->getType();
14472 if (SizeIsNegative)
14473 Diag(Loc, diag::err_typecheck_negative_array_size);
14474 else if (Oversized.getBoolValue())
14475 Diag(Loc, diag::err_array_too_large)
14476 << Oversized.toString(10);
14478 Diag(Loc, diag::err_typecheck_field_variable_size);
14479 InvalidDecl = true;
14483 // Fields can not have abstract class types
14484 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14485 diag::err_abstract_type_in_decl,
14486 AbstractFieldType))
14487 InvalidDecl = true;
14489 bool ZeroWidth = false;
14491 BitWidth = nullptr;
14492 // If this is declared as a bit-field, check the bit-field.
14494 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14497 InvalidDecl = true;
14498 BitWidth = nullptr;
14503 // Check that 'mutable' is consistent with the type of the declaration.
14504 if (!InvalidDecl && Mutable) {
14505 unsigned DiagID = 0;
14506 if (T->isReferenceType())
14507 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14508 : diag::err_mutable_reference;
14509 else if (T.isConstQualified())
14510 DiagID = diag::err_mutable_const;
14513 SourceLocation ErrLoc = Loc;
14514 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14515 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14516 Diag(ErrLoc, DiagID);
14517 if (DiagID != diag::ext_mutable_reference) {
14519 InvalidDecl = true;
14524 // C++11 [class.union]p8 (DR1460):
14525 // At most one variant member of a union may have a
14526 // brace-or-equal-initializer.
14527 if (InitStyle != ICIS_NoInit)
14528 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14530 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14531 BitWidth, Mutable, InitStyle);
14533 NewFD->setInvalidDecl();
14535 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14536 Diag(Loc, diag::err_duplicate_member) << II;
14537 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14538 NewFD->setInvalidDecl();
14541 if (!InvalidDecl && getLangOpts().CPlusPlus) {
14542 if (Record->isUnion()) {
14543 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14544 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14545 if (RDecl->getDefinition()) {
14546 // C++ [class.union]p1: An object of a class with a non-trivial
14547 // constructor, a non-trivial copy constructor, a non-trivial
14548 // destructor, or a non-trivial copy assignment operator
14549 // cannot be a member of a union, nor can an array of such
14551 if (CheckNontrivialField(NewFD))
14552 NewFD->setInvalidDecl();
14556 // C++ [class.union]p1: If a union contains a member of reference type,
14557 // the program is ill-formed, except when compiling with MSVC extensions
14559 if (EltTy->isReferenceType()) {
14560 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14561 diag::ext_union_member_of_reference_type :
14562 diag::err_union_member_of_reference_type)
14563 << NewFD->getDeclName() << EltTy;
14564 if (!getLangOpts().MicrosoftExt)
14565 NewFD->setInvalidDecl();
14570 // FIXME: We need to pass in the attributes given an AST
14571 // representation, not a parser representation.
14573 // FIXME: The current scope is almost... but not entirely... correct here.
14574 ProcessDeclAttributes(getCurScope(), NewFD, *D);
14576 if (NewFD->hasAttrs())
14577 CheckAlignasUnderalignment(NewFD);
14580 // In auto-retain/release, infer strong retension for fields of
14581 // retainable type.
14582 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14583 NewFD->setInvalidDecl();
14585 if (T.isObjCGCWeak())
14586 Diag(Loc, diag::warn_attribute_weak_on_field);
14588 NewFD->setAccess(AS);
14592 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14594 assert(getLangOpts().CPlusPlus && "valid check only for C++");
14596 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14599 QualType EltTy = Context.getBaseElementType(FD->getType());
14600 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14601 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14602 if (RDecl->getDefinition()) {
14603 // We check for copy constructors before constructors
14604 // because otherwise we'll never get complaints about
14605 // copy constructors.
14607 CXXSpecialMember member = CXXInvalid;
14608 // We're required to check for any non-trivial constructors. Since the
14609 // implicit default constructor is suppressed if there are any
14610 // user-declared constructors, we just need to check that there is a
14611 // trivial default constructor and a trivial copy constructor. (We don't
14612 // worry about move constructors here, since this is a C++98 check.)
14613 if (RDecl->hasNonTrivialCopyConstructor())
14614 member = CXXCopyConstructor;
14615 else if (!RDecl->hasTrivialDefaultConstructor())
14616 member = CXXDefaultConstructor;
14617 else if (RDecl->hasNonTrivialCopyAssignment())
14618 member = CXXCopyAssignment;
14619 else if (RDecl->hasNonTrivialDestructor())
14620 member = CXXDestructor;
14622 if (member != CXXInvalid) {
14623 if (!getLangOpts().CPlusPlus11 &&
14624 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14625 // Objective-C++ ARC: it is an error to have a non-trivial field of
14626 // a union. However, system headers in Objective-C programs
14627 // occasionally have Objective-C lifetime objects within unions,
14628 // and rather than cause the program to fail, we make those
14629 // members unavailable.
14630 SourceLocation Loc = FD->getLocation();
14631 if (getSourceManager().isInSystemHeader(Loc)) {
14632 if (!FD->hasAttr<UnavailableAttr>())
14633 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14634 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14639 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14640 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14641 diag::err_illegal_union_or_anon_struct_member)
14642 << FD->getParent()->isUnion() << FD->getDeclName() << member;
14643 DiagnoseNontrivial(RDecl, member);
14644 return !getLangOpts().CPlusPlus11;
14652 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14653 /// AST enum value.
14654 static ObjCIvarDecl::AccessControl
14655 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14656 switch (ivarVisibility) {
14657 default: llvm_unreachable("Unknown visitibility kind");
14658 case tok::objc_private: return ObjCIvarDecl::Private;
14659 case tok::objc_public: return ObjCIvarDecl::Public;
14660 case tok::objc_protected: return ObjCIvarDecl::Protected;
14661 case tok::objc_package: return ObjCIvarDecl::Package;
14665 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14666 /// in order to create an IvarDecl object for it.
14667 Decl *Sema::ActOnIvar(Scope *S,
14668 SourceLocation DeclStart,
14669 Declarator &D, Expr *BitfieldWidth,
14670 tok::ObjCKeywordKind Visibility) {
14672 IdentifierInfo *II = D.getIdentifier();
14673 Expr *BitWidth = (Expr*)BitfieldWidth;
14674 SourceLocation Loc = DeclStart;
14675 if (II) Loc = D.getIdentifierLoc();
14677 // FIXME: Unnamed fields can be handled in various different ways, for
14678 // example, unnamed unions inject all members into the struct namespace!
14680 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14681 QualType T = TInfo->getType();
14684 // 6.7.2.1p3, 6.7.2.1p4
14685 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14687 D.setInvalidType();
14694 if (T->isReferenceType()) {
14695 Diag(Loc, diag::err_ivar_reference_type);
14696 D.setInvalidType();
14698 // C99 6.7.2.1p8: A member of a structure or union may have any type other
14699 // than a variably modified type.
14700 else if (T->isVariablyModifiedType()) {
14701 Diag(Loc, diag::err_typecheck_ivar_variable_size);
14702 D.setInvalidType();
14705 // Get the visibility (access control) for this ivar.
14706 ObjCIvarDecl::AccessControl ac =
14707 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14708 : ObjCIvarDecl::None;
14709 // Must set ivar's DeclContext to its enclosing interface.
14710 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14711 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14713 ObjCContainerDecl *EnclosingContext;
14714 if (ObjCImplementationDecl *IMPDecl =
14715 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14716 if (LangOpts.ObjCRuntime.isFragile()) {
14717 // Case of ivar declared in an implementation. Context is that of its class.
14718 EnclosingContext = IMPDecl->getClassInterface();
14719 assert(EnclosingContext && "Implementation has no class interface!");
14722 EnclosingContext = EnclosingDecl;
14724 if (ObjCCategoryDecl *CDecl =
14725 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14726 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14727 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14731 EnclosingContext = EnclosingDecl;
14734 // Construct the decl.
14735 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14736 DeclStart, Loc, II, T,
14737 TInfo, ac, (Expr *)BitfieldWidth);
14740 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14742 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14743 && !isa<TagDecl>(PrevDecl)) {
14744 Diag(Loc, diag::err_duplicate_member) << II;
14745 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14746 NewID->setInvalidDecl();
14750 // Process attributes attached to the ivar.
14751 ProcessDeclAttributes(S, NewID, D);
14753 if (D.isInvalidType())
14754 NewID->setInvalidDecl();
14756 // In ARC, infer 'retaining' for ivars of retainable type.
14757 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14758 NewID->setInvalidDecl();
14760 if (D.getDeclSpec().isModulePrivateSpecified())
14761 NewID->setModulePrivate();
14764 // FIXME: When interfaces are DeclContexts, we'll need to add
14765 // these to the interface.
14767 IdResolver.AddDecl(NewID);
14770 if (LangOpts.ObjCRuntime.isNonFragile() &&
14771 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14772 Diag(Loc, diag::warn_ivars_in_interface);
14777 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14778 /// class and class extensions. For every class \@interface and class
14779 /// extension \@interface, if the last ivar is a bitfield of any type,
14780 /// then add an implicit `char :0` ivar to the end of that interface.
14781 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14782 SmallVectorImpl<Decl *> &AllIvarDecls) {
14783 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14786 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14787 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14789 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14791 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14793 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14794 if (!CD->IsClassExtension())
14797 // No need to add this to end of @implementation.
14801 // All conditions are met. Add a new bitfield to the tail end of ivars.
14802 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14803 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14805 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14806 DeclLoc, DeclLoc, nullptr,
14808 Context.getTrivialTypeSourceInfo(Context.CharTy,
14810 ObjCIvarDecl::Private, BW,
14812 AllIvarDecls.push_back(Ivar);
14815 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14816 ArrayRef<Decl *> Fields, SourceLocation LBrac,
14817 SourceLocation RBrac, AttributeList *Attr) {
14818 assert(EnclosingDecl && "missing record or interface decl");
14820 // If this is an Objective-C @implementation or category and we have
14821 // new fields here we should reset the layout of the interface since
14822 // it will now change.
14823 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14824 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14825 switch (DC->getKind()) {
14827 case Decl::ObjCCategory:
14828 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14830 case Decl::ObjCImplementation:
14832 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14837 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14839 // Start counting up the number of named members; make sure to include
14840 // members of anonymous structs and unions in the total.
14841 unsigned NumNamedMembers = 0;
14843 for (const auto *I : Record->decls()) {
14844 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14845 if (IFD->getDeclName())
14850 // Verify that all the fields are okay.
14851 SmallVector<FieldDecl*, 32> RecFields;
14853 bool ObjCFieldLifetimeErrReported = false;
14854 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14856 FieldDecl *FD = cast<FieldDecl>(*i);
14858 // Get the type for the field.
14859 const Type *FDTy = FD->getType().getTypePtr();
14861 if (!FD->isAnonymousStructOrUnion()) {
14862 // Remember all fields written by the user.
14863 RecFields.push_back(FD);
14866 // If the field is already invalid for some reason, don't emit more
14867 // diagnostics about it.
14868 if (FD->isInvalidDecl()) {
14869 EnclosingDecl->setInvalidDecl();
14874 // A structure or union shall not contain a member with
14875 // incomplete or function type (hence, a structure shall not
14876 // contain an instance of itself, but may contain a pointer to
14877 // an instance of itself), except that the last member of a
14878 // structure with more than one named member may have incomplete
14879 // array type; such a structure (and any union containing,
14880 // possibly recursively, a member that is such a structure)
14881 // shall not be a member of a structure or an element of an
14883 if (FDTy->isFunctionType()) {
14884 // Field declared as a function.
14885 Diag(FD->getLocation(), diag::err_field_declared_as_function)
14886 << FD->getDeclName();
14887 FD->setInvalidDecl();
14888 EnclosingDecl->setInvalidDecl();
14890 } else if (FDTy->isIncompleteArrayType() && Record &&
14891 ((i + 1 == Fields.end() && !Record->isUnion()) ||
14892 ((getLangOpts().MicrosoftExt ||
14893 getLangOpts().CPlusPlus) &&
14894 (i + 1 == Fields.end() || Record->isUnion())))) {
14895 // Flexible array member.
14896 // Microsoft and g++ is more permissive regarding flexible array.
14897 // It will accept flexible array in union and also
14898 // as the sole element of a struct/class.
14899 unsigned DiagID = 0;
14900 if (Record->isUnion())
14901 DiagID = getLangOpts().MicrosoftExt
14902 ? diag::ext_flexible_array_union_ms
14903 : getLangOpts().CPlusPlus
14904 ? diag::ext_flexible_array_union_gnu
14905 : diag::err_flexible_array_union;
14906 else if (NumNamedMembers < 1)
14907 DiagID = getLangOpts().MicrosoftExt
14908 ? diag::ext_flexible_array_empty_aggregate_ms
14909 : getLangOpts().CPlusPlus
14910 ? diag::ext_flexible_array_empty_aggregate_gnu
14911 : diag::err_flexible_array_empty_aggregate;
14914 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14915 << Record->getTagKind();
14916 // While the layout of types that contain virtual bases is not specified
14917 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14918 // virtual bases after the derived members. This would make a flexible
14919 // array member declared at the end of an object not adjacent to the end
14921 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14922 if (RD->getNumVBases() != 0)
14923 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14924 << FD->getDeclName() << Record->getTagKind();
14925 if (!getLangOpts().C99)
14926 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14927 << FD->getDeclName() << Record->getTagKind();
14929 // If the element type has a non-trivial destructor, we would not
14930 // implicitly destroy the elements, so disallow it for now.
14932 // FIXME: GCC allows this. We should probably either implicitly delete
14933 // the destructor of the containing class, or just allow this.
14934 QualType BaseElem = Context.getBaseElementType(FD->getType());
14935 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14936 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14937 << FD->getDeclName() << FD->getType();
14938 FD->setInvalidDecl();
14939 EnclosingDecl->setInvalidDecl();
14942 // Okay, we have a legal flexible array member at the end of the struct.
14943 Record->setHasFlexibleArrayMember(true);
14944 } else if (!FDTy->isDependentType() &&
14945 RequireCompleteType(FD->getLocation(), FD->getType(),
14946 diag::err_field_incomplete)) {
14948 FD->setInvalidDecl();
14949 EnclosingDecl->setInvalidDecl();
14951 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14952 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14953 // A type which contains a flexible array member is considered to be a
14954 // flexible array member.
14955 Record->setHasFlexibleArrayMember(true);
14956 if (!Record->isUnion()) {
14957 // If this is a struct/class and this is not the last element, reject
14958 // it. Note that GCC supports variable sized arrays in the middle of
14960 if (i + 1 != Fields.end())
14961 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14962 << FD->getDeclName() << FD->getType();
14964 // We support flexible arrays at the end of structs in
14965 // other structs as an extension.
14966 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14967 << FD->getDeclName();
14971 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14972 RequireNonAbstractType(FD->getLocation(), FD->getType(),
14973 diag::err_abstract_type_in_decl,
14974 AbstractIvarType)) {
14975 // Ivars can not have abstract class types
14976 FD->setInvalidDecl();
14978 if (Record && FDTTy->getDecl()->hasObjectMember())
14979 Record->setHasObjectMember(true);
14980 if (Record && FDTTy->getDecl()->hasVolatileMember())
14981 Record->setHasVolatileMember(true);
14982 } else if (FDTy->isObjCObjectType()) {
14983 /// A field cannot be an Objective-c object
14984 Diag(FD->getLocation(), diag::err_statically_allocated_object)
14985 << FixItHint::CreateInsertion(FD->getLocation(), "*");
14986 QualType T = Context.getObjCObjectPointerType(FD->getType());
14988 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14989 Record && !ObjCFieldLifetimeErrReported &&
14990 (!getLangOpts().CPlusPlus || Record->isUnion())) {
14991 // It's an error in ARC or Weak if a field has lifetime.
14992 // We don't want to report this in a system header, though,
14993 // so we just make the field unavailable.
14994 // FIXME: that's really not sufficient; we need to make the type
14995 // itself invalid to, say, initialize or copy.
14996 QualType T = FD->getType();
14997 if (T.hasNonTrivialObjCLifetime()) {
14998 SourceLocation loc = FD->getLocation();
14999 if (getSourceManager().isInSystemHeader(loc)) {
15000 if (!FD->hasAttr<UnavailableAttr>()) {
15001 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15002 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15005 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15006 << T->isBlockPointerType() << Record->getTagKind();
15008 ObjCFieldLifetimeErrReported = true;
15010 } else if (getLangOpts().ObjC1 &&
15011 getLangOpts().getGC() != LangOptions::NonGC &&
15012 Record && !Record->hasObjectMember()) {
15013 if (FD->getType()->isObjCObjectPointerType() ||
15014 FD->getType().isObjCGCStrong())
15015 Record->setHasObjectMember(true);
15016 else if (Context.getAsArrayType(FD->getType())) {
15017 QualType BaseType = Context.getBaseElementType(FD->getType());
15018 if (BaseType->isRecordType() &&
15019 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15020 Record->setHasObjectMember(true);
15021 else if (BaseType->isObjCObjectPointerType() ||
15022 BaseType.isObjCGCStrong())
15023 Record->setHasObjectMember(true);
15026 if (Record && FD->getType().isVolatileQualified())
15027 Record->setHasVolatileMember(true);
15028 // Keep track of the number of named members.
15029 if (FD->getIdentifier())
15033 // Okay, we successfully defined 'Record'.
15035 bool Completed = false;
15036 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15037 if (!CXXRecord->isInvalidDecl()) {
15038 // Set access bits correctly on the directly-declared conversions.
15039 for (CXXRecordDecl::conversion_iterator
15040 I = CXXRecord->conversion_begin(),
15041 E = CXXRecord->conversion_end(); I != E; ++I)
15042 I.setAccess((*I)->getAccess());
15045 if (!CXXRecord->isDependentType()) {
15046 if (CXXRecord->hasUserDeclaredDestructor()) {
15047 // Adjust user-defined destructor exception spec.
15048 if (getLangOpts().CPlusPlus11)
15049 AdjustDestructorExceptionSpec(CXXRecord,
15050 CXXRecord->getDestructor());
15053 if (!CXXRecord->isInvalidDecl()) {
15054 // Add any implicitly-declared members to this class.
15055 AddImplicitlyDeclaredMembersToClass(CXXRecord);
15057 // If we have virtual base classes, we may end up finding multiple
15058 // final overriders for a given virtual function. Check for this
15060 if (CXXRecord->getNumVBases()) {
15061 CXXFinalOverriderMap FinalOverriders;
15062 CXXRecord->getFinalOverriders(FinalOverriders);
15064 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15065 MEnd = FinalOverriders.end();
15067 for (OverridingMethods::iterator SO = M->second.begin(),
15068 SOEnd = M->second.end();
15069 SO != SOEnd; ++SO) {
15070 assert(SO->second.size() > 0 &&
15071 "Virtual function without overridding functions?");
15072 if (SO->second.size() == 1)
15075 // C++ [class.virtual]p2:
15076 // In a derived class, if a virtual member function of a base
15077 // class subobject has more than one final overrider the
15078 // program is ill-formed.
15079 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15080 << (const NamedDecl *)M->first << Record;
15081 Diag(M->first->getLocation(),
15082 diag::note_overridden_virtual_function);
15083 for (OverridingMethods::overriding_iterator
15084 OM = SO->second.begin(),
15085 OMEnd = SO->second.end();
15087 Diag(OM->Method->getLocation(), diag::note_final_overrider)
15088 << (const NamedDecl *)M->first << OM->Method->getParent();
15090 Record->setInvalidDecl();
15093 CXXRecord->completeDefinition(&FinalOverriders);
15101 Record->completeDefinition();
15103 // We may have deferred checking for a deleted destructor. Check now.
15104 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15105 auto *Dtor = CXXRecord->getDestructor();
15106 if (Dtor && Dtor->isImplicit() &&
15107 ShouldDeleteSpecialMember(Dtor, CXXDestructor))
15108 SetDeclDeleted(Dtor, CXXRecord->getLocation());
15111 if (Record->hasAttrs()) {
15112 CheckAlignasUnderalignment(Record);
15114 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15115 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15116 IA->getRange(), IA->getBestCase(),
15117 IA->getSemanticSpelling());
15120 // Check if the structure/union declaration is a type that can have zero
15121 // size in C. For C this is a language extension, for C++ it may cause
15122 // compatibility problems.
15123 bool CheckForZeroSize;
15124 if (!getLangOpts().CPlusPlus) {
15125 CheckForZeroSize = true;
15127 // For C++ filter out types that cannot be referenced in C code.
15128 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15130 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15131 !CXXRecord->isDependentType() &&
15132 CXXRecord->isCLike();
15134 if (CheckForZeroSize) {
15135 bool ZeroSize = true;
15136 bool IsEmpty = true;
15137 unsigned NonBitFields = 0;
15138 for (RecordDecl::field_iterator I = Record->field_begin(),
15139 E = Record->field_end();
15140 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15142 if (I->isUnnamedBitfield()) {
15143 if (I->getBitWidthValue(Context) > 0)
15147 QualType FieldType = I->getType();
15148 if (FieldType->isIncompleteType() ||
15149 !Context.getTypeSizeInChars(FieldType).isZero())
15154 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15155 // allowed in C++, but warn if its declaration is inside
15156 // extern "C" block.
15158 Diag(RecLoc, getLangOpts().CPlusPlus ?
15159 diag::warn_zero_size_struct_union_in_extern_c :
15160 diag::warn_zero_size_struct_union_compat)
15161 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15164 // Structs without named members are extension in C (C99 6.7.2.1p7),
15165 // but are accepted by GCC.
15166 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15167 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15168 diag::ext_no_named_members_in_struct_union)
15169 << Record->isUnion();
15173 ObjCIvarDecl **ClsFields =
15174 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15175 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15176 ID->setEndOfDefinitionLoc(RBrac);
15177 // Add ivar's to class's DeclContext.
15178 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15179 ClsFields[i]->setLexicalDeclContext(ID);
15180 ID->addDecl(ClsFields[i]);
15182 // Must enforce the rule that ivars in the base classes may not be
15184 if (ID->getSuperClass())
15185 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15186 } else if (ObjCImplementationDecl *IMPDecl =
15187 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15188 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15189 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15190 // Ivar declared in @implementation never belongs to the implementation.
15191 // Only it is in implementation's lexical context.
15192 ClsFields[I]->setLexicalDeclContext(IMPDecl);
15193 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15194 IMPDecl->setIvarLBraceLoc(LBrac);
15195 IMPDecl->setIvarRBraceLoc(RBrac);
15196 } else if (ObjCCategoryDecl *CDecl =
15197 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15198 // case of ivars in class extension; all other cases have been
15199 // reported as errors elsewhere.
15200 // FIXME. Class extension does not have a LocEnd field.
15201 // CDecl->setLocEnd(RBrac);
15202 // Add ivar's to class extension's DeclContext.
15203 // Diagnose redeclaration of private ivars.
15204 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15205 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15207 if (const ObjCIvarDecl *ClsIvar =
15208 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15209 Diag(ClsFields[i]->getLocation(),
15210 diag::err_duplicate_ivar_declaration);
15211 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15214 for (const auto *Ext : IDecl->known_extensions()) {
15215 if (const ObjCIvarDecl *ClsExtIvar
15216 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15217 Diag(ClsFields[i]->getLocation(),
15218 diag::err_duplicate_ivar_declaration);
15219 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15224 ClsFields[i]->setLexicalDeclContext(CDecl);
15225 CDecl->addDecl(ClsFields[i]);
15227 CDecl->setIvarLBraceLoc(LBrac);
15228 CDecl->setIvarRBraceLoc(RBrac);
15233 ProcessDeclAttributeList(S, Record, Attr);
15236 /// \brief Determine whether the given integral value is representable within
15237 /// the given type T.
15238 static bool isRepresentableIntegerValue(ASTContext &Context,
15239 llvm::APSInt &Value,
15241 assert(T->isIntegralType(Context) && "Integral type required!");
15242 unsigned BitWidth = Context.getIntWidth(T);
15244 if (Value.isUnsigned() || Value.isNonNegative()) {
15245 if (T->isSignedIntegerOrEnumerationType())
15247 return Value.getActiveBits() <= BitWidth;
15249 return Value.getMinSignedBits() <= BitWidth;
15252 // \brief Given an integral type, return the next larger integral type
15253 // (or a NULL type of no such type exists).
15254 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15255 // FIXME: Int128/UInt128 support, which also needs to be introduced into
15256 // enum checking below.
15257 assert(T->isIntegralType(Context) && "Integral type required!");
15258 const unsigned NumTypes = 4;
15259 QualType SignedIntegralTypes[NumTypes] = {
15260 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15262 QualType UnsignedIntegralTypes[NumTypes] = {
15263 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15264 Context.UnsignedLongLongTy
15267 unsigned BitWidth = Context.getTypeSize(T);
15268 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15269 : UnsignedIntegralTypes;
15270 for (unsigned I = 0; I != NumTypes; ++I)
15271 if (Context.getTypeSize(Types[I]) > BitWidth)
15277 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15278 EnumConstantDecl *LastEnumConst,
15279 SourceLocation IdLoc,
15280 IdentifierInfo *Id,
15282 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15283 llvm::APSInt EnumVal(IntWidth);
15286 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15290 Val = DefaultLvalueConversion(Val).get();
15293 if (Enum->isDependentType() || Val->isTypeDependent())
15294 EltTy = Context.DependentTy;
15296 SourceLocation ExpLoc;
15297 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15298 !getLangOpts().MSVCCompat) {
15299 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15300 // constant-expression in the enumerator-definition shall be a converted
15301 // constant expression of the underlying type.
15302 EltTy = Enum->getIntegerType();
15303 ExprResult Converted =
15304 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15306 if (Converted.isInvalid())
15309 Val = Converted.get();
15310 } else if (!Val->isValueDependent() &&
15311 !(Val = VerifyIntegerConstantExpression(Val,
15312 &EnumVal).get())) {
15313 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15315 if (Enum->isFixed()) {
15316 EltTy = Enum->getIntegerType();
15318 // In Obj-C and Microsoft mode, require the enumeration value to be
15319 // representable in the underlying type of the enumeration. In C++11,
15320 // we perform a non-narrowing conversion as part of converted constant
15321 // expression checking.
15322 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15323 if (getLangOpts().MSVCCompat) {
15324 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15325 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15327 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15329 Val = ImpCastExprToType(Val, EltTy,
15330 EltTy->isBooleanType() ?
15331 CK_IntegralToBoolean : CK_IntegralCast)
15333 } else if (getLangOpts().CPlusPlus) {
15334 // C++11 [dcl.enum]p5:
15335 // If the underlying type is not fixed, the type of each enumerator
15336 // is the type of its initializing value:
15337 // - If an initializer is specified for an enumerator, the
15338 // initializing value has the same type as the expression.
15339 EltTy = Val->getType();
15342 // The expression that defines the value of an enumeration constant
15343 // shall be an integer constant expression that has a value
15344 // representable as an int.
15346 // Complain if the value is not representable in an int.
15347 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15348 Diag(IdLoc, diag::ext_enum_value_not_int)
15349 << EnumVal.toString(10) << Val->getSourceRange()
15350 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15351 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15352 // Force the type of the expression to 'int'.
15353 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15355 EltTy = Val->getType();
15362 if (Enum->isDependentType())
15363 EltTy = Context.DependentTy;
15364 else if (!LastEnumConst) {
15365 // C++0x [dcl.enum]p5:
15366 // If the underlying type is not fixed, the type of each enumerator
15367 // is the type of its initializing value:
15368 // - If no initializer is specified for the first enumerator, the
15369 // initializing value has an unspecified integral type.
15371 // GCC uses 'int' for its unspecified integral type, as does
15373 if (Enum->isFixed()) {
15374 EltTy = Enum->getIntegerType();
15377 EltTy = Context.IntTy;
15380 // Assign the last value + 1.
15381 EnumVal = LastEnumConst->getInitVal();
15383 EltTy = LastEnumConst->getType();
15385 // Check for overflow on increment.
15386 if (EnumVal < LastEnumConst->getInitVal()) {
15387 // C++0x [dcl.enum]p5:
15388 // If the underlying type is not fixed, the type of each enumerator
15389 // is the type of its initializing value:
15391 // - Otherwise the type of the initializing value is the same as
15392 // the type of the initializing value of the preceding enumerator
15393 // unless the incremented value is not representable in that type,
15394 // in which case the type is an unspecified integral type
15395 // sufficient to contain the incremented value. If no such type
15396 // exists, the program is ill-formed.
15397 QualType T = getNextLargerIntegralType(Context, EltTy);
15398 if (T.isNull() || Enum->isFixed()) {
15399 // There is no integral type larger enough to represent this
15400 // value. Complain, then allow the value to wrap around.
15401 EnumVal = LastEnumConst->getInitVal();
15402 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15404 if (Enum->isFixed())
15405 // When the underlying type is fixed, this is ill-formed.
15406 Diag(IdLoc, diag::err_enumerator_wrapped)
15407 << EnumVal.toString(10)
15410 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15411 << EnumVal.toString(10);
15416 // Retrieve the last enumerator's value, extent that type to the
15417 // type that is supposed to be large enough to represent the incremented
15418 // value, then increment.
15419 EnumVal = LastEnumConst->getInitVal();
15420 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15421 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15424 // If we're not in C++, diagnose the overflow of enumerator values,
15425 // which in C99 means that the enumerator value is not representable in
15426 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15427 // permits enumerator values that are representable in some larger
15429 if (!getLangOpts().CPlusPlus && !T.isNull())
15430 Diag(IdLoc, diag::warn_enum_value_overflow);
15431 } else if (!getLangOpts().CPlusPlus &&
15432 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15433 // Enforce C99 6.7.2.2p2 even when we compute the next value.
15434 Diag(IdLoc, diag::ext_enum_value_not_int)
15435 << EnumVal.toString(10) << 1;
15440 if (!EltTy->isDependentType()) {
15441 // Make the enumerator value match the signedness and size of the
15442 // enumerator's type.
15443 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15444 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15447 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15451 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15452 SourceLocation IILoc) {
15453 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15454 !getLangOpts().CPlusPlus)
15455 return SkipBodyInfo();
15457 // We have an anonymous enum definition. Look up the first enumerator to
15458 // determine if we should merge the definition with an existing one and
15460 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15462 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15464 return SkipBodyInfo();
15466 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15468 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15470 Skip.Previous = Hidden;
15474 return SkipBodyInfo();
15477 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15478 SourceLocation IdLoc, IdentifierInfo *Id,
15479 AttributeList *Attr,
15480 SourceLocation EqualLoc, Expr *Val) {
15481 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15482 EnumConstantDecl *LastEnumConst =
15483 cast_or_null<EnumConstantDecl>(lastEnumConst);
15485 // The scope passed in may not be a decl scope. Zip up the scope tree until
15486 // we find one that is.
15487 S = getNonFieldDeclScope(S);
15489 // Verify that there isn't already something declared with this name in this
15491 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15493 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15494 // Maybe we will complain about the shadowed template parameter.
15495 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15496 // Just pretend that we didn't see the previous declaration.
15497 PrevDecl = nullptr;
15500 // C++ [class.mem]p15:
15501 // If T is the name of a class, then each of the following shall have a name
15502 // different from T:
15503 // - every enumerator of every member of class T that is an unscoped
15505 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15506 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15507 DeclarationNameInfo(Id, IdLoc));
15509 EnumConstantDecl *New =
15510 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15515 // When in C++, we may get a TagDecl with the same name; in this case the
15516 // enum constant will 'hide' the tag.
15517 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15518 "Received TagDecl when not in C++!");
15519 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15520 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15521 if (isa<EnumConstantDecl>(PrevDecl))
15522 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15524 Diag(IdLoc, diag::err_redefinition) << Id;
15525 notePreviousDefinition(PrevDecl, IdLoc);
15530 // Process attributes.
15531 if (Attr) ProcessDeclAttributeList(S, New, Attr);
15532 AddPragmaAttributes(S, New);
15534 // Register this decl in the current scope stack.
15535 New->setAccess(TheEnumDecl->getAccess());
15536 PushOnScopeChains(New, S);
15538 ActOnDocumentableDecl(New);
15543 // Returns true when the enum initial expression does not trigger the
15544 // duplicate enum warning. A few common cases are exempted as follows:
15545 // Element2 = Element1
15546 // Element2 = Element1 + 1
15547 // Element2 = Element1 - 1
15548 // Where Element2 and Element1 are from the same enum.
15549 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15550 Expr *InitExpr = ECD->getInitExpr();
15553 InitExpr = InitExpr->IgnoreImpCasts();
15555 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15556 if (!BO->isAdditiveOp())
15558 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15561 if (IL->getValue() != 1)
15564 InitExpr = BO->getLHS();
15567 // This checks if the elements are from the same enum.
15568 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15572 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15576 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15586 bool isTombstoneOrEmptyKey;
15587 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15588 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15591 static DupKey GetDupKey(const llvm::APSInt& Val) {
15592 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15596 struct DenseMapInfoDupKey {
15597 static DupKey getEmptyKey() { return DupKey(0, true); }
15598 static DupKey getTombstoneKey() { return DupKey(1, true); }
15599 static unsigned getHashValue(const DupKey Key) {
15600 return (unsigned)(Key.val * 37);
15602 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15603 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15604 LHS.val == RHS.val;
15607 } // end anonymous namespace
15609 // Emits a warning when an element is implicitly set a value that
15610 // a previous element has already been set to.
15611 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15613 QualType EnumType) {
15614 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15616 // Avoid anonymous enums
15617 if (!Enum->getIdentifier())
15620 // Only check for small enums.
15621 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15624 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15625 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15627 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15628 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15631 DuplicatesVector DupVector;
15632 ValueToVectorMap EnumMap;
15634 // Populate the EnumMap with all values represented by enum constants without
15636 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15637 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15639 // Null EnumConstantDecl means a previous diagnostic has been emitted for
15640 // this constant. Skip this enum since it may be ill-formed.
15645 if (ECD->getInitExpr())
15648 DupKey Key = GetDupKey(ECD->getInitVal());
15649 DeclOrVector &Entry = EnumMap[Key];
15651 // First time encountering this value.
15652 if (Entry.isNull())
15656 // Create vectors for any values that has duplicates.
15657 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15658 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15659 if (!ValidDuplicateEnum(ECD, Enum))
15662 DupKey Key = GetDupKey(ECD->getInitVal());
15664 DeclOrVector& Entry = EnumMap[Key];
15665 if (Entry.isNull())
15668 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15669 // Ensure constants are different.
15673 // Create new vector and push values onto it.
15674 ECDVector *Vec = new ECDVector();
15676 Vec->push_back(ECD);
15678 // Update entry to point to the duplicates vector.
15681 // Store the vector somewhere we can consult later for quick emission of
15683 DupVector.push_back(Vec);
15687 ECDVector *Vec = Entry.get<ECDVector*>();
15688 // Make sure constants are not added more than once.
15689 if (*Vec->begin() == ECD)
15692 Vec->push_back(ECD);
15695 // Emit diagnostics.
15696 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15697 DupVectorEnd = DupVector.end();
15698 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15699 ECDVector *Vec = *DupVectorIter;
15700 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15702 // Emit warning for one enum constant.
15703 ECDVector::iterator I = Vec->begin();
15704 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15705 << (*I)->getName() << (*I)->getInitVal().toString(10)
15706 << (*I)->getSourceRange();
15709 // Emit one note for each of the remaining enum constants with
15711 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15712 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15713 << (*I)->getName() << (*I)->getInitVal().toString(10)
15714 << (*I)->getSourceRange();
15719 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15720 bool AllowMask) const {
15721 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15722 assert(ED->isCompleteDefinition() && "expected enum definition");
15724 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15725 llvm::APInt &FlagBits = R.first->second;
15728 for (auto *E : ED->enumerators()) {
15729 const auto &EVal = E->getInitVal();
15730 // Only single-bit enumerators introduce new flag values.
15731 if (EVal.isPowerOf2())
15732 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15736 // A value is in a flag enum if either its bits are a subset of the enum's
15737 // flag bits (the first condition) or we are allowing masks and the same is
15738 // true of its complement (the second condition). When masks are allowed, we
15739 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15741 // While it's true that any value could be used as a mask, the assumption is
15742 // that a mask will have all of the insignificant bits set. Anything else is
15743 // likely a logic error.
15744 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15745 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15748 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15750 ArrayRef<Decl *> Elements,
15751 Scope *S, AttributeList *Attr) {
15752 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15753 QualType EnumType = Context.getTypeDeclType(Enum);
15756 ProcessDeclAttributeList(S, Enum, Attr);
15758 if (Enum->isDependentType()) {
15759 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15760 EnumConstantDecl *ECD =
15761 cast_or_null<EnumConstantDecl>(Elements[i]);
15762 if (!ECD) continue;
15764 ECD->setType(EnumType);
15767 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15771 // TODO: If the result value doesn't fit in an int, it must be a long or long
15772 // long value. ISO C does not support this, but GCC does as an extension,
15774 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15775 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15776 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15778 // Verify that all the values are okay, compute the size of the values, and
15779 // reverse the list.
15780 unsigned NumNegativeBits = 0;
15781 unsigned NumPositiveBits = 0;
15783 // Keep track of whether all elements have type int.
15784 bool AllElementsInt = true;
15786 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15787 EnumConstantDecl *ECD =
15788 cast_or_null<EnumConstantDecl>(Elements[i]);
15789 if (!ECD) continue; // Already issued a diagnostic.
15791 const llvm::APSInt &InitVal = ECD->getInitVal();
15793 // Keep track of the size of positive and negative values.
15794 if (InitVal.isUnsigned() || InitVal.isNonNegative())
15795 NumPositiveBits = std::max(NumPositiveBits,
15796 (unsigned)InitVal.getActiveBits());
15798 NumNegativeBits = std::max(NumNegativeBits,
15799 (unsigned)InitVal.getMinSignedBits());
15801 // Keep track of whether every enum element has type int (very commmon).
15802 if (AllElementsInt)
15803 AllElementsInt = ECD->getType() == Context.IntTy;
15806 // Figure out the type that should be used for this enum.
15808 unsigned BestWidth;
15810 // C++0x N3000 [conv.prom]p3:
15811 // An rvalue of an unscoped enumeration type whose underlying
15812 // type is not fixed can be converted to an rvalue of the first
15813 // of the following types that can represent all the values of
15814 // the enumeration: int, unsigned int, long int, unsigned long
15815 // int, long long int, or unsigned long long int.
15817 // An identifier declared as an enumeration constant has type int.
15818 // The C99 rule is modified by a gcc extension
15819 QualType BestPromotionType;
15821 bool Packed = Enum->hasAttr<PackedAttr>();
15822 // -fshort-enums is the equivalent to specifying the packed attribute on all
15823 // enum definitions.
15824 if (LangOpts.ShortEnums)
15827 if (Enum->isFixed()) {
15828 BestType = Enum->getIntegerType();
15829 if (BestType->isPromotableIntegerType())
15830 BestPromotionType = Context.getPromotedIntegerType(BestType);
15832 BestPromotionType = BestType;
15834 BestWidth = Context.getIntWidth(BestType);
15836 else if (NumNegativeBits) {
15837 // If there is a negative value, figure out the smallest integer type (of
15838 // int/long/longlong) that fits.
15839 // If it's packed, check also if it fits a char or a short.
15840 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15841 BestType = Context.SignedCharTy;
15842 BestWidth = CharWidth;
15843 } else if (Packed && NumNegativeBits <= ShortWidth &&
15844 NumPositiveBits < ShortWidth) {
15845 BestType = Context.ShortTy;
15846 BestWidth = ShortWidth;
15847 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15848 BestType = Context.IntTy;
15849 BestWidth = IntWidth;
15851 BestWidth = Context.getTargetInfo().getLongWidth();
15853 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15854 BestType = Context.LongTy;
15856 BestWidth = Context.getTargetInfo().getLongLongWidth();
15858 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15859 Diag(Enum->getLocation(), diag::ext_enum_too_large);
15860 BestType = Context.LongLongTy;
15863 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15865 // If there is no negative value, figure out the smallest type that fits
15866 // all of the enumerator values.
15867 // If it's packed, check also if it fits a char or a short.
15868 if (Packed && NumPositiveBits <= CharWidth) {
15869 BestType = Context.UnsignedCharTy;
15870 BestPromotionType = Context.IntTy;
15871 BestWidth = CharWidth;
15872 } else if (Packed && NumPositiveBits <= ShortWidth) {
15873 BestType = Context.UnsignedShortTy;
15874 BestPromotionType = Context.IntTy;
15875 BestWidth = ShortWidth;
15876 } else if (NumPositiveBits <= IntWidth) {
15877 BestType = Context.UnsignedIntTy;
15878 BestWidth = IntWidth;
15880 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15881 ? Context.UnsignedIntTy : Context.IntTy;
15882 } else if (NumPositiveBits <=
15883 (BestWidth = Context.getTargetInfo().getLongWidth())) {
15884 BestType = Context.UnsignedLongTy;
15886 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15887 ? Context.UnsignedLongTy : Context.LongTy;
15889 BestWidth = Context.getTargetInfo().getLongLongWidth();
15890 assert(NumPositiveBits <= BestWidth &&
15891 "How could an initializer get larger than ULL?");
15892 BestType = Context.UnsignedLongLongTy;
15894 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15895 ? Context.UnsignedLongLongTy : Context.LongLongTy;
15899 // Loop over all of the enumerator constants, changing their types to match
15900 // the type of the enum if needed.
15901 for (auto *D : Elements) {
15902 auto *ECD = cast_or_null<EnumConstantDecl>(D);
15903 if (!ECD) continue; // Already issued a diagnostic.
15905 // Standard C says the enumerators have int type, but we allow, as an
15906 // extension, the enumerators to be larger than int size. If each
15907 // enumerator value fits in an int, type it as an int, otherwise type it the
15908 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
15909 // that X has type 'int', not 'unsigned'.
15911 // Determine whether the value fits into an int.
15912 llvm::APSInt InitVal = ECD->getInitVal();
15914 // If it fits into an integer type, force it. Otherwise force it to match
15915 // the enum decl type.
15919 if (!getLangOpts().CPlusPlus &&
15920 !Enum->isFixed() &&
15921 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15922 NewTy = Context.IntTy;
15923 NewWidth = IntWidth;
15925 } else if (ECD->getType() == BestType) {
15926 // Already the right type!
15927 if (getLangOpts().CPlusPlus)
15928 // C++ [dcl.enum]p4: Following the closing brace of an
15929 // enum-specifier, each enumerator has the type of its
15931 ECD->setType(EnumType);
15935 NewWidth = BestWidth;
15936 NewSign = BestType->isSignedIntegerOrEnumerationType();
15939 // Adjust the APSInt value.
15940 InitVal = InitVal.extOrTrunc(NewWidth);
15941 InitVal.setIsSigned(NewSign);
15942 ECD->setInitVal(InitVal);
15944 // Adjust the Expr initializer and type.
15945 if (ECD->getInitExpr() &&
15946 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15947 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15949 ECD->getInitExpr(),
15950 /*base paths*/ nullptr,
15952 if (getLangOpts().CPlusPlus)
15953 // C++ [dcl.enum]p4: Following the closing brace of an
15954 // enum-specifier, each enumerator has the type of its
15956 ECD->setType(EnumType);
15958 ECD->setType(NewTy);
15961 Enum->completeDefinition(BestType, BestPromotionType,
15962 NumPositiveBits, NumNegativeBits);
15964 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15966 if (Enum->isClosedFlag()) {
15967 for (Decl *D : Elements) {
15968 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15969 if (!ECD) continue; // Already issued a diagnostic.
15971 llvm::APSInt InitVal = ECD->getInitVal();
15972 if (InitVal != 0 && !InitVal.isPowerOf2() &&
15973 !IsValueInFlagEnum(Enum, InitVal, true))
15974 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15979 // Now that the enum type is defined, ensure it's not been underaligned.
15980 if (Enum->hasAttrs())
15981 CheckAlignasUnderalignment(Enum);
15984 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15985 SourceLocation StartLoc,
15986 SourceLocation EndLoc) {
15987 StringLiteral *AsmString = cast<StringLiteral>(expr);
15989 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15990 AsmString, StartLoc,
15992 CurContext->addDecl(New);
15996 static void checkModuleImportContext(Sema &S, Module *M,
15997 SourceLocation ImportLoc, DeclContext *DC,
15998 bool FromInclude = false) {
15999 SourceLocation ExternCLoc;
16001 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16002 switch (LSD->getLanguage()) {
16003 case LinkageSpecDecl::lang_c:
16004 if (ExternCLoc.isInvalid())
16005 ExternCLoc = LSD->getLocStart();
16007 case LinkageSpecDecl::lang_cxx:
16010 DC = LSD->getParent();
16013 while (isa<LinkageSpecDecl>(DC))
16014 DC = DC->getParent();
16016 if (!isa<TranslationUnitDecl>(DC)) {
16017 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16018 ? diag::ext_module_import_not_at_top_level_noop
16019 : diag::err_module_import_not_at_top_level_fatal)
16020 << M->getFullModuleName() << DC;
16021 S.Diag(cast<Decl>(DC)->getLocStart(),
16022 diag::note_module_import_not_at_top_level) << DC;
16023 } else if (!M->IsExternC && ExternCLoc.isValid()) {
16024 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16025 << M->getFullModuleName();
16026 S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16030 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16031 SourceLocation ModuleLoc,
16032 ModuleDeclKind MDK,
16033 ModuleIdPath Path) {
16034 // A module implementation unit requires that we are not compiling a module
16035 // of any kind. A module interface unit requires that we are not compiling a
16037 switch (getLangOpts().getCompilingModule()) {
16038 case LangOptions::CMK_None:
16039 // It's OK to compile a module interface as a normal translation unit.
16042 case LangOptions::CMK_ModuleInterface:
16043 if (MDK != ModuleDeclKind::Implementation)
16046 // We were asked to compile a module interface unit but this is a module
16047 // implementation unit. That indicates the 'export' is missing.
16048 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16049 << FixItHint::CreateInsertion(ModuleLoc, "export ");
16052 case LangOptions::CMK_ModuleMap:
16053 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16057 // FIXME: Most of this work should be done by the preprocessor rather than
16058 // here, in order to support macro import.
16060 // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16061 // modules, the dots here are just another character that can appear in a
16063 std::string ModuleName;
16064 for (auto &Piece : Path) {
16065 if (!ModuleName.empty())
16067 ModuleName += Piece.first->getName();
16070 // FIXME: If we've already seen a module-declaration, report an error.
16072 // If a module name was explicitly specified on the command line, it must be
16074 if (!getLangOpts().CurrentModule.empty() &&
16075 getLangOpts().CurrentModule != ModuleName) {
16076 Diag(Path.front().second, diag::err_current_module_name_mismatch)
16077 << SourceRange(Path.front().second, Path.back().second)
16078 << getLangOpts().CurrentModule;
16081 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16083 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16087 case ModuleDeclKind::Module: {
16088 // FIXME: Check we're not in a submodule.
16090 // We can't have parsed or imported a definition of this module or parsed a
16091 // module map defining it already.
16092 if (auto *M = Map.findModule(ModuleName)) {
16093 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16094 if (M->DefinitionLoc.isValid())
16095 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16096 else if (const auto *FE = M->getASTFile())
16097 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16102 // Create a Module for the module that we're defining.
16103 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
16104 assert(Mod && "module creation should not fail");
16108 case ModuleDeclKind::Partition:
16109 // FIXME: Check we are in a submodule of the named module.
16112 case ModuleDeclKind::Implementation:
16113 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16114 PP.getIdentifierInfo(ModuleName), Path[0].second);
16115 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16116 /*IsIncludeDirective=*/false);
16122 // Enter the semantic scope of the module.
16123 ModuleScopes.push_back({});
16124 ModuleScopes.back().Module = Mod;
16125 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16126 VisibleModules.setVisible(Mod, ModuleLoc);
16128 // From now on, we have an owning module for all declarations we see.
16129 // However, those declarations are module-private unless explicitly
16131 Context.getTranslationUnitDecl()->setLocalOwningModule(Mod);
16133 // FIXME: Create a ModuleDecl.
16137 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16138 SourceLocation ImportLoc,
16139 ModuleIdPath Path) {
16141 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16142 /*IsIncludeDirective=*/false);
16146 VisibleModules.setVisible(Mod, ImportLoc);
16148 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16150 // FIXME: we should support importing a submodule within a different submodule
16151 // of the same top-level module. Until we do, make it an error rather than
16152 // silently ignoring the import.
16153 // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16154 // warn on a redundant import of the current module?
16155 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16156 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16157 Diag(ImportLoc, getLangOpts().isCompilingModule()
16158 ? diag::err_module_self_import
16159 : diag::err_module_import_in_implementation)
16160 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16162 SmallVector<SourceLocation, 2> IdentifierLocs;
16163 Module *ModCheck = Mod;
16164 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16165 // If we've run out of module parents, just drop the remaining identifiers.
16166 // We need the length to be consistent.
16169 ModCheck = ModCheck->Parent;
16171 IdentifierLocs.push_back(Path[I].second);
16174 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16175 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
16176 Mod, IdentifierLocs);
16177 if (!ModuleScopes.empty())
16178 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16179 TU->addDecl(Import);
16183 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16184 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16185 BuildModuleInclude(DirectiveLoc, Mod);
16188 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16189 // Determine whether we're in the #include buffer for a module. The #includes
16190 // in that buffer do not qualify as module imports; they're just an
16191 // implementation detail of us building the module.
16193 // FIXME: Should we even get ActOnModuleInclude calls for those?
16194 bool IsInModuleIncludes =
16195 TUKind == TU_Module &&
16196 getSourceManager().isWrittenInMainFile(DirectiveLoc);
16198 bool ShouldAddImport = !IsInModuleIncludes;
16200 // If this module import was due to an inclusion directive, create an
16201 // implicit import declaration to capture it in the AST.
16202 if (ShouldAddImport) {
16203 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16204 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16207 if (!ModuleScopes.empty())
16208 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16209 TU->addDecl(ImportD);
16210 Consumer.HandleImplicitImportDecl(ImportD);
16213 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16214 VisibleModules.setVisible(Mod, DirectiveLoc);
16217 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16218 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16220 ModuleScopes.push_back({});
16221 ModuleScopes.back().Module = Mod;
16222 if (getLangOpts().ModulesLocalVisibility)
16223 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16225 VisibleModules.setVisible(Mod, DirectiveLoc);
16227 // The enclosing context is now part of this module.
16228 // FIXME: Consider creating a child DeclContext to hold the entities
16229 // lexically within the module.
16230 if (getLangOpts().trackLocalOwningModule()) {
16231 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16232 cast<Decl>(DC)->setModuleOwnershipKind(
16233 getLangOpts().ModulesLocalVisibility
16234 ? Decl::ModuleOwnershipKind::VisibleWhenImported
16235 : Decl::ModuleOwnershipKind::Visible);
16236 cast<Decl>(DC)->setLocalOwningModule(Mod);
16241 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16242 if (getLangOpts().ModulesLocalVisibility) {
16243 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16244 // Leaving a module hides namespace names, so our visible namespace cache
16245 // is now out of date.
16246 VisibleNamespaceCache.clear();
16249 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16250 "left the wrong module scope");
16251 ModuleScopes.pop_back();
16253 // We got to the end of processing a local module. Create an
16254 // ImportDecl as we would for an imported module.
16255 FileID File = getSourceManager().getFileID(EomLoc);
16256 SourceLocation DirectiveLoc;
16257 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16258 // We reached the end of a #included module header. Use the #include loc.
16259 assert(File != getSourceManager().getMainFileID() &&
16260 "end of submodule in main source file");
16261 DirectiveLoc = getSourceManager().getIncludeLoc(File);
16263 // We reached an EOM pragma. Use the pragma location.
16264 DirectiveLoc = EomLoc;
16266 BuildModuleInclude(DirectiveLoc, Mod);
16268 // Any further declarations are in whatever module we returned to.
16269 if (getLangOpts().trackLocalOwningModule()) {
16270 // The parser guarantees that this is the same context that we entered
16271 // the module within.
16272 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16273 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16274 if (!getCurrentModule())
16275 cast<Decl>(DC)->setModuleOwnershipKind(
16276 Decl::ModuleOwnershipKind::Unowned);
16281 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16283 // Bail if we're not allowed to implicitly import a module here.
16284 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16285 VisibleModules.isVisible(Mod))
16288 // Create the implicit import declaration.
16289 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16290 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16292 TU->addDecl(ImportD);
16293 Consumer.HandleImplicitImportDecl(ImportD);
16295 // Make the module visible.
16296 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16297 VisibleModules.setVisible(Mod, Loc);
16300 /// We have parsed the start of an export declaration, including the '{'
16302 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16303 SourceLocation LBraceLoc) {
16304 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16306 // C++ Modules TS draft:
16307 // An export-declaration shall appear in the purview of a module other than
16308 // the global module.
16309 if (ModuleScopes.empty() || !ModuleScopes.back().Module ||
16310 ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
16311 Diag(ExportLoc, diag::err_export_not_in_module_interface);
16313 // An export-declaration [...] shall not contain more than one
16316 // The intent here is that an export-declaration cannot appear within another
16317 // export-declaration.
16318 if (D->isExported())
16319 Diag(ExportLoc, diag::err_export_within_export);
16321 CurContext->addDecl(D);
16322 PushDeclContext(S, D);
16323 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16327 /// Complete the definition of an export declaration.
16328 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16329 auto *ED = cast<ExportDecl>(D);
16330 if (RBraceLoc.isValid())
16331 ED->setRBraceLoc(RBraceLoc);
16333 // FIXME: Diagnose export of internal-linkage declaration (including
16334 // anonymous namespace).
16340 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16341 IdentifierInfo* AliasName,
16342 SourceLocation PragmaLoc,
16343 SourceLocation NameLoc,
16344 SourceLocation AliasNameLoc) {
16345 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16346 LookupOrdinaryName);
16347 AsmLabelAttr *Attr =
16348 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16350 // If a declaration that:
16351 // 1) declares a function or a variable
16352 // 2) has external linkage
16353 // already exists, add a label attribute to it.
16354 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16355 if (isDeclExternC(PrevDecl))
16356 PrevDecl->addAttr(Attr);
16358 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16359 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16360 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16362 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16365 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16366 SourceLocation PragmaLoc,
16367 SourceLocation NameLoc) {
16368 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16371 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16373 (void)WeakUndeclaredIdentifiers.insert(
16374 std::pair<IdentifierInfo*,WeakInfo>
16375 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16379 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16380 IdentifierInfo* AliasName,
16381 SourceLocation PragmaLoc,
16382 SourceLocation NameLoc,
16383 SourceLocation AliasNameLoc) {
16384 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16385 LookupOrdinaryName);
16386 WeakInfo W = WeakInfo(Name, NameLoc);
16388 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16389 if (!PrevDecl->hasAttr<AliasAttr>())
16390 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16391 DeclApplyPragmaWeak(TUScope, ND, W);
16393 (void)WeakUndeclaredIdentifiers.insert(
16394 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16398 Decl *Sema::getObjCDeclContext() const {
16399 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));