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)});
7003 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7004 // A variable can't shadow a local variable in an enclosing scope, if
7005 // they are separated by a non-capturing declaration context.
7006 for (DeclContext *ParentDC = NewDC;
7007 ParentDC && !ParentDC->Equals(OldDC);
7008 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7009 // Only block literals, captured statements, and lambda expressions
7010 // can capture; other scopes don't.
7011 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7012 !isLambdaCallOperator(ParentDC)) {
7020 // Only warn about certain kinds of shadowing for class members.
7021 if (NewDC && NewDC->isRecord()) {
7022 // In particular, don't warn about shadowing non-class members.
7023 if (!OldDC->isRecord())
7026 // TODO: should we warn about static data members shadowing
7027 // static data members from base classes?
7029 // TODO: don't diagnose for inaccessible shadowed members.
7030 // This is hard to do perfectly because we might friend the
7031 // shadowing context, but that's just a false negative.
7035 DeclarationName Name = R.getLookupName();
7037 // Emit warning and note.
7038 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7040 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7041 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7042 if (!CaptureLoc.isInvalid())
7043 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7044 << Name << /*explicitly*/ 1;
7045 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7048 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7049 /// when these variables are captured by the lambda.
7050 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7051 for (const auto &Shadow : LSI->ShadowingDecls) {
7052 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7053 // Try to avoid the warning when the shadowed decl isn't captured.
7054 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7055 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7056 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7057 ? diag::warn_decl_shadow_uncaptured_local
7058 : diag::warn_decl_shadow)
7059 << Shadow.VD->getDeclName()
7060 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7061 if (!CaptureLoc.isInvalid())
7062 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7063 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7064 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7068 /// \brief Check -Wshadow without the advantage of a previous lookup.
7069 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7070 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7073 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7074 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
7076 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7077 CheckShadow(D, ShadowedDecl, R);
7080 /// Check if 'E', which is an expression that is about to be modified, refers
7081 /// to a constructor parameter that shadows a field.
7082 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7083 // Quickly ignore expressions that can't be shadowing ctor parameters.
7084 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7086 E = E->IgnoreParenImpCasts();
7087 auto *DRE = dyn_cast<DeclRefExpr>(E);
7090 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7091 auto I = ShadowingDecls.find(D);
7092 if (I == ShadowingDecls.end())
7094 const NamedDecl *ShadowedDecl = I->second;
7095 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7096 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7097 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7098 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7100 // Avoid issuing multiple warnings about the same decl.
7101 ShadowingDecls.erase(I);
7104 /// Check for conflict between this global or extern "C" declaration and
7105 /// previous global or extern "C" declarations. This is only used in C++.
7106 template<typename T>
7107 static bool checkGlobalOrExternCConflict(
7108 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7109 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7110 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7112 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7113 // The common case: this global doesn't conflict with any extern "C"
7119 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7120 // Both the old and new declarations have C language linkage. This is a
7123 Previous.addDecl(Prev);
7127 // This is a global, non-extern "C" declaration, and there is a previous
7128 // non-global extern "C" declaration. Diagnose if this is a variable
7130 if (!isa<VarDecl>(ND))
7133 // The declaration is extern "C". Check for any declaration in the
7134 // translation unit which might conflict.
7136 // We have already performed the lookup into the translation unit.
7138 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7140 if (isa<VarDecl>(*I)) {
7146 DeclContext::lookup_result R =
7147 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7148 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7150 if (isa<VarDecl>(*I)) {
7154 // FIXME: If we have any other entity with this name in global scope,
7155 // the declaration is ill-formed, but that is a defect: it breaks the
7156 // 'stat' hack, for instance. Only variables can have mangled name
7157 // clashes with extern "C" declarations, so only they deserve a
7166 // Use the first declaration's location to ensure we point at something which
7167 // is lexically inside an extern "C" linkage-spec.
7168 assert(Prev && "should have found a previous declaration to diagnose");
7169 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7170 Prev = FD->getFirstDecl();
7172 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7174 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7176 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7181 /// Apply special rules for handling extern "C" declarations. Returns \c true
7182 /// if we have found that this is a redeclaration of some prior entity.
7184 /// Per C++ [dcl.link]p6:
7185 /// Two declarations [for a function or variable] with C language linkage
7186 /// with the same name that appear in different scopes refer to the same
7187 /// [entity]. An entity with C language linkage shall not be declared with
7188 /// the same name as an entity in global scope.
7189 template<typename T>
7190 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7191 LookupResult &Previous) {
7192 if (!S.getLangOpts().CPlusPlus) {
7193 // In C, when declaring a global variable, look for a corresponding 'extern'
7194 // variable declared in function scope. We don't need this in C++, because
7195 // we find local extern decls in the surrounding file-scope DeclContext.
7196 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7197 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7199 Previous.addDecl(Prev);
7206 // A declaration in the translation unit can conflict with an extern "C"
7208 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7209 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7211 // An extern "C" declaration can conflict with a declaration in the
7212 // translation unit or can be a redeclaration of an extern "C" declaration
7213 // in another scope.
7214 if (isIncompleteDeclExternC(S,ND))
7215 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7217 // Neither global nor extern "C": nothing to do.
7221 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7222 // If the decl is already known invalid, don't check it.
7223 if (NewVD->isInvalidDecl())
7226 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7227 QualType T = TInfo->getType();
7229 // Defer checking an 'auto' type until its initializer is attached.
7230 if (T->isUndeducedType())
7233 if (NewVD->hasAttrs())
7234 CheckAlignasUnderalignment(NewVD);
7236 if (T->isObjCObjectType()) {
7237 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7238 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7239 T = Context.getObjCObjectPointerType(T);
7243 // Emit an error if an address space was applied to decl with local storage.
7244 // This includes arrays of objects with address space qualifiers, but not
7245 // automatic variables that point to other address spaces.
7246 // ISO/IEC TR 18037 S5.1.2
7247 if (!getLangOpts().OpenCL
7248 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7249 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7250 NewVD->setInvalidDecl();
7254 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7256 if (getLangOpts().OpenCLVersion == 120 &&
7257 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7258 NewVD->isStaticLocal()) {
7259 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7260 NewVD->setInvalidDecl();
7264 if (getLangOpts().OpenCL) {
7265 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7266 if (NewVD->hasAttr<BlocksAttr>()) {
7267 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7271 if (T->isBlockPointerType()) {
7272 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7273 // can't use 'extern' storage class.
7274 if (!T.isConstQualified()) {
7275 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7277 NewVD->setInvalidDecl();
7280 if (NewVD->hasExternalStorage()) {
7281 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7282 NewVD->setInvalidDecl();
7286 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7287 // __constant address space.
7288 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7289 // variables inside a function can also be declared in the global
7291 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7292 NewVD->hasExternalStorage()) {
7293 if (!T->isSamplerT() &&
7294 !(T.getAddressSpace() == LangAS::opencl_constant ||
7295 (T.getAddressSpace() == LangAS::opencl_global &&
7296 getLangOpts().OpenCLVersion == 200))) {
7297 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7298 if (getLangOpts().OpenCLVersion == 200)
7299 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7300 << Scope << "global or constant";
7302 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7303 << Scope << "constant";
7304 NewVD->setInvalidDecl();
7308 if (T.getAddressSpace() == LangAS::opencl_global) {
7309 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7310 << 1 /*is any function*/ << "global";
7311 NewVD->setInvalidDecl();
7314 if (T.getAddressSpace() == LangAS::opencl_constant ||
7315 T.getAddressSpace() == LangAS::opencl_local) {
7316 FunctionDecl *FD = getCurFunctionDecl();
7317 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7319 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7320 if (T.getAddressSpace() == LangAS::opencl_constant)
7321 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7322 << 0 /*non-kernel only*/ << "constant";
7324 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7325 << 0 /*non-kernel only*/ << "local";
7326 NewVD->setInvalidDecl();
7329 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7330 // in the outermost scope of a kernel function.
7331 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7332 if (!getCurScope()->isFunctionScope()) {
7333 if (T.getAddressSpace() == LangAS::opencl_constant)
7334 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7337 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7339 NewVD->setInvalidDecl();
7343 } else if (T.getAddressSpace() != LangAS::Default) {
7344 // Do not allow other address spaces on automatic variable.
7345 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7346 NewVD->setInvalidDecl();
7352 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7353 && !NewVD->hasAttr<BlocksAttr>()) {
7354 if (getLangOpts().getGC() != LangOptions::NonGC)
7355 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7357 assert(!getLangOpts().ObjCAutoRefCount);
7358 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7362 bool isVM = T->isVariablyModifiedType();
7363 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7364 NewVD->hasAttr<BlocksAttr>())
7365 getCurFunction()->setHasBranchProtectedScope();
7367 if ((isVM && NewVD->hasLinkage()) ||
7368 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7369 bool SizeIsNegative;
7370 llvm::APSInt Oversized;
7371 TypeSourceInfo *FixedTInfo =
7372 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7373 SizeIsNegative, Oversized);
7374 if (!FixedTInfo && T->isVariableArrayType()) {
7375 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7376 // FIXME: This won't give the correct result for
7378 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7380 if (NewVD->isFileVarDecl())
7381 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7383 else if (NewVD->isStaticLocal())
7384 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7387 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7389 NewVD->setInvalidDecl();
7394 if (NewVD->isFileVarDecl())
7395 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7397 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7398 NewVD->setInvalidDecl();
7402 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7403 NewVD->setType(FixedTInfo->getType());
7404 NewVD->setTypeSourceInfo(FixedTInfo);
7407 if (T->isVoidType()) {
7408 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7409 // of objects and functions.
7410 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7411 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7413 NewVD->setInvalidDecl();
7418 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7419 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7420 NewVD->setInvalidDecl();
7424 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7425 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7426 NewVD->setInvalidDecl();
7430 if (NewVD->isConstexpr() && !T->isDependentType() &&
7431 RequireLiteralType(NewVD->getLocation(), T,
7432 diag::err_constexpr_var_non_literal)) {
7433 NewVD->setInvalidDecl();
7438 /// \brief Perform semantic checking on a newly-created variable
7441 /// This routine performs all of the type-checking required for a
7442 /// variable declaration once it has been built. It is used both to
7443 /// check variables after they have been parsed and their declarators
7444 /// have been translated into a declaration, and to check variables
7445 /// that have been instantiated from a template.
7447 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7449 /// Returns true if the variable declaration is a redeclaration.
7450 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7451 CheckVariableDeclarationType(NewVD);
7453 // If the decl is already known invalid, don't check it.
7454 if (NewVD->isInvalidDecl())
7457 // If we did not find anything by this name, look for a non-visible
7458 // extern "C" declaration with the same name.
7459 if (Previous.empty() &&
7460 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7461 Previous.setShadowed();
7463 if (!Previous.empty()) {
7464 MergeVarDecl(NewVD, Previous);
7471 struct FindOverriddenMethod {
7473 CXXMethodDecl *Method;
7475 /// Member lookup function that determines whether a given C++
7476 /// method overrides a method in a base class, to be used with
7477 /// CXXRecordDecl::lookupInBases().
7478 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7479 RecordDecl *BaseRecord =
7480 Specifier->getType()->getAs<RecordType>()->getDecl();
7482 DeclarationName Name = Method->getDeclName();
7484 // FIXME: Do we care about other names here too?
7485 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7486 // We really want to find the base class destructor here.
7487 QualType T = S->Context.getTypeDeclType(BaseRecord);
7488 CanQualType CT = S->Context.getCanonicalType(T);
7490 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7493 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7494 Path.Decls = Path.Decls.slice(1)) {
7495 NamedDecl *D = Path.Decls.front();
7496 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7497 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7506 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7507 } // end anonymous namespace
7509 /// \brief Report an error regarding overriding, along with any relevant
7510 /// overriden methods.
7512 /// \param DiagID the primary error to report.
7513 /// \param MD the overriding method.
7514 /// \param OEK which overrides to include as notes.
7515 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7516 OverrideErrorKind OEK = OEK_All) {
7517 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7518 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7519 E = MD->end_overridden_methods();
7521 // This check (& the OEK parameter) could be replaced by a predicate, but
7522 // without lambdas that would be overkill. This is still nicer than writing
7523 // out the diag loop 3 times.
7524 if ((OEK == OEK_All) ||
7525 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7526 (OEK == OEK_Deleted && (*I)->isDeleted()))
7527 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7531 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7532 /// and if so, check that it's a valid override and remember it.
7533 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7534 // Look for methods in base classes that this method might override.
7536 FindOverriddenMethod FOM;
7539 bool hasDeletedOverridenMethods = false;
7540 bool hasNonDeletedOverridenMethods = false;
7541 bool AddedAny = false;
7542 if (DC->lookupInBases(FOM, Paths)) {
7543 for (auto *I : Paths.found_decls()) {
7544 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7545 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7546 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7547 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7548 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7549 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7550 hasDeletedOverridenMethods |= OldMD->isDeleted();
7551 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7558 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7559 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7561 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7562 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7569 // Struct for holding all of the extra arguments needed by
7570 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7571 struct ActOnFDArgs {
7574 MultiTemplateParamsArg TemplateParamLists;
7577 } // end anonymous namespace
7581 // Callback to only accept typo corrections that have a non-zero edit distance.
7582 // Also only accept corrections that have the same parent decl.
7583 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7585 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7586 CXXRecordDecl *Parent)
7587 : Context(Context), OriginalFD(TypoFD),
7588 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7590 bool ValidateCandidate(const TypoCorrection &candidate) override {
7591 if (candidate.getEditDistance() == 0)
7594 SmallVector<unsigned, 1> MismatchedParams;
7595 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7596 CDeclEnd = candidate.end();
7597 CDecl != CDeclEnd; ++CDecl) {
7598 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7600 if (FD && !FD->hasBody() &&
7601 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7602 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7603 CXXRecordDecl *Parent = MD->getParent();
7604 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7606 } else if (!ExpectedParent) {
7616 ASTContext &Context;
7617 FunctionDecl *OriginalFD;
7618 CXXRecordDecl *ExpectedParent;
7621 } // end anonymous namespace
7623 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7624 TypoCorrectedFunctionDefinitions.insert(F);
7627 /// \brief Generate diagnostics for an invalid function redeclaration.
7629 /// This routine handles generating the diagnostic messages for an invalid
7630 /// function redeclaration, including finding possible similar declarations
7631 /// or performing typo correction if there are no previous declarations with
7634 /// Returns a NamedDecl iff typo correction was performed and substituting in
7635 /// the new declaration name does not cause new errors.
7636 static NamedDecl *DiagnoseInvalidRedeclaration(
7637 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7638 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7639 DeclarationName Name = NewFD->getDeclName();
7640 DeclContext *NewDC = NewFD->getDeclContext();
7641 SmallVector<unsigned, 1> MismatchedParams;
7642 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7643 TypoCorrection Correction;
7644 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7645 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7646 : diag::err_member_decl_does_not_match;
7647 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7648 IsLocalFriend ? Sema::LookupLocalFriendName
7649 : Sema::LookupOrdinaryName,
7650 Sema::ForRedeclaration);
7652 NewFD->setInvalidDecl();
7654 SemaRef.LookupName(Prev, S);
7656 SemaRef.LookupQualifiedName(Prev, NewDC);
7657 assert(!Prev.isAmbiguous() &&
7658 "Cannot have an ambiguity in previous-declaration lookup");
7659 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7660 if (!Prev.empty()) {
7661 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7662 Func != FuncEnd; ++Func) {
7663 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7665 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7666 // Add 1 to the index so that 0 can mean the mismatch didn't
7667 // involve a parameter
7669 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7670 NearMatches.push_back(std::make_pair(FD, ParamNum));
7673 // If the qualified name lookup yielded nothing, try typo correction
7674 } else if ((Correction = SemaRef.CorrectTypo(
7675 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7676 &ExtraArgs.D.getCXXScopeSpec(),
7677 llvm::make_unique<DifferentNameValidatorCCC>(
7678 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7679 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7680 // Set up everything for the call to ActOnFunctionDeclarator
7681 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7682 ExtraArgs.D.getIdentifierLoc());
7684 Previous.setLookupName(Correction.getCorrection());
7685 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7686 CDeclEnd = Correction.end();
7687 CDecl != CDeclEnd; ++CDecl) {
7688 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7689 if (FD && !FD->hasBody() &&
7690 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7691 Previous.addDecl(FD);
7694 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7697 // Retry building the function declaration with the new previous
7698 // declarations, and with errors suppressed.
7701 Sema::SFINAETrap Trap(SemaRef);
7703 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7704 // pieces need to verify the typo-corrected C++ declaration and hopefully
7705 // eliminate the need for the parameter pack ExtraArgs.
7706 Result = SemaRef.ActOnFunctionDeclarator(
7707 ExtraArgs.S, ExtraArgs.D,
7708 Correction.getCorrectionDecl()->getDeclContext(),
7709 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7710 ExtraArgs.AddToScope);
7712 if (Trap.hasErrorOccurred())
7717 // Determine which correction we picked.
7718 Decl *Canonical = Result->getCanonicalDecl();
7719 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7721 if ((*I)->getCanonicalDecl() == Canonical)
7722 Correction.setCorrectionDecl(*I);
7724 // Let Sema know about the correction.
7725 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7726 SemaRef.diagnoseTypo(
7728 SemaRef.PDiag(IsLocalFriend
7729 ? diag::err_no_matching_local_friend_suggest
7730 : diag::err_member_decl_does_not_match_suggest)
7731 << Name << NewDC << IsDefinition);
7735 // Pretend the typo correction never occurred
7736 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7737 ExtraArgs.D.getIdentifierLoc());
7738 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7740 Previous.setLookupName(Name);
7743 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7744 << Name << NewDC << IsDefinition << NewFD->getLocation();
7746 bool NewFDisConst = false;
7747 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7748 NewFDisConst = NewMD->isConst();
7750 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7751 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7752 NearMatch != NearMatchEnd; ++NearMatch) {
7753 FunctionDecl *FD = NearMatch->first;
7754 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7755 bool FDisConst = MD && MD->isConst();
7756 bool IsMember = MD || !IsLocalFriend;
7758 // FIXME: These notes are poorly worded for the local friend case.
7759 if (unsigned Idx = NearMatch->second) {
7760 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7761 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7762 if (Loc.isInvalid()) Loc = FD->getLocation();
7763 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7764 : diag::note_local_decl_close_param_match)
7765 << Idx << FDParam->getType()
7766 << NewFD->getParamDecl(Idx - 1)->getType();
7767 } else if (FDisConst != NewFDisConst) {
7768 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7769 << NewFDisConst << FD->getSourceRange().getEnd();
7771 SemaRef.Diag(FD->getLocation(),
7772 IsMember ? diag::note_member_def_close_match
7773 : diag::note_local_decl_close_match);
7778 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7779 switch (D.getDeclSpec().getStorageClassSpec()) {
7780 default: llvm_unreachable("Unknown storage class!");
7781 case DeclSpec::SCS_auto:
7782 case DeclSpec::SCS_register:
7783 case DeclSpec::SCS_mutable:
7784 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7785 diag::err_typecheck_sclass_func);
7786 D.getMutableDeclSpec().ClearStorageClassSpecs();
7789 case DeclSpec::SCS_unspecified: break;
7790 case DeclSpec::SCS_extern:
7791 if (D.getDeclSpec().isExternInLinkageSpec())
7794 case DeclSpec::SCS_static: {
7795 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7797 // The declaration of an identifier for a function that has
7798 // block scope shall have no explicit storage-class specifier
7799 // other than extern
7800 // See also (C++ [dcl.stc]p4).
7801 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7802 diag::err_static_block_func);
7807 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7810 // No explicit storage class has already been returned
7814 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7815 DeclContext *DC, QualType &R,
7816 TypeSourceInfo *TInfo,
7818 bool &IsVirtualOkay) {
7819 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7820 DeclarationName Name = NameInfo.getName();
7822 FunctionDecl *NewFD = nullptr;
7823 bool isInline = D.getDeclSpec().isInlineSpecified();
7825 if (!SemaRef.getLangOpts().CPlusPlus) {
7826 // Determine whether the function was written with a
7827 // prototype. This true when:
7828 // - there is a prototype in the declarator, or
7829 // - the type R of the function is some kind of typedef or other non-
7830 // attributed reference to a type name (which eventually refers to a
7833 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7834 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7836 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7837 D.getLocStart(), NameInfo, R,
7838 TInfo, SC, isInline,
7839 HasPrototype, false);
7840 if (D.isInvalidType())
7841 NewFD->setInvalidDecl();
7846 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7847 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7849 // Check that the return type is not an abstract class type.
7850 // For record types, this is done by the AbstractClassUsageDiagnoser once
7851 // the class has been completely parsed.
7852 if (!DC->isRecord() &&
7853 SemaRef.RequireNonAbstractType(
7854 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7855 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7858 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7859 // This is a C++ constructor declaration.
7860 assert(DC->isRecord() &&
7861 "Constructors can only be declared in a member context");
7863 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7864 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7865 D.getLocStart(), NameInfo,
7866 R, TInfo, isExplicit, isInline,
7867 /*isImplicitlyDeclared=*/false,
7870 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7871 // This is a C++ destructor declaration.
7872 if (DC->isRecord()) {
7873 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7874 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7875 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7876 SemaRef.Context, Record,
7878 NameInfo, R, TInfo, isInline,
7879 /*isImplicitlyDeclared=*/false);
7881 // If the class is complete, then we now create the implicit exception
7882 // specification. If the class is incomplete or dependent, we can't do
7884 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7885 Record->getDefinition() && !Record->isBeingDefined() &&
7886 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7887 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7890 IsVirtualOkay = true;
7894 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7897 // Create a FunctionDecl to satisfy the function definition parsing
7899 return FunctionDecl::Create(SemaRef.Context, DC,
7901 D.getIdentifierLoc(), Name, R, TInfo,
7903 /*hasPrototype=*/true, isConstexpr);
7906 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7907 if (!DC->isRecord()) {
7908 SemaRef.Diag(D.getIdentifierLoc(),
7909 diag::err_conv_function_not_member);
7913 SemaRef.CheckConversionDeclarator(D, R, SC);
7914 IsVirtualOkay = true;
7915 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7916 D.getLocStart(), NameInfo,
7917 R, TInfo, isInline, isExplicit,
7918 isConstexpr, SourceLocation());
7920 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7921 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7923 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7924 isExplicit, NameInfo, R, TInfo,
7926 } else if (DC->isRecord()) {
7927 // If the name of the function is the same as the name of the record,
7928 // then this must be an invalid constructor that has a return type.
7929 // (The parser checks for a return type and makes the declarator a
7930 // constructor if it has no return type).
7931 if (Name.getAsIdentifierInfo() &&
7932 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7933 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7934 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7935 << SourceRange(D.getIdentifierLoc());
7939 // This is a C++ method declaration.
7940 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7941 cast<CXXRecordDecl>(DC),
7942 D.getLocStart(), NameInfo, R,
7943 TInfo, SC, isInline,
7944 isConstexpr, SourceLocation());
7945 IsVirtualOkay = !Ret->isStatic();
7949 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7950 if (!isFriend && SemaRef.CurContext->isRecord())
7953 // Determine whether the function was written with a
7954 // prototype. This true when:
7955 // - we're in C++ (where every function has a prototype),
7956 return FunctionDecl::Create(SemaRef.Context, DC,
7958 NameInfo, R, TInfo, SC, isInline,
7959 true/*HasPrototype*/, isConstexpr);
7963 enum OpenCLParamType {
7967 InvalidAddrSpacePtrKernelParam,
7972 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7973 if (PT->isPointerType()) {
7974 QualType PointeeType = PT->getPointeeType();
7975 if (PointeeType->isPointerType())
7976 return PtrPtrKernelParam;
7977 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7978 PointeeType.getAddressSpace() == 0)
7979 return InvalidAddrSpacePtrKernelParam;
7980 return PtrKernelParam;
7983 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7984 // be used as builtin types.
7986 if (PT->isImageType())
7987 return PtrKernelParam;
7989 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
7990 return InvalidKernelParam;
7992 // OpenCL extension spec v1.2 s9.5:
7993 // This extension adds support for half scalar and vector types as built-in
7994 // types that can be used for arithmetic operations, conversions etc.
7995 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7996 return InvalidKernelParam;
7998 if (PT->isRecordType())
7999 return RecordKernelParam;
8001 return ValidKernelParam;
8004 static void checkIsValidOpenCLKernelParameter(
8008 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8009 QualType PT = Param->getType();
8011 // Cache the valid types we encounter to avoid rechecking structs that are
8013 if (ValidTypes.count(PT.getTypePtr()))
8016 switch (getOpenCLKernelParameterType(S, PT)) {
8017 case PtrPtrKernelParam:
8018 // OpenCL v1.2 s6.9.a:
8019 // A kernel function argument cannot be declared as a
8020 // pointer to a pointer type.
8021 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8025 case InvalidAddrSpacePtrKernelParam:
8026 // OpenCL v1.0 s6.5:
8027 // __kernel function arguments declared to be a pointer of a type can point
8028 // to one of the following address spaces only : __global, __local or
8030 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8034 // OpenCL v1.2 s6.9.k:
8035 // Arguments to kernel functions in a program cannot be declared with the
8036 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8037 // uintptr_t or a struct and/or union that contain fields declared to be
8038 // one of these built-in scalar types.
8040 case InvalidKernelParam:
8041 // OpenCL v1.2 s6.8 n:
8042 // A kernel function argument cannot be declared
8044 // Do not diagnose half type since it is diagnosed as invalid argument
8045 // type for any function elsewhere.
8046 if (!PT->isHalfType())
8047 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8051 case PtrKernelParam:
8052 case ValidKernelParam:
8053 ValidTypes.insert(PT.getTypePtr());
8056 case RecordKernelParam:
8060 // Track nested structs we will inspect
8061 SmallVector<const Decl *, 4> VisitStack;
8063 // Track where we are in the nested structs. Items will migrate from
8064 // VisitStack to HistoryStack as we do the DFS for bad field.
8065 SmallVector<const FieldDecl *, 4> HistoryStack;
8066 HistoryStack.push_back(nullptr);
8068 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8069 VisitStack.push_back(PD);
8071 assert(VisitStack.back() && "First decl null?");
8074 const Decl *Next = VisitStack.pop_back_val();
8076 assert(!HistoryStack.empty());
8077 // Found a marker, we have gone up a level
8078 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8079 ValidTypes.insert(Hist->getType().getTypePtr());
8084 // Adds everything except the original parameter declaration (which is not a
8085 // field itself) to the history stack.
8086 const RecordDecl *RD;
8087 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8088 HistoryStack.push_back(Field);
8089 RD = Field->getType()->castAs<RecordType>()->getDecl();
8091 RD = cast<RecordDecl>(Next);
8094 // Add a null marker so we know when we've gone back up a level
8095 VisitStack.push_back(nullptr);
8097 for (const auto *FD : RD->fields()) {
8098 QualType QT = FD->getType();
8100 if (ValidTypes.count(QT.getTypePtr()))
8103 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8104 if (ParamType == ValidKernelParam)
8107 if (ParamType == RecordKernelParam) {
8108 VisitStack.push_back(FD);
8112 // OpenCL v1.2 s6.9.p:
8113 // Arguments to kernel functions that are declared to be a struct or union
8114 // do not allow OpenCL objects to be passed as elements of the struct or
8116 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8117 ParamType == InvalidAddrSpacePtrKernelParam) {
8118 S.Diag(Param->getLocation(),
8119 diag::err_record_with_pointers_kernel_param)
8120 << PT->isUnionType()
8123 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8126 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8127 << PD->getDeclName();
8129 // We have an error, now let's go back up through history and show where
8130 // the offending field came from
8131 for (ArrayRef<const FieldDecl *>::const_iterator
8132 I = HistoryStack.begin() + 1,
8133 E = HistoryStack.end();
8135 const FieldDecl *OuterField = *I;
8136 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8137 << OuterField->getType();
8140 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8141 << QT->isPointerType()
8146 } while (!VisitStack.empty());
8149 /// Find the DeclContext in which a tag is implicitly declared if we see an
8150 /// elaborated type specifier in the specified context, and lookup finds
8152 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8153 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8154 DC = DC->getParent();
8158 /// Find the Scope in which a tag is implicitly declared if we see an
8159 /// elaborated type specifier in the specified context, and lookup finds
8161 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8162 while (S->isClassScope() ||
8163 (LangOpts.CPlusPlus &&
8164 S->isFunctionPrototypeScope()) ||
8165 ((S->getFlags() & Scope::DeclScope) == 0) ||
8166 (S->getEntity() && S->getEntity()->isTransparentContext()))
8172 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8173 TypeSourceInfo *TInfo, LookupResult &Previous,
8174 MultiTemplateParamsArg TemplateParamLists,
8176 QualType R = TInfo->getType();
8178 assert(R.getTypePtr()->isFunctionType());
8180 // TODO: consider using NameInfo for diagnostic.
8181 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8182 DeclarationName Name = NameInfo.getName();
8183 StorageClass SC = getFunctionStorageClass(*this, D);
8185 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8186 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8187 diag::err_invalid_thread)
8188 << DeclSpec::getSpecifierName(TSCS);
8190 if (D.isFirstDeclarationOfMember())
8191 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8192 D.getIdentifierLoc());
8194 bool isFriend = false;
8195 FunctionTemplateDecl *FunctionTemplate = nullptr;
8196 bool isMemberSpecialization = false;
8197 bool isFunctionTemplateSpecialization = false;
8199 bool isDependentClassScopeExplicitSpecialization = false;
8200 bool HasExplicitTemplateArgs = false;
8201 TemplateArgumentListInfo TemplateArgs;
8203 bool isVirtualOkay = false;
8205 DeclContext *OriginalDC = DC;
8206 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8208 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8210 if (!NewFD) return nullptr;
8212 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8213 NewFD->setTopLevelDeclInObjCContainer();
8215 // Set the lexical context. If this is a function-scope declaration, or has a
8216 // C++ scope specifier, or is the object of a friend declaration, the lexical
8217 // context will be different from the semantic context.
8218 NewFD->setLexicalDeclContext(CurContext);
8220 if (IsLocalExternDecl)
8221 NewFD->setLocalExternDecl();
8223 if (getLangOpts().CPlusPlus) {
8224 bool isInline = D.getDeclSpec().isInlineSpecified();
8225 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8226 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8227 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8228 bool isConcept = D.getDeclSpec().isConceptSpecified();
8229 isFriend = D.getDeclSpec().isFriendSpecified();
8230 if (isFriend && !isInline && D.isFunctionDefinition()) {
8231 // C++ [class.friend]p5
8232 // A function can be defined in a friend declaration of a
8233 // class . . . . Such a function is implicitly inline.
8234 NewFD->setImplicitlyInline();
8237 // If this is a method defined in an __interface, and is not a constructor
8238 // or an overloaded operator, then set the pure flag (isVirtual will already
8240 if (const CXXRecordDecl *Parent =
8241 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8242 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8243 NewFD->setPure(true);
8245 // C++ [class.union]p2
8246 // A union can have member functions, but not virtual functions.
8247 if (isVirtual && Parent->isUnion())
8248 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8251 SetNestedNameSpecifier(NewFD, D);
8252 isMemberSpecialization = false;
8253 isFunctionTemplateSpecialization = false;
8254 if (D.isInvalidType())
8255 NewFD->setInvalidDecl();
8257 // Match up the template parameter lists with the scope specifier, then
8258 // determine whether we have a template or a template specialization.
8259 bool Invalid = false;
8260 if (TemplateParameterList *TemplateParams =
8261 MatchTemplateParametersToScopeSpecifier(
8262 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8263 D.getCXXScopeSpec(),
8264 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8265 ? D.getName().TemplateId
8267 TemplateParamLists, isFriend, isMemberSpecialization,
8269 if (TemplateParams->size() > 0) {
8270 // This is a function template
8272 // Check that we can declare a template here.
8273 if (CheckTemplateDeclScope(S, TemplateParams))
8274 NewFD->setInvalidDecl();
8276 // A destructor cannot be a template.
8277 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8278 Diag(NewFD->getLocation(), diag::err_destructor_template);
8279 NewFD->setInvalidDecl();
8282 // If we're adding a template to a dependent context, we may need to
8283 // rebuilding some of the types used within the template parameter list,
8284 // now that we know what the current instantiation is.
8285 if (DC->isDependentContext()) {
8286 ContextRAII SavedContext(*this, DC);
8287 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8291 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8292 NewFD->getLocation(),
8293 Name, TemplateParams,
8295 FunctionTemplate->setLexicalDeclContext(CurContext);
8296 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8298 // For source fidelity, store the other template param lists.
8299 if (TemplateParamLists.size() > 1) {
8300 NewFD->setTemplateParameterListsInfo(Context,
8301 TemplateParamLists.drop_back(1));
8304 // This is a function template specialization.
8305 isFunctionTemplateSpecialization = true;
8306 // For source fidelity, store all the template param lists.
8307 if (TemplateParamLists.size() > 0)
8308 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8310 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8312 // We want to remove the "template<>", found here.
8313 SourceRange RemoveRange = TemplateParams->getSourceRange();
8315 // If we remove the template<> and the name is not a
8316 // template-id, we're actually silently creating a problem:
8317 // the friend declaration will refer to an untemplated decl,
8318 // and clearly the user wants a template specialization. So
8319 // we need to insert '<>' after the name.
8320 SourceLocation InsertLoc;
8321 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8322 InsertLoc = D.getName().getSourceRange().getEnd();
8323 InsertLoc = getLocForEndOfToken(InsertLoc);
8326 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8327 << Name << RemoveRange
8328 << FixItHint::CreateRemoval(RemoveRange)
8329 << FixItHint::CreateInsertion(InsertLoc, "<>");
8334 // All template param lists were matched against the scope specifier:
8335 // this is NOT (an explicit specialization of) a template.
8336 if (TemplateParamLists.size() > 0)
8337 // For source fidelity, store all the template param lists.
8338 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8342 NewFD->setInvalidDecl();
8343 if (FunctionTemplate)
8344 FunctionTemplate->setInvalidDecl();
8347 // C++ [dcl.fct.spec]p5:
8348 // The virtual specifier shall only be used in declarations of
8349 // nonstatic class member functions that appear within a
8350 // member-specification of a class declaration; see 10.3.
8352 if (isVirtual && !NewFD->isInvalidDecl()) {
8353 if (!isVirtualOkay) {
8354 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8355 diag::err_virtual_non_function);
8356 } else if (!CurContext->isRecord()) {
8357 // 'virtual' was specified outside of the class.
8358 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8359 diag::err_virtual_out_of_class)
8360 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8361 } else if (NewFD->getDescribedFunctionTemplate()) {
8362 // C++ [temp.mem]p3:
8363 // A member function template shall not be virtual.
8364 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8365 diag::err_virtual_member_function_template)
8366 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8368 // Okay: Add virtual to the method.
8369 NewFD->setVirtualAsWritten(true);
8372 if (getLangOpts().CPlusPlus14 &&
8373 NewFD->getReturnType()->isUndeducedType())
8374 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8377 if (getLangOpts().CPlusPlus14 &&
8378 (NewFD->isDependentContext() ||
8379 (isFriend && CurContext->isDependentContext())) &&
8380 NewFD->getReturnType()->isUndeducedType()) {
8381 // If the function template is referenced directly (for instance, as a
8382 // member of the current instantiation), pretend it has a dependent type.
8383 // This is not really justified by the standard, but is the only sane
8385 // FIXME: For a friend function, we have not marked the function as being
8386 // a friend yet, so 'isDependentContext' on the FD doesn't work.
8387 const FunctionProtoType *FPT =
8388 NewFD->getType()->castAs<FunctionProtoType>();
8390 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8391 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8392 FPT->getExtProtoInfo()));
8395 // C++ [dcl.fct.spec]p3:
8396 // The inline specifier shall not appear on a block scope function
8398 if (isInline && !NewFD->isInvalidDecl()) {
8399 if (CurContext->isFunctionOrMethod()) {
8400 // 'inline' is not allowed on block scope function declaration.
8401 Diag(D.getDeclSpec().getInlineSpecLoc(),
8402 diag::err_inline_declaration_block_scope) << Name
8403 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8407 // C++ [dcl.fct.spec]p6:
8408 // The explicit specifier shall be used only in the declaration of a
8409 // constructor or conversion function within its class definition;
8410 // see 12.3.1 and 12.3.2.
8411 if (isExplicit && !NewFD->isInvalidDecl() &&
8412 !isa<CXXDeductionGuideDecl>(NewFD)) {
8413 if (!CurContext->isRecord()) {
8414 // 'explicit' was specified outside of the class.
8415 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8416 diag::err_explicit_out_of_class)
8417 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8418 } else if (!isa<CXXConstructorDecl>(NewFD) &&
8419 !isa<CXXConversionDecl>(NewFD)) {
8420 // 'explicit' was specified on a function that wasn't a constructor
8421 // or conversion function.
8422 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8423 diag::err_explicit_non_ctor_or_conv_function)
8424 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8429 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8430 // are implicitly inline.
8431 NewFD->setImplicitlyInline();
8433 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8434 // be either constructors or to return a literal type. Therefore,
8435 // destructors cannot be declared constexpr.
8436 if (isa<CXXDestructorDecl>(NewFD))
8437 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8441 // This is a function concept.
8442 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8445 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8446 // applied only to the definition of a function template [...]
8447 if (!D.isFunctionDefinition()) {
8448 Diag(D.getDeclSpec().getConceptSpecLoc(),
8449 diag::err_function_concept_not_defined);
8450 NewFD->setInvalidDecl();
8453 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8454 // have no exception-specification and is treated as if it were specified
8455 // with noexcept(true) (15.4). [...]
8456 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8457 if (FPT->hasExceptionSpec()) {
8459 if (D.isFunctionDeclarator())
8460 Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8461 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8462 << FixItHint::CreateRemoval(Range);
8463 NewFD->setInvalidDecl();
8465 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8468 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8469 // following restrictions:
8470 // - The declared return type shall have the type bool.
8471 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8472 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8473 NewFD->setInvalidDecl();
8476 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8477 // following restrictions:
8478 // - The declaration's parameter list shall be equivalent to an empty
8480 if (FPT->getNumParams() > 0 || FPT->isVariadic())
8481 Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8484 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8485 // implicity defined to be a constexpr declaration (implicitly inline)
8486 NewFD->setImplicitlyInline();
8488 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8489 // be declared with the thread_local, inline, friend, or constexpr
8490 // specifiers, [...]
8492 Diag(D.getDeclSpec().getInlineSpecLoc(),
8493 diag::err_concept_decl_invalid_specifiers)
8495 NewFD->setInvalidDecl(true);
8499 Diag(D.getDeclSpec().getFriendSpecLoc(),
8500 diag::err_concept_decl_invalid_specifiers)
8502 NewFD->setInvalidDecl(true);
8506 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8507 diag::err_concept_decl_invalid_specifiers)
8509 NewFD->setInvalidDecl(true);
8512 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8513 // applied only to the definition of a function template or variable
8514 // template, declared in namespace scope.
8515 if (isFunctionTemplateSpecialization) {
8516 Diag(D.getDeclSpec().getConceptSpecLoc(),
8517 diag::err_concept_specified_specialization) << 1;
8518 NewFD->setInvalidDecl(true);
8523 // If __module_private__ was specified, mark the function accordingly.
8524 if (D.getDeclSpec().isModulePrivateSpecified()) {
8525 if (isFunctionTemplateSpecialization) {
8526 SourceLocation ModulePrivateLoc
8527 = D.getDeclSpec().getModulePrivateSpecLoc();
8528 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8530 << FixItHint::CreateRemoval(ModulePrivateLoc);
8532 NewFD->setModulePrivate();
8533 if (FunctionTemplate)
8534 FunctionTemplate->setModulePrivate();
8539 if (FunctionTemplate) {
8540 FunctionTemplate->setObjectOfFriendDecl();
8541 FunctionTemplate->setAccess(AS_public);
8543 NewFD->setObjectOfFriendDecl();
8544 NewFD->setAccess(AS_public);
8547 // If a function is defined as defaulted or deleted, mark it as such now.
8548 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8549 // definition kind to FDK_Definition.
8550 switch (D.getFunctionDefinitionKind()) {
8551 case FDK_Declaration:
8552 case FDK_Definition:
8556 NewFD->setDefaulted();
8560 NewFD->setDeletedAsWritten();
8564 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8565 D.isFunctionDefinition()) {
8566 // C++ [class.mfct]p2:
8567 // A member function may be defined (8.4) in its class definition, in
8568 // which case it is an inline member function (7.1.2)
8569 NewFD->setImplicitlyInline();
8572 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8573 !CurContext->isRecord()) {
8574 // C++ [class.static]p1:
8575 // A data or function member of a class may be declared static
8576 // in a class definition, in which case it is a static member of
8579 // Complain about the 'static' specifier if it's on an out-of-line
8580 // member function definition.
8581 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8582 diag::err_static_out_of_line)
8583 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8586 // C++11 [except.spec]p15:
8587 // A deallocation function with no exception-specification is treated
8588 // as if it were specified with noexcept(true).
8589 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8590 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8591 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8592 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8593 NewFD->setType(Context.getFunctionType(
8594 FPT->getReturnType(), FPT->getParamTypes(),
8595 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8598 // Filter out previous declarations that don't match the scope.
8599 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8600 D.getCXXScopeSpec().isNotEmpty() ||
8601 isMemberSpecialization ||
8602 isFunctionTemplateSpecialization);
8604 // Handle GNU asm-label extension (encoded as an attribute).
8605 if (Expr *E = (Expr*) D.getAsmLabel()) {
8606 // The parser guarantees this is a string.
8607 StringLiteral *SE = cast<StringLiteral>(E);
8608 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8609 SE->getString(), 0));
8610 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8611 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8612 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8613 if (I != ExtnameUndeclaredIdentifiers.end()) {
8614 if (isDeclExternC(NewFD)) {
8615 NewFD->addAttr(I->second);
8616 ExtnameUndeclaredIdentifiers.erase(I);
8618 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8619 << /*Variable*/0 << NewFD;
8623 // Copy the parameter declarations from the declarator D to the function
8624 // declaration NewFD, if they are available. First scavenge them into Params.
8625 SmallVector<ParmVarDecl*, 16> Params;
8627 if (D.isFunctionDeclarator(FTIIdx)) {
8628 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8630 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8631 // function that takes no arguments, not a function that takes a
8632 // single void argument.
8633 // We let through "const void" here because Sema::GetTypeForDeclarator
8634 // already checks for that case.
8635 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8636 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8637 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8638 assert(Param->getDeclContext() != NewFD && "Was set before ?");
8639 Param->setDeclContext(NewFD);
8640 Params.push_back(Param);
8642 if (Param->isInvalidDecl())
8643 NewFD->setInvalidDecl();
8647 if (!getLangOpts().CPlusPlus) {
8648 // In C, find all the tag declarations from the prototype and move them
8649 // into the function DeclContext. Remove them from the surrounding tag
8650 // injection context of the function, which is typically but not always
8652 DeclContext *PrototypeTagContext =
8653 getTagInjectionContext(NewFD->getLexicalDeclContext());
8654 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8655 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8657 // We don't want to reparent enumerators. Look at their parent enum
8660 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8661 TD = cast<EnumDecl>(ECD->getDeclContext());
8665 DeclContext *TagDC = TD->getLexicalDeclContext();
8666 if (!TagDC->containsDecl(TD))
8668 TagDC->removeDecl(TD);
8669 TD->setDeclContext(NewFD);
8672 // Preserve the lexical DeclContext if it is not the surrounding tag
8673 // injection context of the FD. In this example, the semantic context of
8674 // E will be f and the lexical context will be S, while both the
8675 // semantic and lexical contexts of S will be f:
8676 // void f(struct S { enum E { a } f; } s);
8677 if (TagDC != PrototypeTagContext)
8678 TD->setLexicalDeclContext(TagDC);
8681 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8682 // When we're declaring a function with a typedef, typeof, etc as in the
8683 // following example, we'll need to synthesize (unnamed)
8684 // parameters for use in the declaration.
8687 // typedef void fn(int);
8691 // Synthesize a parameter for each argument type.
8692 for (const auto &AI : FT->param_types()) {
8693 ParmVarDecl *Param =
8694 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8695 Param->setScopeInfo(0, Params.size());
8696 Params.push_back(Param);
8699 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8700 "Should not need args for typedef of non-prototype fn");
8703 // Finally, we know we have the right number of parameters, install them.
8704 NewFD->setParams(Params);
8706 if (D.getDeclSpec().isNoreturnSpecified())
8708 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8711 // Functions returning a variably modified type violate C99 6.7.5.2p2
8712 // because all functions have linkage.
8713 if (!NewFD->isInvalidDecl() &&
8714 NewFD->getReturnType()->isVariablyModifiedType()) {
8715 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8716 NewFD->setInvalidDecl();
8719 // Apply an implicit SectionAttr if '#pragma clang section text' is active
8720 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8721 !NewFD->hasAttr<SectionAttr>()) {
8722 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8723 PragmaClangTextSection.SectionName,
8724 PragmaClangTextSection.PragmaLocation));
8727 // Apply an implicit SectionAttr if #pragma code_seg is active.
8728 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8729 !NewFD->hasAttr<SectionAttr>()) {
8731 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8732 CodeSegStack.CurrentValue->getString(),
8733 CodeSegStack.CurrentPragmaLocation));
8734 if (UnifySection(CodeSegStack.CurrentValue->getString(),
8735 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8736 ASTContext::PSF_Read,
8738 NewFD->dropAttr<SectionAttr>();
8741 // Handle attributes.
8742 ProcessDeclAttributes(S, NewFD, D);
8744 if (getLangOpts().OpenCL) {
8745 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8746 // type declaration will generate a compilation error.
8747 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8748 if (AddressSpace == LangAS::opencl_local ||
8749 AddressSpace == LangAS::opencl_global ||
8750 AddressSpace == LangAS::opencl_constant) {
8751 Diag(NewFD->getLocation(),
8752 diag::err_opencl_return_value_with_address_space);
8753 NewFD->setInvalidDecl();
8757 if (!getLangOpts().CPlusPlus) {
8758 // Perform semantic checking on the function declaration.
8759 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8760 CheckMain(NewFD, D.getDeclSpec());
8762 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8763 CheckMSVCRTEntryPoint(NewFD);
8765 if (!NewFD->isInvalidDecl())
8766 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8767 isMemberSpecialization));
8768 else if (!Previous.empty())
8769 // Recover gracefully from an invalid redeclaration.
8770 D.setRedeclaration(true);
8771 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8772 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8773 "previous declaration set still overloaded");
8775 // Diagnose no-prototype function declarations with calling conventions that
8776 // don't support variadic calls. Only do this in C and do it after merging
8777 // possibly prototyped redeclarations.
8778 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8779 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8780 CallingConv CC = FT->getExtInfo().getCC();
8781 if (!supportsVariadicCall(CC)) {
8782 // Windows system headers sometimes accidentally use stdcall without
8783 // (void) parameters, so we relax this to a warning.
8785 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8786 Diag(NewFD->getLocation(), DiagID)
8787 << FunctionType::getNameForCallConv(CC);
8791 // C++11 [replacement.functions]p3:
8792 // The program's definitions shall not be specified as inline.
8794 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8796 // Suppress the diagnostic if the function is __attribute__((used)), since
8797 // that forces an external definition to be emitted.
8798 if (D.getDeclSpec().isInlineSpecified() &&
8799 NewFD->isReplaceableGlobalAllocationFunction() &&
8800 !NewFD->hasAttr<UsedAttr>())
8801 Diag(D.getDeclSpec().getInlineSpecLoc(),
8802 diag::ext_operator_new_delete_declared_inline)
8803 << NewFD->getDeclName();
8805 // If the declarator is a template-id, translate the parser's template
8806 // argument list into our AST format.
8807 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8808 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8809 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8810 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8811 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8812 TemplateId->NumArgs);
8813 translateTemplateArguments(TemplateArgsPtr,
8816 HasExplicitTemplateArgs = true;
8818 if (NewFD->isInvalidDecl()) {
8819 HasExplicitTemplateArgs = false;
8820 } else if (FunctionTemplate) {
8821 // Function template with explicit template arguments.
8822 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8823 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8825 HasExplicitTemplateArgs = false;
8827 assert((isFunctionTemplateSpecialization ||
8828 D.getDeclSpec().isFriendSpecified()) &&
8829 "should have a 'template<>' for this decl");
8830 // "friend void foo<>(int);" is an implicit specialization decl.
8831 isFunctionTemplateSpecialization = true;
8833 } else if (isFriend && isFunctionTemplateSpecialization) {
8834 // This combination is only possible in a recovery case; the user
8835 // wrote something like:
8836 // template <> friend void foo(int);
8837 // which we're recovering from as if the user had written:
8838 // friend void foo<>(int);
8839 // Go ahead and fake up a template id.
8840 HasExplicitTemplateArgs = true;
8841 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8842 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8845 // We do not add HD attributes to specializations here because
8846 // they may have different constexpr-ness compared to their
8847 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8848 // may end up with different effective targets. Instead, a
8849 // specialization inherits its target attributes from its template
8850 // in the CheckFunctionTemplateSpecialization() call below.
8851 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8852 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8854 // If it's a friend (and only if it's a friend), it's possible
8855 // that either the specialized function type or the specialized
8856 // template is dependent, and therefore matching will fail. In
8857 // this case, don't check the specialization yet.
8858 bool InstantiationDependent = false;
8859 if (isFunctionTemplateSpecialization && isFriend &&
8860 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8861 TemplateSpecializationType::anyDependentTemplateArguments(
8863 InstantiationDependent))) {
8864 assert(HasExplicitTemplateArgs &&
8865 "friend function specialization without template args");
8866 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8868 NewFD->setInvalidDecl();
8869 } else if (isFunctionTemplateSpecialization) {
8870 if (CurContext->isDependentContext() && CurContext->isRecord()
8872 isDependentClassScopeExplicitSpecialization = true;
8873 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8874 diag::ext_function_specialization_in_class :
8875 diag::err_function_specialization_in_class)
8876 << NewFD->getDeclName();
8877 } else if (CheckFunctionTemplateSpecialization(NewFD,
8878 (HasExplicitTemplateArgs ? &TemplateArgs
8881 NewFD->setInvalidDecl();
8884 // A storage-class-specifier shall not be specified in an explicit
8885 // specialization (14.7.3)
8886 FunctionTemplateSpecializationInfo *Info =
8887 NewFD->getTemplateSpecializationInfo();
8888 if (Info && SC != SC_None) {
8889 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8890 Diag(NewFD->getLocation(),
8891 diag::err_explicit_specialization_inconsistent_storage_class)
8893 << FixItHint::CreateRemoval(
8894 D.getDeclSpec().getStorageClassSpecLoc());
8897 Diag(NewFD->getLocation(),
8898 diag::ext_explicit_specialization_storage_class)
8899 << FixItHint::CreateRemoval(
8900 D.getDeclSpec().getStorageClassSpecLoc());
8902 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8903 if (CheckMemberSpecialization(NewFD, Previous))
8904 NewFD->setInvalidDecl();
8907 // Perform semantic checking on the function declaration.
8908 if (!isDependentClassScopeExplicitSpecialization) {
8909 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8910 CheckMain(NewFD, D.getDeclSpec());
8912 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8913 CheckMSVCRTEntryPoint(NewFD);
8915 if (!NewFD->isInvalidDecl())
8916 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8917 isMemberSpecialization));
8918 else if (!Previous.empty())
8919 // Recover gracefully from an invalid redeclaration.
8920 D.setRedeclaration(true);
8923 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8924 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8925 "previous declaration set still overloaded");
8927 NamedDecl *PrincipalDecl = (FunctionTemplate
8928 ? cast<NamedDecl>(FunctionTemplate)
8931 if (isFriend && NewFD->getPreviousDecl()) {
8932 AccessSpecifier Access = AS_public;
8933 if (!NewFD->isInvalidDecl())
8934 Access = NewFD->getPreviousDecl()->getAccess();
8936 NewFD->setAccess(Access);
8937 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8940 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8941 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8942 PrincipalDecl->setNonMemberOperator();
8944 // If we have a function template, check the template parameter
8945 // list. This will check and merge default template arguments.
8946 if (FunctionTemplate) {
8947 FunctionTemplateDecl *PrevTemplate =
8948 FunctionTemplate->getPreviousDecl();
8949 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8950 PrevTemplate ? PrevTemplate->getTemplateParameters()
8952 D.getDeclSpec().isFriendSpecified()
8953 ? (D.isFunctionDefinition()
8954 ? TPC_FriendFunctionTemplateDefinition
8955 : TPC_FriendFunctionTemplate)
8956 : (D.getCXXScopeSpec().isSet() &&
8957 DC && DC->isRecord() &&
8958 DC->isDependentContext())
8959 ? TPC_ClassTemplateMember
8960 : TPC_FunctionTemplate);
8963 if (NewFD->isInvalidDecl()) {
8964 // Ignore all the rest of this.
8965 } else if (!D.isRedeclaration()) {
8966 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8968 // Fake up an access specifier if it's supposed to be a class member.
8969 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8970 NewFD->setAccess(AS_public);
8972 // Qualified decls generally require a previous declaration.
8973 if (D.getCXXScopeSpec().isSet()) {
8974 // ...with the major exception of templated-scope or
8975 // dependent-scope friend declarations.
8977 // TODO: we currently also suppress this check in dependent
8978 // contexts because (1) the parameter depth will be off when
8979 // matching friend templates and (2) we might actually be
8980 // selecting a friend based on a dependent factor. But there
8981 // are situations where these conditions don't apply and we
8982 // can actually do this check immediately.
8984 (TemplateParamLists.size() ||
8985 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8986 CurContext->isDependentContext())) {
8989 // The user tried to provide an out-of-line definition for a
8990 // function that is a member of a class or namespace, but there
8991 // was no such member function declared (C++ [class.mfct]p2,
8992 // C++ [namespace.memdef]p2). For example:
8998 // void X::f() { } // ill-formed
9000 // Complain about this problem, and attempt to suggest close
9001 // matches (e.g., those that differ only in cv-qualifiers and
9002 // whether the parameter types are references).
9004 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9005 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9006 AddToScope = ExtraArgs.AddToScope;
9011 // Unqualified local friend declarations are required to resolve
9013 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9014 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9015 *this, Previous, NewFD, ExtraArgs, true, S)) {
9016 AddToScope = ExtraArgs.AddToScope;
9020 } else if (!D.isFunctionDefinition() &&
9021 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9022 !isFriend && !isFunctionTemplateSpecialization &&
9023 !isMemberSpecialization) {
9024 // An out-of-line member function declaration must also be a
9025 // definition (C++ [class.mfct]p2).
9026 // Note that this is not the case for explicit specializations of
9027 // function templates or member functions of class templates, per
9028 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9029 // extension for compatibility with old SWIG code which likes to
9031 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9032 << D.getCXXScopeSpec().getRange();
9036 ProcessPragmaWeak(S, NewFD);
9037 checkAttributesAfterMerging(*this, *NewFD);
9039 AddKnownFunctionAttributes(NewFD);
9041 if (NewFD->hasAttr<OverloadableAttr>() &&
9042 !NewFD->getType()->getAs<FunctionProtoType>()) {
9043 Diag(NewFD->getLocation(),
9044 diag::err_attribute_overloadable_no_prototype)
9047 // Turn this into a variadic function with no parameters.
9048 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9049 FunctionProtoType::ExtProtoInfo EPI(
9050 Context.getDefaultCallingConvention(true, false));
9051 EPI.Variadic = true;
9052 EPI.ExtInfo = FT->getExtInfo();
9054 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9058 // If there's a #pragma GCC visibility in scope, and this isn't a class
9059 // member, set the visibility of this function.
9060 if (!DC->isRecord() && NewFD->isExternallyVisible())
9061 AddPushedVisibilityAttribute(NewFD);
9063 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9064 // marking the function.
9065 AddCFAuditedAttribute(NewFD);
9067 // If this is a function definition, check if we have to apply optnone due to
9069 if(D.isFunctionDefinition())
9070 AddRangeBasedOptnone(NewFD);
9072 // If this is the first declaration of an extern C variable, update
9073 // the map of such variables.
9074 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9075 isIncompleteDeclExternC(*this, NewFD))
9076 RegisterLocallyScopedExternCDecl(NewFD, S);
9078 // Set this FunctionDecl's range up to the right paren.
9079 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9081 if (D.isRedeclaration() && !Previous.empty()) {
9082 checkDLLAttributeRedeclaration(
9083 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9084 isMemberSpecialization || isFunctionTemplateSpecialization,
9085 D.isFunctionDefinition());
9088 if (getLangOpts().CUDA) {
9089 IdentifierInfo *II = NewFD->getIdentifier();
9090 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9091 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9092 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9093 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9095 Context.setcudaConfigureCallDecl(NewFD);
9098 // Variadic functions, other than a *declaration* of printf, are not allowed
9099 // in device-side CUDA code, unless someone passed
9100 // -fcuda-allow-variadic-functions.
9101 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9102 (NewFD->hasAttr<CUDADeviceAttr>() ||
9103 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9104 !(II && II->isStr("printf") && NewFD->isExternC() &&
9105 !D.isFunctionDefinition())) {
9106 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9110 MarkUnusedFileScopedDecl(NewFD);
9112 if (getLangOpts().CPlusPlus) {
9113 if (FunctionTemplate) {
9114 if (NewFD->isInvalidDecl())
9115 FunctionTemplate->setInvalidDecl();
9116 return FunctionTemplate;
9119 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9120 CompleteMemberSpecialization(NewFD, Previous);
9123 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9124 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9125 if ((getLangOpts().OpenCLVersion >= 120)
9126 && (SC == SC_Static)) {
9127 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9131 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9132 if (!NewFD->getReturnType()->isVoidType()) {
9133 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9134 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9135 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9140 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9141 for (auto Param : NewFD->parameters())
9142 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9144 for (const ParmVarDecl *Param : NewFD->parameters()) {
9145 QualType PT = Param->getType();
9147 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9149 if (getLangOpts().OpenCLVersion >= 200) {
9150 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9151 QualType ElemTy = PipeTy->getElementType();
9152 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9153 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9160 // Here we have an function template explicit specialization at class scope.
9161 // The actually specialization will be postponed to template instatiation
9162 // time via the ClassScopeFunctionSpecializationDecl node.
9163 if (isDependentClassScopeExplicitSpecialization) {
9164 ClassScopeFunctionSpecializationDecl *NewSpec =
9165 ClassScopeFunctionSpecializationDecl::Create(
9166 Context, CurContext, SourceLocation(),
9167 cast<CXXMethodDecl>(NewFD),
9168 HasExplicitTemplateArgs, TemplateArgs);
9169 CurContext->addDecl(NewSpec);
9176 /// \brief Checks if the new declaration declared in dependent context must be
9177 /// put in the same redeclaration chain as the specified declaration.
9179 /// \param D Declaration that is checked.
9180 /// \param PrevDecl Previous declaration found with proper lookup method for the
9181 /// same declaration name.
9182 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9185 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9186 // Any declarations should be put into redeclaration chains except for
9187 // friend declaration in a dependent context that names a function in
9190 // This allows to compile code like:
9193 // template<typename T> class C1 { friend void func() { } };
9194 // template<typename T> class C2 { friend void func() { } };
9196 // This code snippet is a valid code unless both templates are instantiated.
9197 return !(D->getLexicalDeclContext()->isDependentContext() &&
9198 D->getDeclContext()->isFileContext() &&
9199 D->getFriendObjectKind() != Decl::FOK_None);
9202 /// \brief Perform semantic checking of a new function declaration.
9204 /// Performs semantic analysis of the new function declaration
9205 /// NewFD. This routine performs all semantic checking that does not
9206 /// require the actual declarator involved in the declaration, and is
9207 /// used both for the declaration of functions as they are parsed
9208 /// (called via ActOnDeclarator) and for the declaration of functions
9209 /// that have been instantiated via C++ template instantiation (called
9210 /// via InstantiateDecl).
9212 /// \param IsMemberSpecialization whether this new function declaration is
9213 /// a member specialization (that replaces any definition provided by the
9214 /// previous declaration).
9216 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9218 /// \returns true if the function declaration is a redeclaration.
9219 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9220 LookupResult &Previous,
9221 bool IsMemberSpecialization) {
9222 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9223 "Variably modified return types are not handled here");
9225 // Determine whether the type of this function should be merged with
9226 // a previous visible declaration. This never happens for functions in C++,
9227 // and always happens in C if the previous declaration was visible.
9228 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9229 !Previous.isShadowed();
9231 bool Redeclaration = false;
9232 NamedDecl *OldDecl = nullptr;
9233 bool MayNeedOverloadableChecks = false;
9235 // Merge or overload the declaration with an existing declaration of
9236 // the same name, if appropriate.
9237 if (!Previous.empty()) {
9238 // Determine whether NewFD is an overload of PrevDecl or
9239 // a declaration that requires merging. If it's an overload,
9240 // there's no more work to do here; we'll just add the new
9241 // function to the scope.
9242 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9243 NamedDecl *Candidate = Previous.getRepresentativeDecl();
9244 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9245 Redeclaration = true;
9246 OldDecl = Candidate;
9249 MayNeedOverloadableChecks = true;
9250 switch (CheckOverload(S, NewFD, Previous, OldDecl,
9251 /*NewIsUsingDecl*/ false)) {
9253 Redeclaration = true;
9256 case Ovl_NonFunction:
9257 Redeclaration = true;
9261 Redeclaration = false;
9267 // Check for a previous extern "C" declaration with this name.
9268 if (!Redeclaration &&
9269 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9270 if (!Previous.empty()) {
9271 // This is an extern "C" declaration with the same name as a previous
9272 // declaration, and thus redeclares that entity...
9273 Redeclaration = true;
9274 OldDecl = Previous.getFoundDecl();
9275 MergeTypeWithPrevious = false;
9277 // ... except in the presence of __attribute__((overloadable)).
9278 if (OldDecl->hasAttr<OverloadableAttr>() ||
9279 NewFD->hasAttr<OverloadableAttr>()) {
9280 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9281 MayNeedOverloadableChecks = true;
9282 Redeclaration = false;
9289 // C++11 [dcl.constexpr]p8:
9290 // A constexpr specifier for a non-static member function that is not
9291 // a constructor declares that member function to be const.
9293 // This needs to be delayed until we know whether this is an out-of-line
9294 // definition of a static member function.
9296 // This rule is not present in C++1y, so we produce a backwards
9297 // compatibility warning whenever it happens in C++11.
9298 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9299 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9300 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9301 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9302 CXXMethodDecl *OldMD = nullptr;
9304 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9305 if (!OldMD || !OldMD->isStatic()) {
9306 const FunctionProtoType *FPT =
9307 MD->getType()->castAs<FunctionProtoType>();
9308 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9309 EPI.TypeQuals |= Qualifiers::Const;
9310 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9311 FPT->getParamTypes(), EPI));
9313 // Warn that we did this, if we're not performing template instantiation.
9314 // In that case, we'll have warned already when the template was defined.
9315 if (!inTemplateInstantiation()) {
9316 SourceLocation AddConstLoc;
9317 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9318 .IgnoreParens().getAs<FunctionTypeLoc>())
9319 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9321 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9322 << FixItHint::CreateInsertion(AddConstLoc, " const");
9327 if (Redeclaration) {
9328 // NewFD and OldDecl represent declarations that need to be
9330 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9331 NewFD->setInvalidDecl();
9332 return Redeclaration;
9336 Previous.addDecl(OldDecl);
9338 if (FunctionTemplateDecl *OldTemplateDecl
9339 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9340 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9341 FunctionTemplateDecl *NewTemplateDecl
9342 = NewFD->getDescribedFunctionTemplate();
9343 assert(NewTemplateDecl && "Template/non-template mismatch");
9344 if (CXXMethodDecl *Method
9345 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9346 Method->setAccess(OldTemplateDecl->getAccess());
9347 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9350 // If this is an explicit specialization of a member that is a function
9351 // template, mark it as a member specialization.
9352 if (IsMemberSpecialization &&
9353 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9354 NewTemplateDecl->setMemberSpecialization();
9355 assert(OldTemplateDecl->isMemberSpecialization());
9356 // Explicit specializations of a member template do not inherit deleted
9357 // status from the parent member template that they are specializing.
9358 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9359 FunctionDecl *const OldTemplatedDecl =
9360 OldTemplateDecl->getTemplatedDecl();
9361 // FIXME: This assert will not hold in the presence of modules.
9362 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9363 // FIXME: We need an update record for this AST mutation.
9364 OldTemplatedDecl->setDeletedAsWritten(false);
9369 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9370 // This needs to happen first so that 'inline' propagates.
9371 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9372 if (isa<CXXMethodDecl>(NewFD))
9373 NewFD->setAccess(OldDecl->getAccess());
9376 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9377 !NewFD->getAttr<OverloadableAttr>()) {
9378 assert((Previous.empty() ||
9379 llvm::any_of(Previous,
9380 [](const NamedDecl *ND) {
9381 return ND->hasAttr<OverloadableAttr>();
9383 "Non-redecls shouldn't happen without overloadable present");
9385 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9386 const auto *FD = dyn_cast<FunctionDecl>(ND);
9387 return FD && !FD->hasAttr<OverloadableAttr>();
9390 if (OtherUnmarkedIter != Previous.end()) {
9391 Diag(NewFD->getLocation(),
9392 diag::err_attribute_overloadable_multiple_unmarked_overloads);
9393 Diag((*OtherUnmarkedIter)->getLocation(),
9394 diag::note_attribute_overloadable_prev_overload)
9397 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9401 // Semantic checking for this function declaration (in isolation).
9403 if (getLangOpts().CPlusPlus) {
9404 // C++-specific checks.
9405 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9406 CheckConstructor(Constructor);
9407 } else if (CXXDestructorDecl *Destructor =
9408 dyn_cast<CXXDestructorDecl>(NewFD)) {
9409 CXXRecordDecl *Record = Destructor->getParent();
9410 QualType ClassType = Context.getTypeDeclType(Record);
9412 // FIXME: Shouldn't we be able to perform this check even when the class
9413 // type is dependent? Both gcc and edg can handle that.
9414 if (!ClassType->isDependentType()) {
9415 DeclarationName Name
9416 = Context.DeclarationNames.getCXXDestructorName(
9417 Context.getCanonicalType(ClassType));
9418 if (NewFD->getDeclName() != Name) {
9419 Diag(NewFD->getLocation(), diag::err_destructor_name);
9420 NewFD->setInvalidDecl();
9421 return Redeclaration;
9424 } else if (CXXConversionDecl *Conversion
9425 = dyn_cast<CXXConversionDecl>(NewFD)) {
9426 ActOnConversionDeclarator(Conversion);
9427 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9428 if (auto *TD = Guide->getDescribedFunctionTemplate())
9429 CheckDeductionGuideTemplate(TD);
9431 // A deduction guide is not on the list of entities that can be
9432 // explicitly specialized.
9433 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9434 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9435 << /*explicit specialization*/ 1;
9438 // Find any virtual functions that this function overrides.
9439 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9440 if (!Method->isFunctionTemplateSpecialization() &&
9441 !Method->getDescribedFunctionTemplate() &&
9442 Method->isCanonicalDecl()) {
9443 if (AddOverriddenMethods(Method->getParent(), Method)) {
9444 // If the function was marked as "static", we have a problem.
9445 if (NewFD->getStorageClass() == SC_Static) {
9446 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9451 if (Method->isStatic())
9452 checkThisInStaticMemberFunctionType(Method);
9455 // Extra checking for C++ overloaded operators (C++ [over.oper]).
9456 if (NewFD->isOverloadedOperator() &&
9457 CheckOverloadedOperatorDeclaration(NewFD)) {
9458 NewFD->setInvalidDecl();
9459 return Redeclaration;
9462 // Extra checking for C++0x literal operators (C++0x [over.literal]).
9463 if (NewFD->getLiteralIdentifier() &&
9464 CheckLiteralOperatorDeclaration(NewFD)) {
9465 NewFD->setInvalidDecl();
9466 return Redeclaration;
9469 // In C++, check default arguments now that we have merged decls. Unless
9470 // the lexical context is the class, because in this case this is done
9471 // during delayed parsing anyway.
9472 if (!CurContext->isRecord())
9473 CheckCXXDefaultArguments(NewFD);
9475 // If this function declares a builtin function, check the type of this
9476 // declaration against the expected type for the builtin.
9477 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9478 ASTContext::GetBuiltinTypeError Error;
9479 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9480 QualType T = Context.GetBuiltinType(BuiltinID, Error);
9481 // If the type of the builtin differs only in its exception
9482 // specification, that's OK.
9483 // FIXME: If the types do differ in this way, it would be better to
9484 // retain the 'noexcept' form of the type.
9486 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9488 // The type of this function differs from the type of the builtin,
9489 // so forget about the builtin entirely.
9490 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9493 // If this function is declared as being extern "C", then check to see if
9494 // the function returns a UDT (class, struct, or union type) that is not C
9495 // compatible, and if it does, warn the user.
9496 // But, issue any diagnostic on the first declaration only.
9497 if (Previous.empty() && NewFD->isExternC()) {
9498 QualType R = NewFD->getReturnType();
9499 if (R->isIncompleteType() && !R->isVoidType())
9500 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9502 else if (!R.isPODType(Context) && !R->isVoidType() &&
9503 !R->isObjCObjectPointerType())
9504 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9507 // C++1z [dcl.fct]p6:
9508 // [...] whether the function has a non-throwing exception-specification
9509 // [is] part of the function type
9511 // This results in an ABI break between C++14 and C++17 for functions whose
9512 // declared type includes an exception-specification in a parameter or
9513 // return type. (Exception specifications on the function itself are OK in
9514 // most cases, and exception specifications are not permitted in most other
9515 // contexts where they could make it into a mangling.)
9516 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9517 auto HasNoexcept = [&](QualType T) -> bool {
9518 // Strip off declarator chunks that could be between us and a function
9519 // type. We don't need to look far, exception specifications are very
9520 // restricted prior to C++17.
9521 if (auto *RT = T->getAs<ReferenceType>())
9522 T = RT->getPointeeType();
9523 else if (T->isAnyPointerType())
9524 T = T->getPointeeType();
9525 else if (auto *MPT = T->getAs<MemberPointerType>())
9526 T = MPT->getPointeeType();
9527 if (auto *FPT = T->getAs<FunctionProtoType>())
9528 if (FPT->isNothrow(Context))
9533 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9534 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9535 for (QualType T : FPT->param_types())
9536 AnyNoexcept |= HasNoexcept(T);
9538 Diag(NewFD->getLocation(),
9539 diag::warn_cxx1z_compat_exception_spec_in_signature)
9543 if (!Redeclaration && LangOpts.CUDA)
9544 checkCUDATargetOverload(NewFD, Previous);
9546 return Redeclaration;
9549 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9550 // C++11 [basic.start.main]p3:
9551 // A program that [...] declares main to be inline, static or
9552 // constexpr is ill-formed.
9553 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
9554 // appear in a declaration of main.
9555 // static main is not an error under C99, but we should warn about it.
9556 // We accept _Noreturn main as an extension.
9557 if (FD->getStorageClass() == SC_Static)
9558 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9559 ? diag::err_static_main : diag::warn_static_main)
9560 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9561 if (FD->isInlineSpecified())
9562 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9563 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9564 if (DS.isNoreturnSpecified()) {
9565 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9566 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9567 Diag(NoreturnLoc, diag::ext_noreturn_main);
9568 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9569 << FixItHint::CreateRemoval(NoreturnRange);
9571 if (FD->isConstexpr()) {
9572 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9573 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9574 FD->setConstexpr(false);
9577 if (getLangOpts().OpenCL) {
9578 Diag(FD->getLocation(), diag::err_opencl_no_main)
9579 << FD->hasAttr<OpenCLKernelAttr>();
9580 FD->setInvalidDecl();
9584 QualType T = FD->getType();
9585 assert(T->isFunctionType() && "function decl is not of function type");
9586 const FunctionType* FT = T->castAs<FunctionType>();
9588 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9589 // In C with GNU extensions we allow main() to have non-integer return
9590 // type, but we should warn about the extension, and we disable the
9591 // implicit-return-zero rule.
9593 // GCC in C mode accepts qualified 'int'.
9594 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9595 FD->setHasImplicitReturnZero(true);
9597 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9598 SourceRange RTRange = FD->getReturnTypeSourceRange();
9599 if (RTRange.isValid())
9600 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9601 << FixItHint::CreateReplacement(RTRange, "int");
9604 // In C and C++, main magically returns 0 if you fall off the end;
9605 // set the flag which tells us that.
9606 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9608 // All the standards say that main() should return 'int'.
9609 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9610 FD->setHasImplicitReturnZero(true);
9612 // Otherwise, this is just a flat-out error.
9613 SourceRange RTRange = FD->getReturnTypeSourceRange();
9614 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9615 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9617 FD->setInvalidDecl(true);
9621 // Treat protoless main() as nullary.
9622 if (isa<FunctionNoProtoType>(FT)) return;
9624 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9625 unsigned nparams = FTP->getNumParams();
9626 assert(FD->getNumParams() == nparams);
9628 bool HasExtraParameters = (nparams > 3);
9630 if (FTP->isVariadic()) {
9631 Diag(FD->getLocation(), diag::ext_variadic_main);
9632 // FIXME: if we had information about the location of the ellipsis, we
9633 // could add a FixIt hint to remove it as a parameter.
9636 // Darwin passes an undocumented fourth argument of type char**. If
9637 // other platforms start sprouting these, the logic below will start
9639 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9640 HasExtraParameters = false;
9642 if (HasExtraParameters) {
9643 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9644 FD->setInvalidDecl(true);
9648 // FIXME: a lot of the following diagnostics would be improved
9649 // if we had some location information about types.
9652 Context.getPointerType(Context.getPointerType(Context.CharTy));
9653 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9655 for (unsigned i = 0; i < nparams; ++i) {
9656 QualType AT = FTP->getParamType(i);
9658 bool mismatch = true;
9660 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9662 else if (Expected[i] == CharPP) {
9663 // As an extension, the following forms are okay:
9665 // char const * const *
9668 QualifierCollector qs;
9669 const PointerType* PT;
9670 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9671 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9672 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9675 mismatch = !qs.empty();
9680 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9681 // TODO: suggest replacing given type with expected type
9682 FD->setInvalidDecl(true);
9686 if (nparams == 1 && !FD->isInvalidDecl()) {
9687 Diag(FD->getLocation(), diag::warn_main_one_arg);
9690 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9691 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9692 FD->setInvalidDecl();
9696 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9697 QualType T = FD->getType();
9698 assert(T->isFunctionType() && "function decl is not of function type");
9699 const FunctionType *FT = T->castAs<FunctionType>();
9701 // Set an implicit return of 'zero' if the function can return some integral,
9702 // enumeration, pointer or nullptr type.
9703 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9704 FT->getReturnType()->isAnyPointerType() ||
9705 FT->getReturnType()->isNullPtrType())
9706 // DllMain is exempt because a return value of zero means it failed.
9707 if (FD->getName() != "DllMain")
9708 FD->setHasImplicitReturnZero(true);
9710 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9711 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9712 FD->setInvalidDecl();
9716 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9717 // FIXME: Need strict checking. In C89, we need to check for
9718 // any assignment, increment, decrement, function-calls, or
9719 // commas outside of a sizeof. In C99, it's the same list,
9720 // except that the aforementioned are allowed in unevaluated
9721 // expressions. Everything else falls under the
9722 // "may accept other forms of constant expressions" exception.
9723 // (We never end up here for C++, so the constant expression
9724 // rules there don't matter.)
9725 const Expr *Culprit;
9726 if (Init->isConstantInitializer(Context, false, &Culprit))
9728 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9729 << Culprit->getSourceRange();
9734 // Visits an initialization expression to see if OrigDecl is evaluated in
9735 // its own initialization and throws a warning if it does.
9736 class SelfReferenceChecker
9737 : public EvaluatedExprVisitor<SelfReferenceChecker> {
9742 bool isReferenceType;
9745 llvm::SmallVector<unsigned, 4> InitFieldIndex;
9748 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9750 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9751 S(S), OrigDecl(OrigDecl) {
9753 isRecordType = false;
9754 isReferenceType = false;
9756 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9757 isPODType = VD->getType().isPODType(S.Context);
9758 isRecordType = VD->getType()->isRecordType();
9759 isReferenceType = VD->getType()->isReferenceType();
9763 // For most expressions, just call the visitor. For initializer lists,
9764 // track the index of the field being initialized since fields are
9765 // initialized in order allowing use of previously initialized fields.
9766 void CheckExpr(Expr *E) {
9767 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9773 // Track and increment the index here.
9775 InitFieldIndex.push_back(0);
9776 for (auto Child : InitList->children()) {
9777 CheckExpr(cast<Expr>(Child));
9778 ++InitFieldIndex.back();
9780 InitFieldIndex.pop_back();
9783 // Returns true if MemberExpr is checked and no further checking is needed.
9784 // Returns false if additional checking is required.
9785 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9786 llvm::SmallVector<FieldDecl*, 4> Fields;
9788 bool ReferenceField = false;
9790 // Get the field memebers used.
9791 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9792 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9795 Fields.push_back(FD);
9796 if (FD->getType()->isReferenceType())
9797 ReferenceField = true;
9798 Base = ME->getBase()->IgnoreParenImpCasts();
9801 // Keep checking only if the base Decl is the same.
9802 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9803 if (!DRE || DRE->getDecl() != OrigDecl)
9806 // A reference field can be bound to an unininitialized field.
9807 if (CheckReference && !ReferenceField)
9810 // Convert FieldDecls to their index number.
9811 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9812 for (const FieldDecl *I : llvm::reverse(Fields))
9813 UsedFieldIndex.push_back(I->getFieldIndex());
9815 // See if a warning is needed by checking the first difference in index
9816 // numbers. If field being used has index less than the field being
9817 // initialized, then the use is safe.
9818 for (auto UsedIter = UsedFieldIndex.begin(),
9819 UsedEnd = UsedFieldIndex.end(),
9820 OrigIter = InitFieldIndex.begin(),
9821 OrigEnd = InitFieldIndex.end();
9822 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9823 if (*UsedIter < *OrigIter)
9825 if (*UsedIter > *OrigIter)
9829 // TODO: Add a different warning which will print the field names.
9830 HandleDeclRefExpr(DRE);
9834 // For most expressions, the cast is directly above the DeclRefExpr.
9835 // For conditional operators, the cast can be outside the conditional
9836 // operator if both expressions are DeclRefExpr's.
9837 void HandleValue(Expr *E) {
9838 E = E->IgnoreParens();
9839 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9840 HandleDeclRefExpr(DRE);
9844 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9845 Visit(CO->getCond());
9846 HandleValue(CO->getTrueExpr());
9847 HandleValue(CO->getFalseExpr());
9851 if (BinaryConditionalOperator *BCO =
9852 dyn_cast<BinaryConditionalOperator>(E)) {
9853 Visit(BCO->getCond());
9854 HandleValue(BCO->getFalseExpr());
9858 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9859 HandleValue(OVE->getSourceExpr());
9863 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9864 if (BO->getOpcode() == BO_Comma) {
9865 Visit(BO->getLHS());
9866 HandleValue(BO->getRHS());
9871 if (isa<MemberExpr>(E)) {
9873 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9874 false /*CheckReference*/))
9878 Expr *Base = E->IgnoreParenImpCasts();
9879 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9880 // Check for static member variables and don't warn on them.
9881 if (!isa<FieldDecl>(ME->getMemberDecl()))
9883 Base = ME->getBase()->IgnoreParenImpCasts();
9885 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9886 HandleDeclRefExpr(DRE);
9893 // Reference types not handled in HandleValue are handled here since all
9894 // uses of references are bad, not just r-value uses.
9895 void VisitDeclRefExpr(DeclRefExpr *E) {
9896 if (isReferenceType)
9897 HandleDeclRefExpr(E);
9900 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9901 if (E->getCastKind() == CK_LValueToRValue) {
9902 HandleValue(E->getSubExpr());
9906 Inherited::VisitImplicitCastExpr(E);
9909 void VisitMemberExpr(MemberExpr *E) {
9911 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9915 // Don't warn on arrays since they can be treated as pointers.
9916 if (E->getType()->canDecayToPointerType()) return;
9918 // Warn when a non-static method call is followed by non-static member
9919 // field accesses, which is followed by a DeclRefExpr.
9920 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9921 bool Warn = (MD && !MD->isStatic());
9922 Expr *Base = E->getBase()->IgnoreParenImpCasts();
9923 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9924 if (!isa<FieldDecl>(ME->getMemberDecl()))
9926 Base = ME->getBase()->IgnoreParenImpCasts();
9929 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9931 HandleDeclRefExpr(DRE);
9935 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9936 // Visit that expression.
9940 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9941 Expr *Callee = E->getCallee();
9943 if (isa<UnresolvedLookupExpr>(Callee))
9944 return Inherited::VisitCXXOperatorCallExpr(E);
9947 for (auto Arg: E->arguments())
9948 HandleValue(Arg->IgnoreParenImpCasts());
9951 void VisitUnaryOperator(UnaryOperator *E) {
9952 // For POD record types, addresses of its own members are well-defined.
9953 if (E->getOpcode() == UO_AddrOf && isRecordType &&
9954 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9956 HandleValue(E->getSubExpr());
9960 if (E->isIncrementDecrementOp()) {
9961 HandleValue(E->getSubExpr());
9965 Inherited::VisitUnaryOperator(E);
9968 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9970 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9971 if (E->getConstructor()->isCopyConstructor()) {
9972 Expr *ArgExpr = E->getArg(0);
9973 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9974 if (ILE->getNumInits() == 1)
9975 ArgExpr = ILE->getInit(0);
9976 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9977 if (ICE->getCastKind() == CK_NoOp)
9978 ArgExpr = ICE->getSubExpr();
9979 HandleValue(ArgExpr);
9982 Inherited::VisitCXXConstructExpr(E);
9985 void VisitCallExpr(CallExpr *E) {
9986 // Treat std::move as a use.
9987 if (E->getNumArgs() == 1) {
9988 if (FunctionDecl *FD = E->getDirectCallee()) {
9989 if (FD->isInStdNamespace() && FD->getIdentifier() &&
9990 FD->getIdentifier()->isStr("move")) {
9991 HandleValue(E->getArg(0));
9997 Inherited::VisitCallExpr(E);
10000 void VisitBinaryOperator(BinaryOperator *E) {
10001 if (E->isCompoundAssignmentOp()) {
10002 HandleValue(E->getLHS());
10003 Visit(E->getRHS());
10007 Inherited::VisitBinaryOperator(E);
10010 // A custom visitor for BinaryConditionalOperator is needed because the
10011 // regular visitor would check the condition and true expression separately
10012 // but both point to the same place giving duplicate diagnostics.
10013 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10014 Visit(E->getCond());
10015 Visit(E->getFalseExpr());
10018 void HandleDeclRefExpr(DeclRefExpr *DRE) {
10019 Decl* ReferenceDecl = DRE->getDecl();
10020 if (OrigDecl != ReferenceDecl) return;
10022 if (isReferenceType) {
10023 diag = diag::warn_uninit_self_reference_in_reference_init;
10024 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10025 diag = diag::warn_static_self_reference_in_init;
10026 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10027 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10028 DRE->getDecl()->getType()->isRecordType()) {
10029 diag = diag::warn_uninit_self_reference_in_init;
10031 // Local variables will be handled by the CFG analysis.
10035 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10037 << DRE->getNameInfo().getName()
10038 << OrigDecl->getLocation()
10039 << DRE->getSourceRange());
10043 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10044 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10046 // Parameters arguments are occassionially constructed with itself,
10047 // for instance, in recursive functions. Skip them.
10048 if (isa<ParmVarDecl>(OrigDecl))
10051 E = E->IgnoreParens();
10053 // Skip checking T a = a where T is not a record or reference type.
10054 // Doing so is a way to silence uninitialized warnings.
10055 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10056 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10057 if (ICE->getCastKind() == CK_LValueToRValue)
10058 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10059 if (DRE->getDecl() == OrigDecl)
10062 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10064 } // end anonymous namespace
10067 // Simple wrapper to add the name of a variable or (if no variable is
10068 // available) a DeclarationName into a diagnostic.
10069 struct VarDeclOrName {
10071 DeclarationName Name;
10073 friend const Sema::SemaDiagnosticBuilder &
10074 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10075 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10078 } // end anonymous namespace
10080 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10081 DeclarationName Name, QualType Type,
10082 TypeSourceInfo *TSI,
10083 SourceRange Range, bool DirectInit,
10085 bool IsInitCapture = !VDecl;
10086 assert((!VDecl || !VDecl->isInitCapture()) &&
10087 "init captures are expected to be deduced prior to initialization");
10089 VarDeclOrName VN{VDecl, Name};
10091 DeducedType *Deduced = Type->getContainedDeducedType();
10092 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10094 // C++11 [dcl.spec.auto]p3
10096 assert(VDecl && "no init for init capture deduction?");
10097 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10098 << VDecl->getDeclName() << Type;
10102 ArrayRef<Expr*> DeduceInits = Init;
10104 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10105 DeduceInits = PL->exprs();
10108 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10109 assert(VDecl && "non-auto type for init capture deduction?");
10110 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10111 InitializationKind Kind = InitializationKind::CreateForInit(
10112 VDecl->getLocation(), DirectInit, Init);
10113 // FIXME: Initialization should not be taking a mutable list of inits.
10114 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10115 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10120 if (auto *IL = dyn_cast<InitListExpr>(Init))
10121 DeduceInits = IL->inits();
10124 // Deduction only works if we have exactly one source expression.
10125 if (DeduceInits.empty()) {
10126 // It isn't possible to write this directly, but it is possible to
10127 // end up in this situation with "auto x(some_pack...);"
10128 Diag(Init->getLocStart(), IsInitCapture
10129 ? diag::err_init_capture_no_expression
10130 : diag::err_auto_var_init_no_expression)
10131 << VN << Type << Range;
10135 if (DeduceInits.size() > 1) {
10136 Diag(DeduceInits[1]->getLocStart(),
10137 IsInitCapture ? diag::err_init_capture_multiple_expressions
10138 : diag::err_auto_var_init_multiple_expressions)
10139 << VN << Type << Range;
10143 Expr *DeduceInit = DeduceInits[0];
10144 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10145 Diag(Init->getLocStart(), IsInitCapture
10146 ? diag::err_init_capture_paren_braces
10147 : diag::err_auto_var_init_paren_braces)
10148 << isa<InitListExpr>(Init) << VN << Type << Range;
10152 // Expressions default to 'id' when we're in a debugger.
10153 bool DefaultedAnyToId = false;
10154 if (getLangOpts().DebuggerCastResultToId &&
10155 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10156 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10157 if (Result.isInvalid()) {
10160 Init = Result.get();
10161 DefaultedAnyToId = true;
10164 // C++ [dcl.decomp]p1:
10165 // If the assignment-expression [...] has array type A and no ref-qualifier
10166 // is present, e has type cv A
10167 if (VDecl && isa<DecompositionDecl>(VDecl) &&
10168 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10169 DeduceInit->getType()->isConstantArrayType())
10170 return Context.getQualifiedType(DeduceInit->getType(),
10171 Type.getQualifiers());
10173 QualType DeducedType;
10174 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10175 if (!IsInitCapture)
10176 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10177 else if (isa<InitListExpr>(Init))
10178 Diag(Range.getBegin(),
10179 diag::err_init_capture_deduction_failure_from_init_list)
10181 << (DeduceInit->getType().isNull() ? TSI->getType()
10182 : DeduceInit->getType())
10183 << DeduceInit->getSourceRange();
10185 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10186 << VN << TSI->getType()
10187 << (DeduceInit->getType().isNull() ? TSI->getType()
10188 : DeduceInit->getType())
10189 << DeduceInit->getSourceRange();
10192 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10193 // 'id' instead of a specific object type prevents most of our usual
10195 // We only want to warn outside of template instantiations, though:
10196 // inside a template, the 'id' could have come from a parameter.
10197 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10198 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10199 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10200 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10203 return DeducedType;
10206 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10208 QualType DeducedType = deduceVarTypeFromInitializer(
10209 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10210 VDecl->getSourceRange(), DirectInit, Init);
10211 if (DeducedType.isNull()) {
10212 VDecl->setInvalidDecl();
10216 VDecl->setType(DeducedType);
10217 assert(VDecl->isLinkageValid());
10219 // In ARC, infer lifetime.
10220 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10221 VDecl->setInvalidDecl();
10223 // If this is a redeclaration, check that the type we just deduced matches
10224 // the previously declared type.
10225 if (VarDecl *Old = VDecl->getPreviousDecl()) {
10226 // We never need to merge the type, because we cannot form an incomplete
10227 // array of auto, nor deduce such a type.
10228 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10231 // Check the deduced type is valid for a variable declaration.
10232 CheckVariableDeclarationType(VDecl);
10233 return VDecl->isInvalidDecl();
10236 /// AddInitializerToDecl - Adds the initializer Init to the
10237 /// declaration dcl. If DirectInit is true, this is C++ direct
10238 /// initialization rather than copy initialization.
10239 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10240 // If there is no declaration, there was an error parsing it. Just ignore
10241 // the initializer.
10242 if (!RealDecl || RealDecl->isInvalidDecl()) {
10243 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10247 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10248 // Pure-specifiers are handled in ActOnPureSpecifier.
10249 Diag(Method->getLocation(), diag::err_member_function_initialization)
10250 << Method->getDeclName() << Init->getSourceRange();
10251 Method->setInvalidDecl();
10255 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10257 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10258 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10259 RealDecl->setInvalidDecl();
10263 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10264 if (VDecl->getType()->isUndeducedType()) {
10265 // Attempt typo correction early so that the type of the init expression can
10266 // be deduced based on the chosen correction if the original init contains a
10268 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10269 if (!Res.isUsable()) {
10270 RealDecl->setInvalidDecl();
10275 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10279 // dllimport cannot be used on variable definitions.
10280 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10281 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10282 VDecl->setInvalidDecl();
10286 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10287 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10288 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10289 VDecl->setInvalidDecl();
10293 if (!VDecl->getType()->isDependentType()) {
10294 // A definition must end up with a complete type, which means it must be
10295 // complete with the restriction that an array type might be completed by
10296 // the initializer; note that later code assumes this restriction.
10297 QualType BaseDeclType = VDecl->getType();
10298 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10299 BaseDeclType = Array->getElementType();
10300 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10301 diag::err_typecheck_decl_incomplete_type)) {
10302 RealDecl->setInvalidDecl();
10306 // The variable can not have an abstract class type.
10307 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10308 diag::err_abstract_type_in_decl,
10309 AbstractVariableType))
10310 VDecl->setInvalidDecl();
10313 // If adding the initializer will turn this declaration into a definition,
10314 // and we already have a definition for this variable, diagnose or otherwise
10315 // handle the situation.
10317 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10318 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10319 !VDecl->isThisDeclarationADemotedDefinition() &&
10320 checkVarDeclRedefinition(Def, VDecl))
10323 if (getLangOpts().CPlusPlus) {
10324 // C++ [class.static.data]p4
10325 // If a static data member is of const integral or const
10326 // enumeration type, its declaration in the class definition can
10327 // specify a constant-initializer which shall be an integral
10328 // constant expression (5.19). In that case, the member can appear
10329 // in integral constant expressions. The member shall still be
10330 // defined in a namespace scope if it is used in the program and the
10331 // namespace scope definition shall not contain an initializer.
10333 // We already performed a redefinition check above, but for static
10334 // data members we also need to check whether there was an in-class
10335 // declaration with an initializer.
10336 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10337 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10338 << VDecl->getDeclName();
10339 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10340 diag::note_previous_initializer)
10345 if (VDecl->hasLocalStorage())
10346 getCurFunction()->setHasBranchProtectedScope();
10348 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10349 VDecl->setInvalidDecl();
10354 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10355 // a kernel function cannot be initialized."
10356 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10357 Diag(VDecl->getLocation(), diag::err_local_cant_init);
10358 VDecl->setInvalidDecl();
10362 // Get the decls type and save a reference for later, since
10363 // CheckInitializerTypes may change it.
10364 QualType DclT = VDecl->getType(), SavT = DclT;
10366 // Expressions default to 'id' when we're in a debugger
10367 // and we are assigning it to a variable of Objective-C pointer type.
10368 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10369 Init->getType() == Context.UnknownAnyTy) {
10370 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10371 if (Result.isInvalid()) {
10372 VDecl->setInvalidDecl();
10375 Init = Result.get();
10378 // Perform the initialization.
10379 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10380 if (!VDecl->isInvalidDecl()) {
10381 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10382 InitializationKind Kind = InitializationKind::CreateForInit(
10383 VDecl->getLocation(), DirectInit, Init);
10385 MultiExprArg Args = Init;
10387 Args = MultiExprArg(CXXDirectInit->getExprs(),
10388 CXXDirectInit->getNumExprs());
10390 // Try to correct any TypoExprs in the initialization arguments.
10391 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10392 ExprResult Res = CorrectDelayedTyposInExpr(
10393 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10394 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10395 return Init.Failed() ? ExprError() : E;
10397 if (Res.isInvalid()) {
10398 VDecl->setInvalidDecl();
10399 } else if (Res.get() != Args[Idx]) {
10400 Args[Idx] = Res.get();
10403 if (VDecl->isInvalidDecl())
10406 InitializationSequence InitSeq(*this, Entity, Kind, Args,
10407 /*TopLevelOfInitList=*/false,
10408 /*TreatUnavailableAsInvalid=*/false);
10409 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10410 if (Result.isInvalid()) {
10411 VDecl->setInvalidDecl();
10415 Init = Result.getAs<Expr>();
10418 // Check for self-references within variable initializers.
10419 // Variables declared within a function/method body (except for references)
10420 // are handled by a dataflow analysis.
10421 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10422 VDecl->getType()->isReferenceType()) {
10423 CheckSelfReference(*this, RealDecl, Init, DirectInit);
10426 // If the type changed, it means we had an incomplete type that was
10427 // completed by the initializer. For example:
10428 // int ary[] = { 1, 3, 5 };
10429 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10430 if (!VDecl->isInvalidDecl() && (DclT != SavT))
10431 VDecl->setType(DclT);
10433 if (!VDecl->isInvalidDecl()) {
10434 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10436 if (VDecl->hasAttr<BlocksAttr>())
10437 checkRetainCycles(VDecl, Init);
10439 // It is safe to assign a weak reference into a strong variable.
10440 // Although this code can still have problems:
10441 // id x = self.weakProp;
10442 // id y = self.weakProp;
10443 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10444 // paths through the function. This should be revisited if
10445 // -Wrepeated-use-of-weak is made flow-sensitive.
10446 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10447 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10448 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10449 Init->getLocStart()))
10450 getCurFunction()->markSafeWeakUse(Init);
10453 // The initialization is usually a full-expression.
10455 // FIXME: If this is a braced initialization of an aggregate, it is not
10456 // an expression, and each individual field initializer is a separate
10457 // full-expression. For instance, in:
10459 // struct Temp { ~Temp(); };
10460 // struct S { S(Temp); };
10461 // struct T { S a, b; } t = { Temp(), Temp() }
10463 // we should destroy the first Temp before constructing the second.
10464 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10466 VDecl->isConstexpr());
10467 if (Result.isInvalid()) {
10468 VDecl->setInvalidDecl();
10471 Init = Result.get();
10473 // Attach the initializer to the decl.
10474 VDecl->setInit(Init);
10476 if (VDecl->isLocalVarDecl()) {
10477 // Don't check the initializer if the declaration is malformed.
10478 if (VDecl->isInvalidDecl()) {
10481 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10482 // This is true even in OpenCL C++.
10483 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10484 CheckForConstantInitializer(Init, DclT);
10486 // Otherwise, C++ does not restrict the initializer.
10487 } else if (getLangOpts().CPlusPlus) {
10490 // C99 6.7.8p4: All the expressions in an initializer for an object that has
10491 // static storage duration shall be constant expressions or string literals.
10492 } else if (VDecl->getStorageClass() == SC_Static) {
10493 CheckForConstantInitializer(Init, DclT);
10495 // C89 is stricter than C99 for aggregate initializers.
10496 // C89 6.5.7p3: All the expressions [...] in an initializer list
10497 // for an object that has aggregate or union type shall be
10498 // constant expressions.
10499 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10500 isa<InitListExpr>(Init)) {
10501 const Expr *Culprit;
10502 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10503 Diag(Culprit->getExprLoc(),
10504 diag::ext_aggregate_init_not_constant)
10505 << Culprit->getSourceRange();
10508 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10509 VDecl->getLexicalDeclContext()->isRecord()) {
10510 // This is an in-class initialization for a static data member, e.g.,
10513 // static const int value = 17;
10516 // C++ [class.mem]p4:
10517 // A member-declarator can contain a constant-initializer only
10518 // if it declares a static member (9.4) of const integral or
10519 // const enumeration type, see 9.4.2.
10521 // C++11 [class.static.data]p3:
10522 // If a non-volatile non-inline const static data member is of integral
10523 // or enumeration type, its declaration in the class definition can
10524 // specify a brace-or-equal-initializer in which every initializer-clause
10525 // that is an assignment-expression is a constant expression. A static
10526 // data member of literal type can be declared in the class definition
10527 // with the constexpr specifier; if so, its declaration shall specify a
10528 // brace-or-equal-initializer in which every initializer-clause that is
10529 // an assignment-expression is a constant expression.
10531 // Do nothing on dependent types.
10532 if (DclT->isDependentType()) {
10534 // Allow any 'static constexpr' members, whether or not they are of literal
10535 // type. We separately check that every constexpr variable is of literal
10537 } else if (VDecl->isConstexpr()) {
10539 // Require constness.
10540 } else if (!DclT.isConstQualified()) {
10541 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10542 << Init->getSourceRange();
10543 VDecl->setInvalidDecl();
10545 // We allow integer constant expressions in all cases.
10546 } else if (DclT->isIntegralOrEnumerationType()) {
10547 // Check whether the expression is a constant expression.
10548 SourceLocation Loc;
10549 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10550 // In C++11, a non-constexpr const static data member with an
10551 // in-class initializer cannot be volatile.
10552 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10553 else if (Init->isValueDependent())
10554 ; // Nothing to check.
10555 else if (Init->isIntegerConstantExpr(Context, &Loc))
10556 ; // Ok, it's an ICE!
10557 else if (Init->isEvaluatable(Context)) {
10558 // If we can constant fold the initializer through heroics, accept it,
10559 // but report this as a use of an extension for -pedantic.
10560 Diag(Loc, diag::ext_in_class_initializer_non_constant)
10561 << Init->getSourceRange();
10563 // Otherwise, this is some crazy unknown case. Report the issue at the
10564 // location provided by the isIntegerConstantExpr failed check.
10565 Diag(Loc, diag::err_in_class_initializer_non_constant)
10566 << Init->getSourceRange();
10567 VDecl->setInvalidDecl();
10570 // We allow foldable floating-point constants as an extension.
10571 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10572 // In C++98, this is a GNU extension. In C++11, it is not, but we support
10573 // it anyway and provide a fixit to add the 'constexpr'.
10574 if (getLangOpts().CPlusPlus11) {
10575 Diag(VDecl->getLocation(),
10576 diag::ext_in_class_initializer_float_type_cxx11)
10577 << DclT << Init->getSourceRange();
10578 Diag(VDecl->getLocStart(),
10579 diag::note_in_class_initializer_float_type_cxx11)
10580 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10582 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10583 << DclT << Init->getSourceRange();
10585 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10586 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10587 << Init->getSourceRange();
10588 VDecl->setInvalidDecl();
10592 // Suggest adding 'constexpr' in C++11 for literal types.
10593 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10594 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10595 << DclT << Init->getSourceRange()
10596 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10597 VDecl->setConstexpr(true);
10600 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10601 << DclT << Init->getSourceRange();
10602 VDecl->setInvalidDecl();
10604 } else if (VDecl->isFileVarDecl()) {
10605 // In C, extern is typically used to avoid tentative definitions when
10606 // declaring variables in headers, but adding an intializer makes it a
10607 // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10608 // In C++, extern is often used to give implictly static const variables
10609 // external linkage, so don't warn in that case. If selectany is present,
10610 // this might be header code intended for C and C++ inclusion, so apply the
10612 if (VDecl->getStorageClass() == SC_Extern &&
10613 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10614 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10615 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10616 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10617 Diag(VDecl->getLocation(), diag::warn_extern_init);
10619 // C99 6.7.8p4. All file scoped initializers need to be constant.
10620 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10621 CheckForConstantInitializer(Init, DclT);
10624 // We will represent direct-initialization similarly to copy-initialization:
10625 // int x(1); -as-> int x = 1;
10626 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10628 // Clients that want to distinguish between the two forms, can check for
10629 // direct initializer using VarDecl::getInitStyle().
10630 // A major benefit is that clients that don't particularly care about which
10631 // exactly form was it (like the CodeGen) can handle both cases without
10632 // special case code.
10635 // The form of initialization (using parentheses or '=') is generally
10636 // insignificant, but does matter when the entity being initialized has a
10638 if (CXXDirectInit) {
10639 assert(DirectInit && "Call-style initializer must be direct init.");
10640 VDecl->setInitStyle(VarDecl::CallInit);
10641 } else if (DirectInit) {
10642 // This must be list-initialization. No other way is direct-initialization.
10643 VDecl->setInitStyle(VarDecl::ListInit);
10646 CheckCompleteVariableDeclaration(VDecl);
10649 /// ActOnInitializerError - Given that there was an error parsing an
10650 /// initializer for the given declaration, try to return to some form
10652 void Sema::ActOnInitializerError(Decl *D) {
10653 // Our main concern here is re-establishing invariants like "a
10654 // variable's type is either dependent or complete".
10655 if (!D || D->isInvalidDecl()) return;
10657 VarDecl *VD = dyn_cast<VarDecl>(D);
10660 // Bindings are not usable if we can't make sense of the initializer.
10661 if (auto *DD = dyn_cast<DecompositionDecl>(D))
10662 for (auto *BD : DD->bindings())
10663 BD->setInvalidDecl();
10665 // Auto types are meaningless if we can't make sense of the initializer.
10666 if (ParsingInitForAutoVars.count(D)) {
10667 D->setInvalidDecl();
10671 QualType Ty = VD->getType();
10672 if (Ty->isDependentType()) return;
10674 // Require a complete type.
10675 if (RequireCompleteType(VD->getLocation(),
10676 Context.getBaseElementType(Ty),
10677 diag::err_typecheck_decl_incomplete_type)) {
10678 VD->setInvalidDecl();
10682 // Require a non-abstract type.
10683 if (RequireNonAbstractType(VD->getLocation(), Ty,
10684 diag::err_abstract_type_in_decl,
10685 AbstractVariableType)) {
10686 VD->setInvalidDecl();
10690 // Don't bother complaining about constructors or destructors,
10694 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10695 // If there is no declaration, there was an error parsing it. Just ignore it.
10699 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10700 QualType Type = Var->getType();
10702 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10703 if (isa<DecompositionDecl>(RealDecl)) {
10704 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10705 Var->setInvalidDecl();
10709 if (Type->isUndeducedType() &&
10710 DeduceVariableDeclarationType(Var, false, nullptr))
10713 // C++11 [class.static.data]p3: A static data member can be declared with
10714 // the constexpr specifier; if so, its declaration shall specify
10715 // a brace-or-equal-initializer.
10716 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10717 // the definition of a variable [...] or the declaration of a static data
10719 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10720 !Var->isThisDeclarationADemotedDefinition()) {
10721 if (Var->isStaticDataMember()) {
10722 // C++1z removes the relevant rule; the in-class declaration is always
10723 // a definition there.
10724 if (!getLangOpts().CPlusPlus1z) {
10725 Diag(Var->getLocation(),
10726 diag::err_constexpr_static_mem_var_requires_init)
10727 << Var->getDeclName();
10728 Var->setInvalidDecl();
10732 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10733 Var->setInvalidDecl();
10738 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
10739 // definition having the concept specifier is called a variable concept. A
10740 // concept definition refers to [...] a variable concept and its initializer.
10741 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10742 if (VTD->isConcept()) {
10743 Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10744 Var->setInvalidDecl();
10749 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10751 if (!Var->isInvalidDecl() &&
10752 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10753 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10754 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10755 Var->setInvalidDecl();
10759 switch (Var->isThisDeclarationADefinition()) {
10760 case VarDecl::Definition:
10761 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10764 // We have an out-of-line definition of a static data member
10765 // that has an in-class initializer, so we type-check this like
10770 case VarDecl::DeclarationOnly:
10771 // It's only a declaration.
10773 // Block scope. C99 6.7p7: If an identifier for an object is
10774 // declared with no linkage (C99 6.2.2p6), the type for the
10775 // object shall be complete.
10776 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10777 !Var->hasLinkage() && !Var->isInvalidDecl() &&
10778 RequireCompleteType(Var->getLocation(), Type,
10779 diag::err_typecheck_decl_incomplete_type))
10780 Var->setInvalidDecl();
10782 // Make sure that the type is not abstract.
10783 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10784 RequireNonAbstractType(Var->getLocation(), Type,
10785 diag::err_abstract_type_in_decl,
10786 AbstractVariableType))
10787 Var->setInvalidDecl();
10788 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10789 Var->getStorageClass() == SC_PrivateExtern) {
10790 Diag(Var->getLocation(), diag::warn_private_extern);
10791 Diag(Var->getLocation(), diag::note_private_extern);
10796 case VarDecl::TentativeDefinition:
10797 // File scope. C99 6.9.2p2: A declaration of an identifier for an
10798 // object that has file scope without an initializer, and without a
10799 // storage-class specifier or with the storage-class specifier "static",
10800 // constitutes a tentative definition. Note: A tentative definition with
10801 // external linkage is valid (C99 6.2.2p5).
10802 if (!Var->isInvalidDecl()) {
10803 if (const IncompleteArrayType *ArrayT
10804 = Context.getAsIncompleteArrayType(Type)) {
10805 if (RequireCompleteType(Var->getLocation(),
10806 ArrayT->getElementType(),
10807 diag::err_illegal_decl_array_incomplete_type))
10808 Var->setInvalidDecl();
10809 } else if (Var->getStorageClass() == SC_Static) {
10810 // C99 6.9.2p3: If the declaration of an identifier for an object is
10811 // a tentative definition and has internal linkage (C99 6.2.2p3), the
10812 // declared type shall not be an incomplete type.
10813 // NOTE: code such as the following
10814 // static struct s;
10815 // struct s { int a; };
10816 // is accepted by gcc. Hence here we issue a warning instead of
10817 // an error and we do not invalidate the static declaration.
10818 // NOTE: to avoid multiple warnings, only check the first declaration.
10819 if (Var->isFirstDecl())
10820 RequireCompleteType(Var->getLocation(), Type,
10821 diag::ext_typecheck_decl_incomplete_type);
10825 // Record the tentative definition; we're done.
10826 if (!Var->isInvalidDecl())
10827 TentativeDefinitions.push_back(Var);
10831 // Provide a specific diagnostic for uninitialized variable
10832 // definitions with incomplete array type.
10833 if (Type->isIncompleteArrayType()) {
10834 Diag(Var->getLocation(),
10835 diag::err_typecheck_incomplete_array_needs_initializer);
10836 Var->setInvalidDecl();
10840 // Provide a specific diagnostic for uninitialized variable
10841 // definitions with reference type.
10842 if (Type->isReferenceType()) {
10843 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10844 << Var->getDeclName()
10845 << SourceRange(Var->getLocation(), Var->getLocation());
10846 Var->setInvalidDecl();
10850 // Do not attempt to type-check the default initializer for a
10851 // variable with dependent type.
10852 if (Type->isDependentType())
10855 if (Var->isInvalidDecl())
10858 if (!Var->hasAttr<AliasAttr>()) {
10859 if (RequireCompleteType(Var->getLocation(),
10860 Context.getBaseElementType(Type),
10861 diag::err_typecheck_decl_incomplete_type)) {
10862 Var->setInvalidDecl();
10869 // The variable can not have an abstract class type.
10870 if (RequireNonAbstractType(Var->getLocation(), Type,
10871 diag::err_abstract_type_in_decl,
10872 AbstractVariableType)) {
10873 Var->setInvalidDecl();
10877 // Check for jumps past the implicit initializer. C++0x
10878 // clarifies that this applies to a "variable with automatic
10879 // storage duration", not a "local variable".
10880 // C++11 [stmt.dcl]p3
10881 // A program that jumps from a point where a variable with automatic
10882 // storage duration is not in scope to a point where it is in scope is
10883 // ill-formed unless the variable has scalar type, class type with a
10884 // trivial default constructor and a trivial destructor, a cv-qualified
10885 // version of one of these types, or an array of one of the preceding
10886 // types and is declared without an initializer.
10887 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10888 if (const RecordType *Record
10889 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10890 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10891 // Mark the function for further checking even if the looser rules of
10892 // C++11 do not require such checks, so that we can diagnose
10893 // incompatibilities with C++98.
10894 if (!CXXRecord->isPOD())
10895 getCurFunction()->setHasBranchProtectedScope();
10899 // C++03 [dcl.init]p9:
10900 // If no initializer is specified for an object, and the
10901 // object is of (possibly cv-qualified) non-POD class type (or
10902 // array thereof), the object shall be default-initialized; if
10903 // the object is of const-qualified type, the underlying class
10904 // type shall have a user-declared default
10905 // constructor. Otherwise, if no initializer is specified for
10906 // a non- static object, the object and its subobjects, if
10907 // any, have an indeterminate initial value); if the object
10908 // or any of its subobjects are of const-qualified type, the
10909 // program is ill-formed.
10910 // C++0x [dcl.init]p11:
10911 // If no initializer is specified for an object, the object is
10912 // default-initialized; [...].
10913 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10914 InitializationKind Kind
10915 = InitializationKind::CreateDefault(Var->getLocation());
10917 InitializationSequence InitSeq(*this, Entity, Kind, None);
10918 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10919 if (Init.isInvalid())
10920 Var->setInvalidDecl();
10921 else if (Init.get()) {
10922 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10923 // This is important for template substitution.
10924 Var->setInitStyle(VarDecl::CallInit);
10927 CheckCompleteVariableDeclaration(Var);
10931 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10932 // If there is no declaration, there was an error parsing it. Ignore it.
10936 VarDecl *VD = dyn_cast<VarDecl>(D);
10938 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10939 D->setInvalidDecl();
10943 VD->setCXXForRangeDecl(true);
10945 // for-range-declaration cannot be given a storage class specifier.
10947 switch (VD->getStorageClass()) {
10956 case SC_PrivateExtern:
10967 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10968 << VD->getDeclName() << Error;
10969 D->setInvalidDecl();
10974 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10975 IdentifierInfo *Ident,
10976 ParsedAttributes &Attrs,
10977 SourceLocation AttrEnd) {
10978 // C++1y [stmt.iter]p1:
10979 // A range-based for statement of the form
10980 // for ( for-range-identifier : for-range-initializer ) statement
10981 // is equivalent to
10982 // for ( auto&& for-range-identifier : for-range-initializer ) statement
10983 DeclSpec DS(Attrs.getPool().getFactory());
10985 const char *PrevSpec;
10987 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10988 getPrintingPolicy());
10990 Declarator D(DS, Declarator::ForContext);
10991 D.SetIdentifier(Ident, IdentLoc);
10992 D.takeAttributes(Attrs, AttrEnd);
10994 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10995 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10996 EmptyAttrs, IdentLoc);
10997 Decl *Var = ActOnDeclarator(S, D);
10998 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10999 FinalizeDeclaration(Var);
11000 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11001 AttrEnd.isValid() ? AttrEnd : IdentLoc);
11004 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11005 if (var->isInvalidDecl()) return;
11007 if (getLangOpts().OpenCL) {
11008 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11010 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11012 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11014 var->setInvalidDecl();
11019 // In Objective-C, don't allow jumps past the implicit initialization of a
11020 // local retaining variable.
11021 if (getLangOpts().ObjC1 &&
11022 var->hasLocalStorage()) {
11023 switch (var->getType().getObjCLifetime()) {
11024 case Qualifiers::OCL_None:
11025 case Qualifiers::OCL_ExplicitNone:
11026 case Qualifiers::OCL_Autoreleasing:
11029 case Qualifiers::OCL_Weak:
11030 case Qualifiers::OCL_Strong:
11031 getCurFunction()->setHasBranchProtectedScope();
11036 // Warn about externally-visible variables being defined without a
11037 // prior declaration. We only want to do this for global
11038 // declarations, but we also specifically need to avoid doing it for
11039 // class members because the linkage of an anonymous class can
11040 // change if it's later given a typedef name.
11041 if (var->isThisDeclarationADefinition() &&
11042 var->getDeclContext()->getRedeclContext()->isFileContext() &&
11043 var->isExternallyVisible() && var->hasLinkage() &&
11044 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11045 var->getLocation())) {
11046 // Find a previous declaration that's not a definition.
11047 VarDecl *prev = var->getPreviousDecl();
11048 while (prev && prev->isThisDeclarationADefinition())
11049 prev = prev->getPreviousDecl();
11052 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11055 // Cache the result of checking for constant initialization.
11056 Optional<bool> CacheHasConstInit;
11057 const Expr *CacheCulprit;
11058 auto checkConstInit = [&]() mutable {
11059 if (!CacheHasConstInit)
11060 CacheHasConstInit = var->getInit()->isConstantInitializer(
11061 Context, var->getType()->isReferenceType(), &CacheCulprit);
11062 return *CacheHasConstInit;
11065 if (var->getTLSKind() == VarDecl::TLS_Static) {
11066 if (var->getType().isDestructedType()) {
11067 // GNU C++98 edits for __thread, [basic.start.term]p3:
11068 // The type of an object with thread storage duration shall not
11069 // have a non-trivial destructor.
11070 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11071 if (getLangOpts().CPlusPlus11)
11072 Diag(var->getLocation(), diag::note_use_thread_local);
11073 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11074 if (!checkConstInit()) {
11075 // GNU C++98 edits for __thread, [basic.start.init]p4:
11076 // An object of thread storage duration shall not require dynamic
11078 // FIXME: Need strict checking here.
11079 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11080 << CacheCulprit->getSourceRange();
11081 if (getLangOpts().CPlusPlus11)
11082 Diag(var->getLocation(), diag::note_use_thread_local);
11087 // Apply section attributes and pragmas to global variables.
11088 bool GlobalStorage = var->hasGlobalStorage();
11089 if (GlobalStorage && var->isThisDeclarationADefinition() &&
11090 !inTemplateInstantiation()) {
11091 PragmaStack<StringLiteral *> *Stack = nullptr;
11092 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11093 if (var->getType().isConstQualified())
11094 Stack = &ConstSegStack;
11095 else if (!var->getInit()) {
11096 Stack = &BSSSegStack;
11097 SectionFlags |= ASTContext::PSF_Write;
11099 Stack = &DataSegStack;
11100 SectionFlags |= ASTContext::PSF_Write;
11102 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11103 var->addAttr(SectionAttr::CreateImplicit(
11104 Context, SectionAttr::Declspec_allocate,
11105 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11107 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11108 if (UnifySection(SA->getName(), SectionFlags, var))
11109 var->dropAttr<SectionAttr>();
11111 // Apply the init_seg attribute if this has an initializer. If the
11112 // initializer turns out to not be dynamic, we'll end up ignoring this
11114 if (CurInitSeg && var->getInit())
11115 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11119 // All the following checks are C++ only.
11120 if (!getLangOpts().CPlusPlus) {
11121 // If this variable must be emitted, add it as an initializer for the
11123 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11124 Context.addModuleInitializer(ModuleScopes.back().Module, var);
11128 if (auto *DD = dyn_cast<DecompositionDecl>(var))
11129 CheckCompleteDecompositionDeclaration(DD);
11131 QualType type = var->getType();
11132 if (type->isDependentType()) return;
11134 // __block variables might require us to capture a copy-initializer.
11135 if (var->hasAttr<BlocksAttr>()) {
11136 // It's currently invalid to ever have a __block variable with an
11137 // array type; should we diagnose that here?
11139 // Regardless, we don't want to ignore array nesting when
11140 // constructing this copy.
11141 if (type->isStructureOrClassType()) {
11142 EnterExpressionEvaluationContext scope(
11143 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11144 SourceLocation poi = var->getLocation();
11145 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11147 = PerformMoveOrCopyInitialization(
11148 InitializedEntity::InitializeBlock(poi, type, false),
11149 var, var->getType(), varRef, /*AllowNRVO=*/true);
11150 if (!result.isInvalid()) {
11151 result = MaybeCreateExprWithCleanups(result);
11152 Expr *init = result.getAs<Expr>();
11153 Context.setBlockVarCopyInits(var, init);
11158 Expr *Init = var->getInit();
11159 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11160 QualType baseType = Context.getBaseElementType(type);
11162 if (Init && !Init->isValueDependent()) {
11163 if (var->isConstexpr()) {
11164 SmallVector<PartialDiagnosticAt, 8> Notes;
11165 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11166 SourceLocation DiagLoc = var->getLocation();
11167 // If the note doesn't add any useful information other than a source
11168 // location, fold it into the primary diagnostic.
11169 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11170 diag::note_invalid_subexpr_in_const_expr) {
11171 DiagLoc = Notes[0].first;
11174 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11175 << var << Init->getSourceRange();
11176 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11177 Diag(Notes[I].first, Notes[I].second);
11179 } else if (var->isUsableInConstantExpressions(Context)) {
11180 // Check whether the initializer of a const variable of integral or
11181 // enumeration type is an ICE now, since we can't tell whether it was
11182 // initialized by a constant expression if we check later.
11183 var->checkInitIsICE();
11186 // Don't emit further diagnostics about constexpr globals since they
11187 // were just diagnosed.
11188 if (!var->isConstexpr() && GlobalStorage &&
11189 var->hasAttr<RequireConstantInitAttr>()) {
11190 // FIXME: Need strict checking in C++03 here.
11191 bool DiagErr = getLangOpts().CPlusPlus11
11192 ? !var->checkInitIsICE() : !checkConstInit();
11194 auto attr = var->getAttr<RequireConstantInitAttr>();
11195 Diag(var->getLocation(), diag::err_require_constant_init_failed)
11196 << Init->getSourceRange();
11197 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11198 << attr->getRange();
11199 if (getLangOpts().CPlusPlus11) {
11201 SmallVector<PartialDiagnosticAt, 8> Notes;
11202 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11203 for (auto &it : Notes)
11204 Diag(it.first, it.second);
11206 Diag(CacheCulprit->getExprLoc(),
11207 diag::note_invalid_subexpr_in_const_expr)
11208 << CacheCulprit->getSourceRange();
11212 else if (!var->isConstexpr() && IsGlobal &&
11213 !getDiagnostics().isIgnored(diag::warn_global_constructor,
11214 var->getLocation())) {
11215 // Warn about globals which don't have a constant initializer. Don't
11216 // warn about globals with a non-trivial destructor because we already
11217 // warned about them.
11218 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11219 if (!(RD && !RD->hasTrivialDestructor())) {
11220 if (!checkConstInit())
11221 Diag(var->getLocation(), diag::warn_global_constructor)
11222 << Init->getSourceRange();
11227 // Require the destructor.
11228 if (const RecordType *recordType = baseType->getAs<RecordType>())
11229 FinalizeVarWithDestructor(var, recordType);
11231 // If this variable must be emitted, add it as an initializer for the current
11233 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11234 Context.addModuleInitializer(ModuleScopes.back().Module, var);
11237 /// \brief Determines if a variable's alignment is dependent.
11238 static bool hasDependentAlignment(VarDecl *VD) {
11239 if (VD->getType()->isDependentType())
11241 for (auto *I : VD->specific_attrs<AlignedAttr>())
11242 if (I->isAlignmentDependent())
11247 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11248 /// any semantic actions necessary after any initializer has been attached.
11249 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11250 // Note that we are no longer parsing the initializer for this declaration.
11251 ParsingInitForAutoVars.erase(ThisDecl);
11253 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11257 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11258 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11259 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11260 if (PragmaClangBSSSection.Valid)
11261 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11262 PragmaClangBSSSection.SectionName,
11263 PragmaClangBSSSection.PragmaLocation));
11264 if (PragmaClangDataSection.Valid)
11265 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11266 PragmaClangDataSection.SectionName,
11267 PragmaClangDataSection.PragmaLocation));
11268 if (PragmaClangRodataSection.Valid)
11269 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11270 PragmaClangRodataSection.SectionName,
11271 PragmaClangRodataSection.PragmaLocation));
11274 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11275 for (auto *BD : DD->bindings()) {
11276 FinalizeDeclaration(BD);
11280 checkAttributesAfterMerging(*this, *VD);
11282 // Perform TLS alignment check here after attributes attached to the variable
11283 // which may affect the alignment have been processed. Only perform the check
11284 // if the target has a maximum TLS alignment (zero means no constraints).
11285 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11286 // Protect the check so that it's not performed on dependent types and
11287 // dependent alignments (we can't determine the alignment in that case).
11288 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11289 !VD->isInvalidDecl()) {
11290 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11291 if (Context.getDeclAlign(VD) > MaxAlignChars) {
11292 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11293 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11294 << (unsigned)MaxAlignChars.getQuantity();
11299 if (VD->isStaticLocal()) {
11300 if (FunctionDecl *FD =
11301 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11302 // Static locals inherit dll attributes from their function.
11303 if (Attr *A = getDLLAttr(FD)) {
11304 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11305 NewAttr->setInherited(true);
11306 VD->addAttr(NewAttr);
11308 // CUDA E.2.9.4: Within the body of a __device__ or __global__
11309 // function, only __shared__ variables may be declared with
11310 // static storage class.
11311 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11312 CUDADiagIfDeviceCode(VD->getLocation(),
11313 diag::err_device_static_local_var)
11314 << CurrentCUDATarget())
11315 VD->setInvalidDecl();
11319 // Perform check for initializers of device-side global variables.
11320 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11321 // 7.5). We must also apply the same checks to all __shared__
11322 // variables whether they are local or not. CUDA also allows
11323 // constant initializers for __constant__ and __device__ variables.
11324 if (getLangOpts().CUDA) {
11325 const Expr *Init = VD->getInit();
11326 if (Init && VD->hasGlobalStorage()) {
11327 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11328 VD->hasAttr<CUDASharedAttr>()) {
11329 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11330 bool AllowedInit = false;
11331 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11333 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11334 // We'll allow constant initializers even if it's a non-empty
11335 // constructor according to CUDA rules. This deviates from NVCC,
11336 // but allows us to handle things like constexpr constructors.
11337 if (!AllowedInit &&
11338 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11339 AllowedInit = VD->getInit()->isConstantInitializer(
11340 Context, VD->getType()->isReferenceType());
11342 // Also make sure that destructor, if there is one, is empty.
11344 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11346 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11348 if (!AllowedInit) {
11349 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11350 ? diag::err_shared_var_init
11351 : diag::err_dynamic_var_init)
11352 << Init->getSourceRange();
11353 VD->setInvalidDecl();
11356 // This is a host-side global variable. Check that the initializer is
11357 // callable from the host side.
11358 const FunctionDecl *InitFn = nullptr;
11359 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11360 InitFn = CE->getConstructor();
11361 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11362 InitFn = CE->getDirectCallee();
11365 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11366 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11367 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11368 << InitFnTarget << InitFn;
11369 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11370 VD->setInvalidDecl();
11377 // Grab the dllimport or dllexport attribute off of the VarDecl.
11378 const InheritableAttr *DLLAttr = getDLLAttr(VD);
11380 // Imported static data members cannot be defined out-of-line.
11381 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11382 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11383 VD->isThisDeclarationADefinition()) {
11384 // We allow definitions of dllimport class template static data members
11386 CXXRecordDecl *Context =
11387 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11388 bool IsClassTemplateMember =
11389 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11390 Context->getDescribedClassTemplate();
11392 Diag(VD->getLocation(),
11393 IsClassTemplateMember
11394 ? diag::warn_attribute_dllimport_static_field_definition
11395 : diag::err_attribute_dllimport_static_field_definition);
11396 Diag(IA->getLocation(), diag::note_attribute);
11397 if (!IsClassTemplateMember)
11398 VD->setInvalidDecl();
11402 // dllimport/dllexport variables cannot be thread local, their TLS index
11403 // isn't exported with the variable.
11404 if (DLLAttr && VD->getTLSKind()) {
11405 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11406 if (F && getDLLAttr(F)) {
11407 assert(VD->isStaticLocal());
11408 // But if this is a static local in a dlimport/dllexport function, the
11409 // function will never be inlined, which means the var would never be
11410 // imported, so having it marked import/export is safe.
11412 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11414 VD->setInvalidDecl();
11418 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11419 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11420 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11421 VD->dropAttr<UsedAttr>();
11425 const DeclContext *DC = VD->getDeclContext();
11426 // If there's a #pragma GCC visibility in scope, and this isn't a class
11427 // member, set the visibility of this variable.
11428 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11429 AddPushedVisibilityAttribute(VD);
11431 // FIXME: Warn on unused var template partial specializations.
11432 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11433 MarkUnusedFileScopedDecl(VD);
11435 // Now we have parsed the initializer and can update the table of magic
11437 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11438 !VD->getType()->isIntegralOrEnumerationType())
11441 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11442 const Expr *MagicValueExpr = VD->getInit();
11443 if (!MagicValueExpr) {
11446 llvm::APSInt MagicValueInt;
11447 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11448 Diag(I->getRange().getBegin(),
11449 diag::err_type_tag_for_datatype_not_ice)
11450 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11453 if (MagicValueInt.getActiveBits() > 64) {
11454 Diag(I->getRange().getBegin(),
11455 diag::err_type_tag_for_datatype_too_large)
11456 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11459 uint64_t MagicValue = MagicValueInt.getZExtValue();
11460 RegisterTypeTagForDatatype(I->getArgumentKind(),
11462 I->getMatchingCType(),
11463 I->getLayoutCompatible(),
11464 I->getMustBeNull());
11468 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11469 auto *VD = dyn_cast<VarDecl>(DD);
11470 return VD && !VD->getType()->hasAutoForTrailingReturnType();
11473 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11474 ArrayRef<Decl *> Group) {
11475 SmallVector<Decl*, 8> Decls;
11477 if (DS.isTypeSpecOwned())
11478 Decls.push_back(DS.getRepAsDecl());
11480 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11481 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11482 bool DiagnosedMultipleDecomps = false;
11483 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11484 bool DiagnosedNonDeducedAuto = false;
11486 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11487 if (Decl *D = Group[i]) {
11488 // For declarators, there are some additional syntactic-ish checks we need
11490 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11491 if (!FirstDeclaratorInGroup)
11492 FirstDeclaratorInGroup = DD;
11493 if (!FirstDecompDeclaratorInGroup)
11494 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11495 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11496 !hasDeducedAuto(DD))
11497 FirstNonDeducedAutoInGroup = DD;
11499 if (FirstDeclaratorInGroup != DD) {
11500 // A decomposition declaration cannot be combined with any other
11501 // declaration in the same group.
11502 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11503 Diag(FirstDecompDeclaratorInGroup->getLocation(),
11504 diag::err_decomp_decl_not_alone)
11505 << FirstDeclaratorInGroup->getSourceRange()
11506 << DD->getSourceRange();
11507 DiagnosedMultipleDecomps = true;
11510 // A declarator that uses 'auto' in any way other than to declare a
11511 // variable with a deduced type cannot be combined with any other
11512 // declarator in the same group.
11513 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11514 Diag(FirstNonDeducedAutoInGroup->getLocation(),
11515 diag::err_auto_non_deduced_not_alone)
11516 << FirstNonDeducedAutoInGroup->getType()
11517 ->hasAutoForTrailingReturnType()
11518 << FirstDeclaratorInGroup->getSourceRange()
11519 << DD->getSourceRange();
11520 DiagnosedNonDeducedAuto = true;
11525 Decls.push_back(D);
11529 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11530 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11531 handleTagNumbering(Tag, S);
11532 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11533 getLangOpts().CPlusPlus)
11534 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11538 return BuildDeclaratorGroup(Decls);
11541 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11542 /// group, performing any necessary semantic checking.
11543 Sema::DeclGroupPtrTy
11544 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11545 // C++14 [dcl.spec.auto]p7: (DR1347)
11546 // If the type that replaces the placeholder type is not the same in each
11547 // deduction, the program is ill-formed.
11548 if (Group.size() > 1) {
11550 VarDecl *DeducedDecl = nullptr;
11551 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11552 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11553 if (!D || D->isInvalidDecl())
11555 DeducedType *DT = D->getType()->getContainedDeducedType();
11556 if (!DT || DT->getDeducedType().isNull())
11558 if (Deduced.isNull()) {
11559 Deduced = DT->getDeducedType();
11561 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11562 auto *AT = dyn_cast<AutoType>(DT);
11563 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11564 diag::err_auto_different_deductions)
11565 << (AT ? (unsigned)AT->getKeyword() : 3)
11566 << Deduced << DeducedDecl->getDeclName()
11567 << DT->getDeducedType() << D->getDeclName()
11568 << DeducedDecl->getInit()->getSourceRange()
11569 << D->getInit()->getSourceRange();
11570 D->setInvalidDecl();
11576 ActOnDocumentableDecls(Group);
11578 return DeclGroupPtrTy::make(
11579 DeclGroupRef::Create(Context, Group.data(), Group.size()));
11582 void Sema::ActOnDocumentableDecl(Decl *D) {
11583 ActOnDocumentableDecls(D);
11586 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11587 // Don't parse the comment if Doxygen diagnostics are ignored.
11588 if (Group.empty() || !Group[0])
11591 if (Diags.isIgnored(diag::warn_doc_param_not_found,
11592 Group[0]->getLocation()) &&
11593 Diags.isIgnored(diag::warn_unknown_comment_command_name,
11594 Group[0]->getLocation()))
11597 if (Group.size() >= 2) {
11598 // This is a decl group. Normally it will contain only declarations
11599 // produced from declarator list. But in case we have any definitions or
11600 // additional declaration references:
11601 // 'typedef struct S {} S;'
11602 // 'typedef struct S *S;'
11604 // FinalizeDeclaratorGroup adds these as separate declarations.
11605 Decl *MaybeTagDecl = Group[0];
11606 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11607 Group = Group.slice(1);
11611 // See if there are any new comments that are not attached to a decl.
11612 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11613 if (!Comments.empty() &&
11614 !Comments.back()->isAttached()) {
11615 // There is at least one comment that not attached to a decl.
11616 // Maybe it should be attached to one of these decls?
11618 // Note that this way we pick up not only comments that precede the
11619 // declaration, but also comments that *follow* the declaration -- thanks to
11620 // the lookahead in the lexer: we've consumed the semicolon and looked
11621 // ahead through comments.
11622 for (unsigned i = 0, e = Group.size(); i != e; ++i)
11623 Context.getCommentForDecl(Group[i], &PP);
11627 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11628 /// to introduce parameters into function prototype scope.
11629 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11630 const DeclSpec &DS = D.getDeclSpec();
11632 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11634 // C++03 [dcl.stc]p2 also permits 'auto'.
11635 StorageClass SC = SC_None;
11636 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11638 } else if (getLangOpts().CPlusPlus &&
11639 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11641 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11642 Diag(DS.getStorageClassSpecLoc(),
11643 diag::err_invalid_storage_class_in_func_decl);
11644 D.getMutableDeclSpec().ClearStorageClassSpecs();
11647 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11648 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11649 << DeclSpec::getSpecifierName(TSCS);
11650 if (DS.isInlineSpecified())
11651 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11652 << getLangOpts().CPlusPlus1z;
11653 if (DS.isConstexprSpecified())
11654 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11656 if (DS.isConceptSpecified())
11657 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11659 DiagnoseFunctionSpecifiers(DS);
11661 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11662 QualType parmDeclType = TInfo->getType();
11664 if (getLangOpts().CPlusPlus) {
11665 // Check that there are no default arguments inside the type of this
11667 CheckExtraCXXDefaultArguments(D);
11669 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11670 if (D.getCXXScopeSpec().isSet()) {
11671 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11672 << D.getCXXScopeSpec().getRange();
11673 D.getCXXScopeSpec().clear();
11677 // Ensure we have a valid name
11678 IdentifierInfo *II = nullptr;
11680 II = D.getIdentifier();
11682 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11683 << GetNameForDeclarator(D).getName();
11684 D.setInvalidType(true);
11688 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11690 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11693 if (R.isSingleResult()) {
11694 NamedDecl *PrevDecl = R.getFoundDecl();
11695 if (PrevDecl->isTemplateParameter()) {
11696 // Maybe we will complain about the shadowed template parameter.
11697 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11698 // Just pretend that we didn't see the previous declaration.
11699 PrevDecl = nullptr;
11700 } else if (S->isDeclScope(PrevDecl)) {
11701 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11702 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11704 // Recover by removing the name
11706 D.SetIdentifier(nullptr, D.getIdentifierLoc());
11707 D.setInvalidType(true);
11712 // Temporarily put parameter variables in the translation unit, not
11713 // the enclosing context. This prevents them from accidentally
11714 // looking like class members in C++.
11715 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11717 D.getIdentifierLoc(), II,
11718 parmDeclType, TInfo,
11721 if (D.isInvalidType())
11722 New->setInvalidDecl();
11724 assert(S->isFunctionPrototypeScope());
11725 assert(S->getFunctionPrototypeDepth() >= 1);
11726 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11727 S->getNextFunctionPrototypeIndex());
11729 // Add the parameter declaration into this scope.
11732 IdResolver.AddDecl(New);
11734 ProcessDeclAttributes(S, New, D);
11736 if (D.getDeclSpec().isModulePrivateSpecified())
11737 Diag(New->getLocation(), diag::err_module_private_local)
11738 << 1 << New->getDeclName()
11739 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11740 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11742 if (New->hasAttr<BlocksAttr>()) {
11743 Diag(New->getLocation(), diag::err_block_on_nonlocal);
11748 /// \brief Synthesizes a variable for a parameter arising from a
11750 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11751 SourceLocation Loc,
11753 /* FIXME: setting StartLoc == Loc.
11754 Would it be worth to modify callers so as to provide proper source
11755 location for the unnamed parameters, embedding the parameter's type? */
11756 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11757 T, Context.getTrivialTypeSourceInfo(T, Loc),
11759 Param->setImplicit();
11763 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11764 // Don't diagnose unused-parameter errors in template instantiations; we
11765 // will already have done so in the template itself.
11766 if (inTemplateInstantiation())
11769 for (const ParmVarDecl *Parameter : Parameters) {
11770 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11771 !Parameter->hasAttr<UnusedAttr>()) {
11772 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11773 << Parameter->getDeclName();
11778 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11779 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11780 if (LangOpts.NumLargeByValueCopy == 0) // No check.
11783 // Warn if the return value is pass-by-value and larger than the specified
11785 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11786 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11787 if (Size > LangOpts.NumLargeByValueCopy)
11788 Diag(D->getLocation(), diag::warn_return_value_size)
11789 << D->getDeclName() << Size;
11792 // Warn if any parameter is pass-by-value and larger than the specified
11794 for (const ParmVarDecl *Parameter : Parameters) {
11795 QualType T = Parameter->getType();
11796 if (T->isDependentType() || !T.isPODType(Context))
11798 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11799 if (Size > LangOpts.NumLargeByValueCopy)
11800 Diag(Parameter->getLocation(), diag::warn_parameter_size)
11801 << Parameter->getDeclName() << Size;
11805 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11806 SourceLocation NameLoc, IdentifierInfo *Name,
11807 QualType T, TypeSourceInfo *TSInfo,
11809 // In ARC, infer a lifetime qualifier for appropriate parameter types.
11810 if (getLangOpts().ObjCAutoRefCount &&
11811 T.getObjCLifetime() == Qualifiers::OCL_None &&
11812 T->isObjCLifetimeType()) {
11814 Qualifiers::ObjCLifetime lifetime;
11816 // Special cases for arrays:
11817 // - if it's const, use __unsafe_unretained
11818 // - otherwise, it's an error
11819 if (T->isArrayType()) {
11820 if (!T.isConstQualified()) {
11821 DelayedDiagnostics.add(
11822 sema::DelayedDiagnostic::makeForbiddenType(
11823 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11825 lifetime = Qualifiers::OCL_ExplicitNone;
11827 lifetime = T->getObjCARCImplicitLifetime();
11829 T = Context.getLifetimeQualifiedType(T, lifetime);
11832 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11833 Context.getAdjustedParameterType(T),
11834 TSInfo, SC, nullptr);
11836 // Parameters can not be abstract class types.
11837 // For record types, this is done by the AbstractClassUsageDiagnoser once
11838 // the class has been completely parsed.
11839 if (!CurContext->isRecord() &&
11840 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11841 AbstractParamType))
11842 New->setInvalidDecl();
11844 // Parameter declarators cannot be interface types. All ObjC objects are
11845 // passed by reference.
11846 if (T->isObjCObjectType()) {
11847 SourceLocation TypeEndLoc =
11848 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11850 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11851 << FixItHint::CreateInsertion(TypeEndLoc, "*");
11852 T = Context.getObjCObjectPointerType(T);
11856 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11857 // duration shall not be qualified by an address-space qualifier."
11858 // Since all parameters have automatic store duration, they can not have
11859 // an address space.
11860 if (T.getAddressSpace() != 0) {
11861 // OpenCL allows function arguments declared to be an array of a type
11862 // to be qualified with an address space.
11863 if (!(getLangOpts().OpenCL && T->isArrayType())) {
11864 Diag(NameLoc, diag::err_arg_with_address_space);
11865 New->setInvalidDecl();
11872 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11873 SourceLocation LocAfterDecls) {
11874 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11876 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11877 // for a K&R function.
11878 if (!FTI.hasPrototype) {
11879 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11881 if (FTI.Params[i].Param == nullptr) {
11882 SmallString<256> Code;
11883 llvm::raw_svector_ostream(Code)
11884 << " int " << FTI.Params[i].Ident->getName() << ";\n";
11885 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11886 << FTI.Params[i].Ident
11887 << FixItHint::CreateInsertion(LocAfterDecls, Code);
11889 // Implicitly declare the argument as type 'int' for lack of a better
11891 AttributeFactory attrs;
11892 DeclSpec DS(attrs);
11893 const char* PrevSpec; // unused
11894 unsigned DiagID; // unused
11895 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11896 DiagID, Context.getPrintingPolicy());
11897 // Use the identifier location for the type source range.
11898 DS.SetRangeStart(FTI.Params[i].IdentLoc);
11899 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11900 Declarator ParamD(DS, Declarator::KNRTypeListContext);
11901 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11902 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11909 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11910 MultiTemplateParamsArg TemplateParameterLists,
11911 SkipBodyInfo *SkipBody) {
11912 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11913 assert(D.isFunctionDeclarator() && "Not a function declarator!");
11914 Scope *ParentScope = FnBodyScope->getParent();
11916 D.setFunctionDefinitionKind(FDK_Definition);
11917 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11918 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11921 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11922 Consumer.HandleInlineFunctionDefinition(D);
11925 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11926 const FunctionDecl*& PossibleZeroParamPrototype) {
11927 // Don't warn about invalid declarations.
11928 if (FD->isInvalidDecl())
11931 // Or declarations that aren't global.
11932 if (!FD->isGlobal())
11935 // Don't warn about C++ member functions.
11936 if (isa<CXXMethodDecl>(FD))
11939 // Don't warn about 'main'.
11943 // Don't warn about inline functions.
11944 if (FD->isInlined())
11947 // Don't warn about function templates.
11948 if (FD->getDescribedFunctionTemplate())
11951 // Don't warn about function template specializations.
11952 if (FD->isFunctionTemplateSpecialization())
11955 // Don't warn for OpenCL kernels.
11956 if (FD->hasAttr<OpenCLKernelAttr>())
11959 // Don't warn on explicitly deleted functions.
11960 if (FD->isDeleted())
11963 bool MissingPrototype = true;
11964 for (const FunctionDecl *Prev = FD->getPreviousDecl();
11965 Prev; Prev = Prev->getPreviousDecl()) {
11966 // Ignore any declarations that occur in function or method
11967 // scope, because they aren't visible from the header.
11968 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11971 MissingPrototype = !Prev->getType()->isFunctionProtoType();
11972 if (FD->getNumParams() == 0)
11973 PossibleZeroParamPrototype = Prev;
11977 return MissingPrototype;
11981 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11982 const FunctionDecl *EffectiveDefinition,
11983 SkipBodyInfo *SkipBody) {
11984 const FunctionDecl *Definition = EffectiveDefinition;
11986 if (!FD->isDefined(Definition))
11989 if (canRedefineFunction(Definition, getLangOpts()))
11992 // Don't emit an error when this is redefinition of a typo-corrected
11994 if (TypoCorrectedFunctionDefinitions.count(Definition))
11997 // If we don't have a visible definition of the function, and it's inline or
11998 // a template, skip the new definition.
11999 if (SkipBody && !hasVisibleDefinition(Definition) &&
12000 (Definition->getFormalLinkage() == InternalLinkage ||
12001 Definition->isInlined() ||
12002 Definition->getDescribedFunctionTemplate() ||
12003 Definition->getNumTemplateParameterLists())) {
12004 SkipBody->ShouldSkip = true;
12005 if (auto *TD = Definition->getDescribedFunctionTemplate())
12006 makeMergedDefinitionVisible(TD);
12007 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12011 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12012 Definition->getStorageClass() == SC_Extern)
12013 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12014 << FD->getDeclName() << getLangOpts().CPlusPlus;
12016 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12018 Diag(Definition->getLocation(), diag::note_previous_definition);
12019 FD->setInvalidDecl();
12022 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12024 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12026 LambdaScopeInfo *LSI = S.PushLambdaScope();
12027 LSI->CallOperator = CallOperator;
12028 LSI->Lambda = LambdaClass;
12029 LSI->ReturnType = CallOperator->getReturnType();
12030 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12032 if (LCD == LCD_None)
12033 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12034 else if (LCD == LCD_ByCopy)
12035 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12036 else if (LCD == LCD_ByRef)
12037 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12038 DeclarationNameInfo DNI = CallOperator->getNameInfo();
12040 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12041 LSI->Mutable = !CallOperator->isConst();
12043 // Add the captures to the LSI so they can be noted as already
12044 // captured within tryCaptureVar.
12045 auto I = LambdaClass->field_begin();
12046 for (const auto &C : LambdaClass->captures()) {
12047 if (C.capturesVariable()) {
12048 VarDecl *VD = C.getCapturedVar();
12049 if (VD->isInitCapture())
12050 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12051 QualType CaptureType = VD->getType();
12052 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12053 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12054 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12055 /*EllipsisLoc*/C.isPackExpansion()
12056 ? C.getEllipsisLoc() : SourceLocation(),
12057 CaptureType, /*Expr*/ nullptr);
12059 } else if (C.capturesThis()) {
12060 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12062 C.getCaptureKind() == LCK_StarThis);
12064 LSI->addVLATypeCapture(C.getLocation(), I->getType());
12070 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12071 SkipBodyInfo *SkipBody) {
12074 FunctionDecl *FD = nullptr;
12076 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12077 FD = FunTmpl->getTemplatedDecl();
12079 FD = cast<FunctionDecl>(D);
12081 // Check for defining attributes before the check for redefinition.
12082 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12083 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12084 FD->dropAttr<AliasAttr>();
12085 FD->setInvalidDecl();
12087 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12088 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12089 FD->dropAttr<IFuncAttr>();
12090 FD->setInvalidDecl();
12093 // See if this is a redefinition. If 'will have body' is already set, then
12094 // these checks were already performed when it was set.
12095 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12096 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12098 // If we're skipping the body, we're done. Don't enter the scope.
12099 if (SkipBody && SkipBody->ShouldSkip)
12103 // Mark this function as "will have a body eventually". This lets users to
12104 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12106 FD->setWillHaveBody();
12108 // If we are instantiating a generic lambda call operator, push
12109 // a LambdaScopeInfo onto the function stack. But use the information
12110 // that's already been calculated (ActOnLambdaExpr) to prime the current
12111 // LambdaScopeInfo.
12112 // When the template operator is being specialized, the LambdaScopeInfo,
12113 // has to be properly restored so that tryCaptureVariable doesn't try
12114 // and capture any new variables. In addition when calculating potential
12115 // captures during transformation of nested lambdas, it is necessary to
12116 // have the LSI properly restored.
12117 if (isGenericLambdaCallOperatorSpecialization(FD)) {
12118 assert(inTemplateInstantiation() &&
12119 "There should be an active template instantiation on the stack "
12120 "when instantiating a generic lambda!");
12121 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12123 // Enter a new function scope
12124 PushFunctionScope();
12127 // Builtin functions cannot be defined.
12128 if (unsigned BuiltinID = FD->getBuiltinID()) {
12129 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12130 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12131 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12132 FD->setInvalidDecl();
12136 // The return type of a function definition must be complete
12137 // (C99 6.9.1p3, C++ [dcl.fct]p6).
12138 QualType ResultType = FD->getReturnType();
12139 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12140 !FD->isInvalidDecl() &&
12141 RequireCompleteType(FD->getLocation(), ResultType,
12142 diag::err_func_def_incomplete_result))
12143 FD->setInvalidDecl();
12146 PushDeclContext(FnBodyScope, FD);
12148 // Check the validity of our function parameters
12149 CheckParmsForFunctionDef(FD->parameters(),
12150 /*CheckParameterNames=*/true);
12152 // Add non-parameter declarations already in the function to the current
12155 for (Decl *NPD : FD->decls()) {
12156 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12159 assert(!isa<ParmVarDecl>(NonParmDecl) &&
12160 "parameters should not be in newly created FD yet");
12162 // If the decl has a name, make it accessible in the current scope.
12163 if (NonParmDecl->getDeclName())
12164 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12166 // Similarly, dive into enums and fish their constants out, making them
12167 // accessible in this scope.
12168 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12169 for (auto *EI : ED->enumerators())
12170 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12175 // Introduce our parameters into the function scope
12176 for (auto Param : FD->parameters()) {
12177 Param->setOwningFunction(FD);
12179 // If this has an identifier, add it to the scope stack.
12180 if (Param->getIdentifier() && FnBodyScope) {
12181 CheckShadow(FnBodyScope, Param);
12183 PushOnScopeChains(Param, FnBodyScope);
12187 // Ensure that the function's exception specification is instantiated.
12188 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12189 ResolveExceptionSpec(D->getLocation(), FPT);
12191 // dllimport cannot be applied to non-inline function definitions.
12192 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12193 !FD->isTemplateInstantiation()) {
12194 assert(!FD->hasAttr<DLLExportAttr>());
12195 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12196 FD->setInvalidDecl();
12199 // We want to attach documentation to original Decl (which might be
12200 // a function template).
12201 ActOnDocumentableDecl(D);
12202 if (getCurLexicalContext()->isObjCContainer() &&
12203 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12204 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12205 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12210 /// \brief Given the set of return statements within a function body,
12211 /// compute the variables that are subject to the named return value
12214 /// Each of the variables that is subject to the named return value
12215 /// optimization will be marked as NRVO variables in the AST, and any
12216 /// return statement that has a marked NRVO variable as its NRVO candidate can
12217 /// use the named return value optimization.
12219 /// This function applies a very simplistic algorithm for NRVO: if every return
12220 /// statement in the scope of a variable has the same NRVO candidate, that
12221 /// candidate is an NRVO variable.
12222 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12223 ReturnStmt **Returns = Scope->Returns.data();
12225 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12226 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12227 if (!NRVOCandidate->isNRVOVariable())
12228 Returns[I]->setNRVOCandidate(nullptr);
12233 bool Sema::canDelayFunctionBody(const Declarator &D) {
12234 // We can't delay parsing the body of a constexpr function template (yet).
12235 if (D.getDeclSpec().isConstexprSpecified())
12238 // We can't delay parsing the body of a function template with a deduced
12239 // return type (yet).
12240 if (D.getDeclSpec().hasAutoTypeSpec()) {
12241 // If the placeholder introduces a non-deduced trailing return type,
12242 // we can still delay parsing it.
12243 if (D.getNumTypeObjects()) {
12244 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12245 if (Outer.Kind == DeclaratorChunk::Function &&
12246 Outer.Fun.hasTrailingReturnType()) {
12247 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12248 return Ty.isNull() || !Ty->isUndeducedType();
12257 bool Sema::canSkipFunctionBody(Decl *D) {
12258 // We cannot skip the body of a function (or function template) which is
12259 // constexpr, since we may need to evaluate its body in order to parse the
12260 // rest of the file.
12261 // We cannot skip the body of a function with an undeduced return type,
12262 // because any callers of that function need to know the type.
12263 if (const FunctionDecl *FD = D->getAsFunction())
12264 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12266 return Consumer.shouldSkipFunctionBody(D);
12269 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12270 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12271 FD->setHasSkippedBody();
12272 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12273 MD->setHasSkippedBody();
12277 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12278 return ActOnFinishFunctionBody(D, BodyArg, false);
12281 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12282 bool IsInstantiation) {
12283 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12285 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12286 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12288 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12289 CheckCompletedCoroutineBody(FD, Body);
12293 FD->setWillHaveBody(false);
12295 if (getLangOpts().CPlusPlus14) {
12296 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12297 FD->getReturnType()->isUndeducedType()) {
12298 // If the function has a deduced result type but contains no 'return'
12299 // statements, the result type as written must be exactly 'auto', and
12300 // the deduced result type is 'void'.
12301 if (!FD->getReturnType()->getAs<AutoType>()) {
12302 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12303 << FD->getReturnType();
12304 FD->setInvalidDecl();
12306 // Substitute 'void' for the 'auto' in the type.
12307 TypeLoc ResultType = getReturnTypeLoc(FD);
12308 Context.adjustDeducedFunctionResultType(
12309 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12312 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12313 // In C++11, we don't use 'auto' deduction rules for lambda call
12314 // operators because we don't support return type deduction.
12315 auto *LSI = getCurLambda();
12316 if (LSI->HasImplicitReturnType) {
12317 deduceClosureReturnType(*LSI);
12319 // C++11 [expr.prim.lambda]p4:
12320 // [...] if there are no return statements in the compound-statement
12321 // [the deduced type is] the type void
12323 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12325 // Update the return type to the deduced type.
12326 const FunctionProtoType *Proto =
12327 FD->getType()->getAs<FunctionProtoType>();
12328 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12329 Proto->getExtProtoInfo()));
12333 // The only way to be included in UndefinedButUsed is if there is an
12334 // ODR use before the definition. Avoid the expensive map lookup if this
12335 // is the first declaration.
12336 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12337 if (!FD->isExternallyVisible())
12338 UndefinedButUsed.erase(FD);
12339 else if (FD->isInlined() &&
12340 !LangOpts.GNUInline &&
12341 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12342 UndefinedButUsed.erase(FD);
12345 // If the function implicitly returns zero (like 'main') or is naked,
12346 // don't complain about missing return statements.
12347 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12348 WP.disableCheckFallThrough();
12350 // MSVC permits the use of pure specifier (=0) on function definition,
12351 // defined at class scope, warn about this non-standard construct.
12352 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12353 Diag(FD->getLocation(), diag::ext_pure_function_definition);
12355 if (!FD->isInvalidDecl()) {
12356 // Don't diagnose unused parameters of defaulted or deleted functions.
12357 if (!FD->isDeleted() && !FD->isDefaulted())
12358 DiagnoseUnusedParameters(FD->parameters());
12359 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12360 FD->getReturnType(), FD);
12362 // If this is a structor, we need a vtable.
12363 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12364 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12365 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12366 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12368 // Try to apply the named return value optimization. We have to check
12369 // if we can do this here because lambdas keep return statements around
12370 // to deduce an implicit return type.
12371 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12372 !FD->isDependentContext())
12373 computeNRVO(Body, getCurFunction());
12376 // GNU warning -Wmissing-prototypes:
12377 // Warn if a global function is defined without a previous
12378 // prototype declaration. This warning is issued even if the
12379 // definition itself provides a prototype. The aim is to detect
12380 // global functions that fail to be declared in header files.
12381 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12382 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12383 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12385 if (PossibleZeroParamPrototype) {
12386 // We found a declaration that is not a prototype,
12387 // but that could be a zero-parameter prototype
12388 if (TypeSourceInfo *TI =
12389 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12390 TypeLoc TL = TI->getTypeLoc();
12391 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12392 Diag(PossibleZeroParamPrototype->getLocation(),
12393 diag::note_declaration_not_a_prototype)
12394 << PossibleZeroParamPrototype
12395 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12399 // GNU warning -Wstrict-prototypes
12400 // Warn if K&R function is defined without a previous declaration.
12401 // This warning is issued only if the definition itself does not provide
12402 // a prototype. Only K&R definitions do not provide a prototype.
12403 // An empty list in a function declarator that is part of a definition
12404 // of that function specifies that the function has no parameters
12405 // (C99 6.7.5.3p14)
12406 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12407 !LangOpts.CPlusPlus) {
12408 TypeSourceInfo *TI = FD->getTypeSourceInfo();
12409 TypeLoc TL = TI->getTypeLoc();
12410 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12411 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12415 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12416 const CXXMethodDecl *KeyFunction;
12417 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12419 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12420 MD == KeyFunction->getCanonicalDecl()) {
12421 // Update the key-function state if necessary for this ABI.
12422 if (FD->isInlined() &&
12423 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12424 Context.setNonKeyFunction(MD);
12426 // If the newly-chosen key function is already defined, then we
12427 // need to mark the vtable as used retroactively.
12428 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12429 const FunctionDecl *Definition;
12430 if (KeyFunction && KeyFunction->isDefined(Definition))
12431 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12433 // We just defined they key function; mark the vtable as used.
12434 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12439 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12440 "Function parsing confused");
12441 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12442 assert(MD == getCurMethodDecl() && "Method parsing confused");
12444 if (!MD->isInvalidDecl()) {
12445 DiagnoseUnusedParameters(MD->parameters());
12446 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12447 MD->getReturnType(), MD);
12450 computeNRVO(Body, getCurFunction());
12452 if (getCurFunction()->ObjCShouldCallSuper) {
12453 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12454 << MD->getSelector().getAsString();
12455 getCurFunction()->ObjCShouldCallSuper = false;
12457 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12458 const ObjCMethodDecl *InitMethod = nullptr;
12459 bool isDesignated =
12460 MD->isDesignatedInitializerForTheInterface(&InitMethod);
12461 assert(isDesignated && InitMethod);
12462 (void)isDesignated;
12464 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12465 auto IFace = MD->getClassInterface();
12468 auto SuperD = IFace->getSuperClass();
12471 return SuperD->getIdentifier() ==
12472 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12474 // Don't issue this warning for unavailable inits or direct subclasses
12476 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12477 Diag(MD->getLocation(),
12478 diag::warn_objc_designated_init_missing_super_call);
12479 Diag(InitMethod->getLocation(),
12480 diag::note_objc_designated_init_marked_here);
12482 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12484 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12485 // Don't issue this warning for unavaialable inits.
12486 if (!MD->isUnavailable())
12487 Diag(MD->getLocation(),
12488 diag::warn_objc_secondary_init_missing_init_call);
12489 getCurFunction()->ObjCWarnForNoInitDelegation = false;
12495 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12496 DiagnoseUnguardedAvailabilityViolations(dcl);
12498 assert(!getCurFunction()->ObjCShouldCallSuper &&
12499 "This should only be set for ObjC methods, which should have been "
12500 "handled in the block above.");
12502 // Verify and clean out per-function state.
12503 if (Body && (!FD || !FD->isDefaulted())) {
12504 // C++ constructors that have function-try-blocks can't have return
12505 // statements in the handlers of that block. (C++ [except.handle]p14)
12507 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12508 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12510 // Verify that gotos and switch cases don't jump into scopes illegally.
12511 if (getCurFunction()->NeedsScopeChecking() &&
12512 !PP.isCodeCompletionEnabled())
12513 DiagnoseInvalidJumps(Body);
12515 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12516 if (!Destructor->getParent()->isDependentType())
12517 CheckDestructor(Destructor);
12519 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12520 Destructor->getParent());
12523 // If any errors have occurred, clear out any temporaries that may have
12524 // been leftover. This ensures that these temporaries won't be picked up for
12525 // deletion in some later function.
12526 if (getDiagnostics().hasErrorOccurred() ||
12527 getDiagnostics().getSuppressAllDiagnostics()) {
12528 DiscardCleanupsInEvaluationContext();
12530 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12531 !isa<FunctionTemplateDecl>(dcl)) {
12532 // Since the body is valid, issue any analysis-based warnings that are
12534 ActivePolicy = &WP;
12537 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12538 (!CheckConstexprFunctionDecl(FD) ||
12539 !CheckConstexprFunctionBody(FD, Body)))
12540 FD->setInvalidDecl();
12542 if (FD && FD->hasAttr<NakedAttr>()) {
12543 for (const Stmt *S : Body->children()) {
12544 // Allow local register variables without initializer as they don't
12545 // require prologue.
12546 bool RegisterVariables = false;
12547 if (auto *DS = dyn_cast<DeclStmt>(S)) {
12548 for (const auto *Decl : DS->decls()) {
12549 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12550 RegisterVariables =
12551 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12552 if (!RegisterVariables)
12557 if (RegisterVariables)
12559 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12560 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12561 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12562 FD->setInvalidDecl();
12568 assert(ExprCleanupObjects.size() ==
12569 ExprEvalContexts.back().NumCleanupObjects &&
12570 "Leftover temporaries in function");
12571 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12572 assert(MaybeODRUseExprs.empty() &&
12573 "Leftover expressions for odr-use checking");
12576 if (!IsInstantiation)
12579 PopFunctionScopeInfo(ActivePolicy, dcl);
12580 // If any errors have occurred, clear out any temporaries that may have
12581 // been leftover. This ensures that these temporaries won't be picked up for
12582 // deletion in some later function.
12583 if (getDiagnostics().hasErrorOccurred()) {
12584 DiscardCleanupsInEvaluationContext();
12590 /// When we finish delayed parsing of an attribute, we must attach it to the
12592 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12593 ParsedAttributes &Attrs) {
12594 // Always attach attributes to the underlying decl.
12595 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12596 D = TD->getTemplatedDecl();
12597 ProcessDeclAttributeList(S, D, Attrs.getList());
12599 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12600 if (Method->isStatic())
12601 checkThisInStaticMemberFunctionAttributes(Method);
12604 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12605 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12606 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12607 IdentifierInfo &II, Scope *S) {
12608 // Before we produce a declaration for an implicitly defined
12609 // function, see whether there was a locally-scoped declaration of
12610 // this name as a function or variable. If so, use that
12611 // (non-visible) declaration, and complain about it.
12612 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12613 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12614 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12615 return ExternCPrev;
12618 // Extension in C99. Legal in C90, but warn about it.
12620 if (II.getName().startswith("__builtin_"))
12621 diag_id = diag::warn_builtin_unknown;
12622 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12623 else if (getLangOpts().OpenCL)
12624 diag_id = diag::err_opencl_implicit_function_decl;
12625 else if (getLangOpts().C99)
12626 diag_id = diag::ext_implicit_function_decl;
12628 diag_id = diag::warn_implicit_function_decl;
12629 Diag(Loc, diag_id) << &II;
12631 // Because typo correction is expensive, only do it if the implicit
12632 // function declaration is going to be treated as an error.
12633 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12634 TypoCorrection Corrected;
12636 (Corrected = CorrectTypo(
12637 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12638 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12639 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12640 /*ErrorRecovery*/false);
12643 // Set a Declarator for the implicit definition: int foo();
12645 AttributeFactory attrFactory;
12646 DeclSpec DS(attrFactory);
12648 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12649 Context.getPrintingPolicy());
12650 (void)Error; // Silence warning.
12651 assert(!Error && "Error setting up implicit decl!");
12652 SourceLocation NoLoc;
12653 Declarator D(DS, Declarator::BlockContext);
12654 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12655 /*IsAmbiguous=*/false,
12656 /*LParenLoc=*/NoLoc,
12657 /*Params=*/nullptr,
12659 /*EllipsisLoc=*/NoLoc,
12660 /*RParenLoc=*/NoLoc,
12662 /*RefQualifierIsLvalueRef=*/true,
12663 /*RefQualifierLoc=*/NoLoc,
12664 /*ConstQualifierLoc=*/NoLoc,
12665 /*VolatileQualifierLoc=*/NoLoc,
12666 /*RestrictQualifierLoc=*/NoLoc,
12667 /*MutableLoc=*/NoLoc,
12669 /*ESpecRange=*/SourceRange(),
12670 /*Exceptions=*/nullptr,
12671 /*ExceptionRanges=*/nullptr,
12672 /*NumExceptions=*/0,
12673 /*NoexceptExpr=*/nullptr,
12674 /*ExceptionSpecTokens=*/nullptr,
12675 /*DeclsInPrototype=*/None,
12677 DS.getAttributes(),
12679 D.SetIdentifier(&II, Loc);
12681 // Insert this function into translation-unit scope.
12683 DeclContext *PrevDC = CurContext;
12684 CurContext = Context.getTranslationUnitDecl();
12686 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12689 CurContext = PrevDC;
12691 AddKnownFunctionAttributes(FD);
12696 /// \brief Adds any function attributes that we know a priori based on
12697 /// the declaration of this function.
12699 /// These attributes can apply both to implicitly-declared builtins
12700 /// (like __builtin___printf_chk) or to library-declared functions
12701 /// like NSLog or printf.
12703 /// We need to check for duplicate attributes both here and where user-written
12704 /// attributes are applied to declarations.
12705 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12706 if (FD->isInvalidDecl())
12709 // If this is a built-in function, map its builtin attributes to
12710 // actual attributes.
12711 if (unsigned BuiltinID = FD->getBuiltinID()) {
12712 // Handle printf-formatting attributes.
12713 unsigned FormatIdx;
12715 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12716 if (!FD->hasAttr<FormatAttr>()) {
12717 const char *fmt = "printf";
12718 unsigned int NumParams = FD->getNumParams();
12719 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12720 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12722 FD->addAttr(FormatAttr::CreateImplicit(Context,
12723 &Context.Idents.get(fmt),
12725 HasVAListArg ? 0 : FormatIdx+2,
12726 FD->getLocation()));
12729 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12731 if (!FD->hasAttr<FormatAttr>())
12732 FD->addAttr(FormatAttr::CreateImplicit(Context,
12733 &Context.Idents.get("scanf"),
12735 HasVAListArg ? 0 : FormatIdx+2,
12736 FD->getLocation()));
12739 // Mark const if we don't care about errno and that is the only
12740 // thing preventing the function from being const. This allows
12741 // IRgen to use LLVM intrinsics for such functions.
12742 if (!getLangOpts().MathErrno &&
12743 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12744 if (!FD->hasAttr<ConstAttr>())
12745 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12748 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12749 !FD->hasAttr<ReturnsTwiceAttr>())
12750 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12751 FD->getLocation()));
12752 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12753 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12754 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12755 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12756 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12757 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12758 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12759 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12760 // Add the appropriate attribute, depending on the CUDA compilation mode
12761 // and which target the builtin belongs to. For example, during host
12762 // compilation, aux builtins are __device__, while the rest are __host__.
12763 if (getLangOpts().CUDAIsDevice !=
12764 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12765 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12767 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12771 // If C++ exceptions are enabled but we are told extern "C" functions cannot
12772 // throw, add an implicit nothrow attribute to any extern "C" function we come
12774 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12775 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12776 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12777 if (!FPT || FPT->getExceptionSpecType() == EST_None)
12778 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12781 IdentifierInfo *Name = FD->getIdentifier();
12784 if ((!getLangOpts().CPlusPlus &&
12785 FD->getDeclContext()->isTranslationUnit()) ||
12786 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12787 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12788 LinkageSpecDecl::lang_c)) {
12789 // Okay: this could be a libc/libm/Objective-C function we know
12794 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12795 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12796 // target-specific builtins, perhaps?
12797 if (!FD->hasAttr<FormatAttr>())
12798 FD->addAttr(FormatAttr::CreateImplicit(Context,
12799 &Context.Idents.get("printf"), 2,
12800 Name->isStr("vasprintf") ? 0 : 3,
12801 FD->getLocation()));
12804 if (Name->isStr("__CFStringMakeConstantString")) {
12805 // We already have a __builtin___CFStringMakeConstantString,
12806 // but builds that use -fno-constant-cfstrings don't go through that.
12807 if (!FD->hasAttr<FormatArgAttr>())
12808 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12809 FD->getLocation()));
12813 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12814 TypeSourceInfo *TInfo) {
12815 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12816 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12819 assert(D.isInvalidType() && "no declarator info for valid type");
12820 TInfo = Context.getTrivialTypeSourceInfo(T);
12823 // Scope manipulation handled by caller.
12824 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12826 D.getIdentifierLoc(),
12830 // Bail out immediately if we have an invalid declaration.
12831 if (D.isInvalidType()) {
12832 NewTD->setInvalidDecl();
12836 if (D.getDeclSpec().isModulePrivateSpecified()) {
12837 if (CurContext->isFunctionOrMethod())
12838 Diag(NewTD->getLocation(), diag::err_module_private_local)
12839 << 2 << NewTD->getDeclName()
12840 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12841 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12843 NewTD->setModulePrivate();
12846 // C++ [dcl.typedef]p8:
12847 // If the typedef declaration defines an unnamed class (or
12848 // enum), the first typedef-name declared by the declaration
12849 // to be that class type (or enum type) is used to denote the
12850 // class type (or enum type) for linkage purposes only.
12851 // We need to check whether the type was declared in the declaration.
12852 switch (D.getDeclSpec().getTypeSpecType()) {
12855 case TST_interface:
12858 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12859 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12870 /// \brief Check that this is a valid underlying type for an enum declaration.
12871 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12872 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12873 QualType T = TI->getType();
12875 if (T->isDependentType())
12878 if (const BuiltinType *BT = T->getAs<BuiltinType>())
12879 if (BT->isInteger())
12882 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12886 /// Check whether this is a valid redeclaration of a previous enumeration.
12887 /// \return true if the redeclaration was invalid.
12888 bool Sema::CheckEnumRedeclaration(
12889 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12890 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12891 bool IsFixed = !EnumUnderlyingTy.isNull();
12893 if (IsScoped != Prev->isScoped()) {
12894 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12895 << Prev->isScoped();
12896 Diag(Prev->getLocation(), diag::note_previous_declaration);
12900 if (IsFixed && Prev->isFixed()) {
12901 if (!EnumUnderlyingTy->isDependentType() &&
12902 !Prev->getIntegerType()->isDependentType() &&
12903 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12904 Prev->getIntegerType())) {
12905 // TODO: Highlight the underlying type of the redeclaration.
12906 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12907 << EnumUnderlyingTy << Prev->getIntegerType();
12908 Diag(Prev->getLocation(), diag::note_previous_declaration)
12909 << Prev->getIntegerTypeRange();
12912 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12914 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12916 } else if (IsFixed != Prev->isFixed()) {
12917 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12918 << Prev->isFixed();
12919 Diag(Prev->getLocation(), diag::note_previous_declaration);
12926 /// \brief Get diagnostic %select index for tag kind for
12927 /// redeclaration diagnostic message.
12928 /// WARNING: Indexes apply to particular diagnostics only!
12930 /// \returns diagnostic %select index.
12931 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12933 case TTK_Struct: return 0;
12934 case TTK_Interface: return 1;
12935 case TTK_Class: return 2;
12936 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12940 /// \brief Determine if tag kind is a class-key compatible with
12941 /// class for redeclaration (class, struct, or __interface).
12943 /// \returns true iff the tag kind is compatible.
12944 static bool isClassCompatTagKind(TagTypeKind Tag)
12946 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12949 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12951 if (isa<TypedefDecl>(PrevDecl))
12952 return NTK_Typedef;
12953 else if (isa<TypeAliasDecl>(PrevDecl))
12954 return NTK_TypeAlias;
12955 else if (isa<ClassTemplateDecl>(PrevDecl))
12956 return NTK_Template;
12957 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12958 return NTK_TypeAliasTemplate;
12959 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12960 return NTK_TemplateTemplateArgument;
12963 case TTK_Interface:
12965 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12967 return NTK_NonUnion;
12969 return NTK_NonEnum;
12971 llvm_unreachable("invalid TTK");
12974 /// \brief Determine whether a tag with a given kind is acceptable
12975 /// as a redeclaration of the given tag declaration.
12977 /// \returns true if the new tag kind is acceptable, false otherwise.
12978 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12979 TagTypeKind NewTag, bool isDefinition,
12980 SourceLocation NewTagLoc,
12981 const IdentifierInfo *Name) {
12982 // C++ [dcl.type.elab]p3:
12983 // The class-key or enum keyword present in the
12984 // elaborated-type-specifier shall agree in kind with the
12985 // declaration to which the name in the elaborated-type-specifier
12986 // refers. This rule also applies to the form of
12987 // elaborated-type-specifier that declares a class-name or
12988 // friend class since it can be construed as referring to the
12989 // definition of the class. Thus, in any
12990 // elaborated-type-specifier, the enum keyword shall be used to
12991 // refer to an enumeration (7.2), the union class-key shall be
12992 // used to refer to a union (clause 9), and either the class or
12993 // struct class-key shall be used to refer to a class (clause 9)
12994 // declared using the class or struct class-key.
12995 TagTypeKind OldTag = Previous->getTagKind();
12996 if (!isDefinition || !isClassCompatTagKind(NewTag))
12997 if (OldTag == NewTag)
13000 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13001 // Warn about the struct/class tag mismatch.
13002 bool isTemplate = false;
13003 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13004 isTemplate = Record->getDescribedClassTemplate();
13006 if (inTemplateInstantiation()) {
13007 // In a template instantiation, do not offer fix-its for tag mismatches
13008 // since they usually mess up the template instead of fixing the problem.
13009 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13010 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13011 << getRedeclDiagFromTagKind(OldTag);
13015 if (isDefinition) {
13016 // On definitions, check previous tags and issue a fix-it for each
13017 // one that doesn't match the current tag.
13018 if (Previous->getDefinition()) {
13019 // Don't suggest fix-its for redefinitions.
13023 bool previousMismatch = false;
13024 for (auto I : Previous->redecls()) {
13025 if (I->getTagKind() != NewTag) {
13026 if (!previousMismatch) {
13027 previousMismatch = true;
13028 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13029 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13030 << getRedeclDiagFromTagKind(I->getTagKind());
13032 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13033 << getRedeclDiagFromTagKind(NewTag)
13034 << FixItHint::CreateReplacement(I->getInnerLocStart(),
13035 TypeWithKeyword::getTagTypeKindName(NewTag));
13041 // Check for a previous definition. If current tag and definition
13042 // are same type, do nothing. If no definition, but disagree with
13043 // with previous tag type, give a warning, but no fix-it.
13044 const TagDecl *Redecl = Previous->getDefinition() ?
13045 Previous->getDefinition() : Previous;
13046 if (Redecl->getTagKind() == NewTag) {
13050 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13051 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13052 << getRedeclDiagFromTagKind(OldTag);
13053 Diag(Redecl->getLocation(), diag::note_previous_use);
13055 // If there is a previous definition, suggest a fix-it.
13056 if (Previous->getDefinition()) {
13057 Diag(NewTagLoc, diag::note_struct_class_suggestion)
13058 << getRedeclDiagFromTagKind(Redecl->getTagKind())
13059 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13060 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13068 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13069 /// from an outer enclosing namespace or file scope inside a friend declaration.
13070 /// This should provide the commented out code in the following snippet:
13074 /// struct Y { friend struct /*N::*/ X; };
13077 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13078 SourceLocation NameLoc) {
13079 // While the decl is in a namespace, do repeated lookup of that name and see
13080 // if we get the same namespace back. If we do not, continue until
13081 // translation unit scope, at which point we have a fully qualified NNS.
13082 SmallVector<IdentifierInfo *, 4> Namespaces;
13083 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13084 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13085 // This tag should be declared in a namespace, which can only be enclosed by
13086 // other namespaces. Bail if there's an anonymous namespace in the chain.
13087 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13088 if (!Namespace || Namespace->isAnonymousNamespace())
13089 return FixItHint();
13090 IdentifierInfo *II = Namespace->getIdentifier();
13091 Namespaces.push_back(II);
13092 NamedDecl *Lookup = SemaRef.LookupSingleName(
13093 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13094 if (Lookup == Namespace)
13098 // Once we have all the namespaces, reverse them to go outermost first, and
13100 SmallString<64> Insertion;
13101 llvm::raw_svector_ostream OS(Insertion);
13102 if (DC->isTranslationUnit())
13104 std::reverse(Namespaces.begin(), Namespaces.end());
13105 for (auto *II : Namespaces)
13106 OS << II->getName() << "::";
13107 return FixItHint::CreateInsertion(NameLoc, Insertion);
13110 /// \brief Determine whether a tag originally declared in context \p OldDC can
13111 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13112 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13113 /// using-declaration).
13114 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13115 DeclContext *NewDC) {
13116 OldDC = OldDC->getRedeclContext();
13117 NewDC = NewDC->getRedeclContext();
13119 if (OldDC->Equals(NewDC))
13122 // In MSVC mode, we allow a redeclaration if the contexts are related (either
13123 // encloses the other).
13124 if (S.getLangOpts().MSVCCompat &&
13125 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13131 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
13132 /// former case, Name will be non-null. In the later case, Name will be null.
13133 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13134 /// reference/declaration/definition of a tag.
13136 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13137 /// trailing-type-specifier) other than one in an alias-declaration.
13139 /// \param SkipBody If non-null, will be set to indicate if the caller should
13140 /// skip the definition of this tag and treat it as if it were a declaration.
13141 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13142 SourceLocation KWLoc, CXXScopeSpec &SS,
13143 IdentifierInfo *Name, SourceLocation NameLoc,
13144 AttributeList *Attr, AccessSpecifier AS,
13145 SourceLocation ModulePrivateLoc,
13146 MultiTemplateParamsArg TemplateParameterLists,
13147 bool &OwnedDecl, bool &IsDependent,
13148 SourceLocation ScopedEnumKWLoc,
13149 bool ScopedEnumUsesClassTag,
13150 TypeResult UnderlyingType,
13151 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13152 SkipBodyInfo *SkipBody) {
13153 // If this is not a definition, it must have a name.
13154 IdentifierInfo *OrigName = Name;
13155 assert((Name != nullptr || TUK == TUK_Definition) &&
13156 "Nameless record must be a definition!");
13157 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13160 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13161 bool ScopedEnum = ScopedEnumKWLoc.isValid();
13163 // FIXME: Check member specializations more carefully.
13164 bool isMemberSpecialization = false;
13165 bool Invalid = false;
13167 // We only need to do this matching if we have template parameters
13168 // or a scope specifier, which also conveniently avoids this work
13169 // for non-C++ cases.
13170 if (TemplateParameterLists.size() > 0 ||
13171 (SS.isNotEmpty() && TUK != TUK_Reference)) {
13172 if (TemplateParameterList *TemplateParams =
13173 MatchTemplateParametersToScopeSpecifier(
13174 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13175 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13176 if (Kind == TTK_Enum) {
13177 Diag(KWLoc, diag::err_enum_template);
13181 if (TemplateParams->size() > 0) {
13182 // This is a declaration or definition of a class template (which may
13183 // be a member of another template).
13189 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13190 SS, Name, NameLoc, Attr,
13191 TemplateParams, AS,
13193 /*FriendLoc*/SourceLocation(),
13194 TemplateParameterLists.size()-1,
13195 TemplateParameterLists.data(),
13197 return Result.get();
13199 // The "template<>" header is extraneous.
13200 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13201 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13202 isMemberSpecialization = true;
13207 // Figure out the underlying type if this a enum declaration. We need to do
13208 // this early, because it's needed to detect if this is an incompatible
13210 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13211 bool EnumUnderlyingIsImplicit = false;
13213 if (Kind == TTK_Enum) {
13214 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13215 // No underlying type explicitly specified, or we failed to parse the
13216 // type, default to int.
13217 EnumUnderlying = Context.IntTy.getTypePtr();
13218 else if (UnderlyingType.get()) {
13219 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13220 // integral type; any cv-qualification is ignored.
13221 TypeSourceInfo *TI = nullptr;
13222 GetTypeFromParser(UnderlyingType.get(), &TI);
13223 EnumUnderlying = TI;
13225 if (CheckEnumUnderlyingType(TI))
13226 // Recover by falling back to int.
13227 EnumUnderlying = Context.IntTy.getTypePtr();
13229 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13230 UPPC_FixedUnderlyingType))
13231 EnumUnderlying = Context.IntTy.getTypePtr();
13233 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13234 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13235 // Microsoft enums are always of int type.
13236 EnumUnderlying = Context.IntTy.getTypePtr();
13237 EnumUnderlyingIsImplicit = true;
13242 DeclContext *SearchDC = CurContext;
13243 DeclContext *DC = CurContext;
13244 bool isStdBadAlloc = false;
13245 bool isStdAlignValT = false;
13247 RedeclarationKind Redecl = ForRedeclaration;
13248 if (TUK == TUK_Friend || TUK == TUK_Reference)
13249 Redecl = NotForRedeclaration;
13251 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13252 /// implemented asks for structural equivalence checking, the returned decl
13253 /// here is passed back to the parser, allowing the tag body to be parsed.
13254 auto createTagFromNewDecl = [&]() -> TagDecl * {
13255 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13256 // If there is an identifier, use the location of the identifier as the
13257 // location of the decl, otherwise use the location of the struct/union
13259 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13260 TagDecl *New = nullptr;
13262 if (Kind == TTK_Enum) {
13263 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13264 ScopedEnum, ScopedEnumUsesClassTag,
13265 !EnumUnderlying.isNull());
13266 // If this is an undefined enum, bail.
13267 if (TUK != TUK_Definition && !Invalid)
13269 if (EnumUnderlying) {
13270 EnumDecl *ED = cast<EnumDecl>(New);
13271 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13272 ED->setIntegerTypeSourceInfo(TI);
13274 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13275 ED->setPromotionType(ED->getIntegerType());
13277 } else { // struct/union
13278 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13282 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13283 // Add alignment attributes if necessary; these attributes are checked
13284 // when the ASTContext lays out the structure.
13286 // It is important for implementing the correct semantics that this
13287 // happen here (in ActOnTag). The #pragma pack stack is
13288 // maintained as a result of parser callbacks which can occur at
13289 // many points during the parsing of a struct declaration (because
13290 // the #pragma tokens are effectively skipped over during the
13291 // parsing of the struct).
13292 if (TUK == TUK_Definition) {
13293 AddAlignmentAttributesForRecord(RD);
13294 AddMsStructLayoutForRecord(RD);
13297 New->setLexicalDeclContext(CurContext);
13301 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13302 if (Name && SS.isNotEmpty()) {
13303 // We have a nested-name tag ('struct foo::bar').
13305 // Check for invalid 'foo::'.
13306 if (SS.isInvalid()) {
13308 goto CreateNewDecl;
13311 // If this is a friend or a reference to a class in a dependent
13312 // context, don't try to make a decl for it.
13313 if (TUK == TUK_Friend || TUK == TUK_Reference) {
13314 DC = computeDeclContext(SS, false);
13316 IsDependent = true;
13320 DC = computeDeclContext(SS, true);
13322 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13328 if (RequireCompleteDeclContext(SS, DC))
13332 // Look-up name inside 'foo::'.
13333 LookupQualifiedName(Previous, DC);
13335 if (Previous.isAmbiguous())
13338 if (Previous.empty()) {
13339 // Name lookup did not find anything. However, if the
13340 // nested-name-specifier refers to the current instantiation,
13341 // and that current instantiation has any dependent base
13342 // classes, we might find something at instantiation time: treat
13343 // this as a dependent elaborated-type-specifier.
13344 // But this only makes any sense for reference-like lookups.
13345 if (Previous.wasNotFoundInCurrentInstantiation() &&
13346 (TUK == TUK_Reference || TUK == TUK_Friend)) {
13347 IsDependent = true;
13351 // A tag 'foo::bar' must already exist.
13352 Diag(NameLoc, diag::err_not_tag_in_scope)
13353 << Kind << Name << DC << SS.getRange();
13356 goto CreateNewDecl;
13359 // C++14 [class.mem]p14:
13360 // If T is the name of a class, then each of the following shall have a
13361 // name different from T:
13362 // -- every member of class T that is itself a type
13363 if (TUK != TUK_Reference && TUK != TUK_Friend &&
13364 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13367 // If this is a named struct, check to see if there was a previous forward
13368 // declaration or definition.
13369 // FIXME: We're looking into outer scopes here, even when we
13370 // shouldn't be. Doing so can result in ambiguities that we
13371 // shouldn't be diagnosing.
13372 LookupName(Previous, S);
13374 // When declaring or defining a tag, ignore ambiguities introduced
13375 // by types using'ed into this scope.
13376 if (Previous.isAmbiguous() &&
13377 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13378 LookupResult::Filter F = Previous.makeFilter();
13379 while (F.hasNext()) {
13380 NamedDecl *ND = F.next();
13381 if (!ND->getDeclContext()->getRedeclContext()->Equals(
13382 SearchDC->getRedeclContext()))
13388 // C++11 [namespace.memdef]p3:
13389 // If the name in a friend declaration is neither qualified nor
13390 // a template-id and the declaration is a function or an
13391 // elaborated-type-specifier, the lookup to determine whether
13392 // the entity has been previously declared shall not consider
13393 // any scopes outside the innermost enclosing namespace.
13395 // MSVC doesn't implement the above rule for types, so a friend tag
13396 // declaration may be a redeclaration of a type declared in an enclosing
13397 // scope. They do implement this rule for friend functions.
13399 // Does it matter that this should be by scope instead of by
13400 // semantic context?
13401 if (!Previous.empty() && TUK == TUK_Friend) {
13402 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13403 LookupResult::Filter F = Previous.makeFilter();
13404 bool FriendSawTagOutsideEnclosingNamespace = false;
13405 while (F.hasNext()) {
13406 NamedDecl *ND = F.next();
13407 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13408 if (DC->isFileContext() &&
13409 !EnclosingNS->Encloses(ND->getDeclContext())) {
13410 if (getLangOpts().MSVCCompat)
13411 FriendSawTagOutsideEnclosingNamespace = true;
13418 // Diagnose this MSVC extension in the easy case where lookup would have
13419 // unambiguously found something outside the enclosing namespace.
13420 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13421 NamedDecl *ND = Previous.getFoundDecl();
13422 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13423 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13427 // Note: there used to be some attempt at recovery here.
13428 if (Previous.isAmbiguous())
13431 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13432 // FIXME: This makes sure that we ignore the contexts associated
13433 // with C structs, unions, and enums when looking for a matching
13434 // tag declaration or definition. See the similar lookup tweak
13435 // in Sema::LookupName; is there a better way to deal with this?
13436 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13437 SearchDC = SearchDC->getParent();
13441 if (Previous.isSingleResult() &&
13442 Previous.getFoundDecl()->isTemplateParameter()) {
13443 // Maybe we will complain about the shadowed template parameter.
13444 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13445 // Just pretend that we didn't see the previous declaration.
13449 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13450 DC->Equals(getStdNamespace())) {
13451 if (Name->isStr("bad_alloc")) {
13452 // This is a declaration of or a reference to "std::bad_alloc".
13453 isStdBadAlloc = true;
13455 // If std::bad_alloc has been implicitly declared (but made invisible to
13456 // name lookup), fill in this implicit declaration as the previous
13457 // declaration, so that the declarations get chained appropriately.
13458 if (Previous.empty() && StdBadAlloc)
13459 Previous.addDecl(getStdBadAlloc());
13460 } else if (Name->isStr("align_val_t")) {
13461 isStdAlignValT = true;
13462 if (Previous.empty() && StdAlignValT)
13463 Previous.addDecl(getStdAlignValT());
13467 // If we didn't find a previous declaration, and this is a reference
13468 // (or friend reference), move to the correct scope. In C++, we
13469 // also need to do a redeclaration lookup there, just in case
13470 // there's a shadow friend decl.
13471 if (Name && Previous.empty() &&
13472 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13473 if (Invalid) goto CreateNewDecl;
13474 assert(SS.isEmpty());
13476 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13477 // C++ [basic.scope.pdecl]p5:
13478 // -- for an elaborated-type-specifier of the form
13480 // class-key identifier
13482 // if the elaborated-type-specifier is used in the
13483 // decl-specifier-seq or parameter-declaration-clause of a
13484 // function defined in namespace scope, the identifier is
13485 // declared as a class-name in the namespace that contains
13486 // the declaration; otherwise, except as a friend
13487 // declaration, the identifier is declared in the smallest
13488 // non-class, non-function-prototype scope that contains the
13491 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13492 // C structs and unions.
13494 // It is an error in C++ to declare (rather than define) an enum
13495 // type, including via an elaborated type specifier. We'll
13496 // diagnose that later; for now, declare the enum in the same
13497 // scope as we would have picked for any other tag type.
13499 // GNU C also supports this behavior as part of its incomplete
13500 // enum types extension, while GNU C++ does not.
13502 // Find the context where we'll be declaring the tag.
13503 // FIXME: We would like to maintain the current DeclContext as the
13504 // lexical context,
13505 SearchDC = getTagInjectionContext(SearchDC);
13507 // Find the scope where we'll be declaring the tag.
13508 S = getTagInjectionScope(S, getLangOpts());
13510 assert(TUK == TUK_Friend);
13511 // C++ [namespace.memdef]p3:
13512 // If a friend declaration in a non-local class first declares a
13513 // class or function, the friend class or function is a member of
13514 // the innermost enclosing namespace.
13515 SearchDC = SearchDC->getEnclosingNamespaceContext();
13518 // In C++, we need to do a redeclaration lookup to properly
13519 // diagnose some problems.
13520 // FIXME: redeclaration lookup is also used (with and without C++) to find a
13521 // hidden declaration so that we don't get ambiguity errors when using a
13522 // type declared by an elaborated-type-specifier. In C that is not correct
13523 // and we should instead merge compatible types found by lookup.
13524 if (getLangOpts().CPlusPlus) {
13525 Previous.setRedeclarationKind(ForRedeclaration);
13526 LookupQualifiedName(Previous, SearchDC);
13528 Previous.setRedeclarationKind(ForRedeclaration);
13529 LookupName(Previous, S);
13533 // If we have a known previous declaration to use, then use it.
13534 if (Previous.empty() && SkipBody && SkipBody->Previous)
13535 Previous.addDecl(SkipBody->Previous);
13537 if (!Previous.empty()) {
13538 NamedDecl *PrevDecl = Previous.getFoundDecl();
13539 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13541 // It's okay to have a tag decl in the same scope as a typedef
13542 // which hides a tag decl in the same scope. Finding this
13543 // insanity with a redeclaration lookup can only actually happen
13546 // This is also okay for elaborated-type-specifiers, which is
13547 // technically forbidden by the current standard but which is
13548 // okay according to the likely resolution of an open issue;
13549 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13550 if (getLangOpts().CPlusPlus) {
13551 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13552 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13553 TagDecl *Tag = TT->getDecl();
13554 if (Tag->getDeclName() == Name &&
13555 Tag->getDeclContext()->getRedeclContext()
13556 ->Equals(TD->getDeclContext()->getRedeclContext())) {
13559 Previous.addDecl(Tag);
13560 Previous.resolveKind();
13566 // If this is a redeclaration of a using shadow declaration, it must
13567 // declare a tag in the same context. In MSVC mode, we allow a
13568 // redefinition if either context is within the other.
13569 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13570 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13571 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13572 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13573 !(OldTag && isAcceptableTagRedeclContext(
13574 *this, OldTag->getDeclContext(), SearchDC))) {
13575 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13576 Diag(Shadow->getTargetDecl()->getLocation(),
13577 diag::note_using_decl_target);
13578 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13580 // Recover by ignoring the old declaration.
13582 goto CreateNewDecl;
13586 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13587 // If this is a use of a previous tag, or if the tag is already declared
13588 // in the same scope (so that the definition/declaration completes or
13589 // rementions the tag), reuse the decl.
13590 if (TUK == TUK_Reference || TUK == TUK_Friend ||
13591 isDeclInScope(DirectPrevDecl, SearchDC, S,
13592 SS.isNotEmpty() || isMemberSpecialization)) {
13593 // Make sure that this wasn't declared as an enum and now used as a
13594 // struct or something similar.
13595 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13596 TUK == TUK_Definition, KWLoc,
13598 bool SafeToContinue
13599 = (PrevTagDecl->getTagKind() != TTK_Enum &&
13601 if (SafeToContinue)
13602 Diag(KWLoc, diag::err_use_with_wrong_tag)
13604 << FixItHint::CreateReplacement(SourceRange(KWLoc),
13605 PrevTagDecl->getKindName());
13607 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13608 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13610 if (SafeToContinue)
13611 Kind = PrevTagDecl->getTagKind();
13613 // Recover by making this an anonymous redefinition.
13620 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13621 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13623 // If this is an elaborated-type-specifier for a scoped enumeration,
13624 // the 'class' keyword is not necessary and not permitted.
13625 if (TUK == TUK_Reference || TUK == TUK_Friend) {
13627 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13628 << PrevEnum->isScoped()
13629 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13630 return PrevTagDecl;
13633 QualType EnumUnderlyingTy;
13634 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13635 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13636 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13637 EnumUnderlyingTy = QualType(T, 0);
13639 // All conflicts with previous declarations are recovered by
13640 // returning the previous declaration, unless this is a definition,
13641 // in which case we want the caller to bail out.
13642 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13643 ScopedEnum, EnumUnderlyingTy,
13644 EnumUnderlyingIsImplicit, PrevEnum))
13645 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13648 // C++11 [class.mem]p1:
13649 // A member shall not be declared twice in the member-specification,
13650 // except that a nested class or member class template can be declared
13651 // and then later defined.
13652 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13653 S->isDeclScope(PrevDecl)) {
13654 Diag(NameLoc, diag::ext_member_redeclared);
13655 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13659 // If this is a use, just return the declaration we found, unless
13660 // we have attributes.
13661 if (TUK == TUK_Reference || TUK == TUK_Friend) {
13663 // FIXME: Diagnose these attributes. For now, we create a new
13664 // declaration to hold them.
13665 } else if (TUK == TUK_Reference &&
13666 (PrevTagDecl->getFriendObjectKind() ==
13667 Decl::FOK_Undeclared ||
13668 PrevDecl->getOwningModule() != getCurrentModule()) &&
13670 // This declaration is a reference to an existing entity, but
13671 // has different visibility from that entity: it either makes
13672 // a friend visible or it makes a type visible in a new module.
13673 // In either case, create a new declaration. We only do this if
13674 // the declaration would have meant the same thing if no prior
13675 // declaration were found, that is, if it was found in the same
13676 // scope where we would have injected a declaration.
13677 if (!getTagInjectionContext(CurContext)->getRedeclContext()
13678 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13679 return PrevTagDecl;
13680 // This is in the injected scope, create a new declaration in
13682 S = getTagInjectionScope(S, getLangOpts());
13684 return PrevTagDecl;
13688 // Diagnose attempts to redefine a tag.
13689 if (TUK == TUK_Definition) {
13690 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13691 // If we're defining a specialization and the previous definition
13692 // is from an implicit instantiation, don't emit an error
13693 // here; we'll catch this in the general case below.
13694 bool IsExplicitSpecializationAfterInstantiation = false;
13695 if (isMemberSpecialization) {
13696 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13697 IsExplicitSpecializationAfterInstantiation =
13698 RD->getTemplateSpecializationKind() !=
13699 TSK_ExplicitSpecialization;
13700 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13701 IsExplicitSpecializationAfterInstantiation =
13702 ED->getTemplateSpecializationKind() !=
13703 TSK_ExplicitSpecialization;
13706 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
13707 // not keep more that one definition around (merge them). However,
13708 // ensure the decl passes the structural compatibility check in
13709 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
13710 NamedDecl *Hidden = nullptr;
13711 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
13712 // There is a definition of this tag, but it is not visible. We
13713 // explicitly make use of C++'s one definition rule here, and
13714 // assume that this definition is identical to the hidden one
13715 // we already have. Make the existing definition visible and
13716 // use it in place of this one.
13717 if (!getLangOpts().CPlusPlus) {
13718 // Postpone making the old definition visible until after we
13719 // complete parsing the new one and do the structural
13721 SkipBody->CheckSameAsPrevious = true;
13722 SkipBody->New = createTagFromNewDecl();
13723 SkipBody->Previous = Hidden;
13725 SkipBody->ShouldSkip = true;
13726 makeMergedDefinitionVisible(Hidden);
13729 } else if (!IsExplicitSpecializationAfterInstantiation) {
13730 // A redeclaration in function prototype scope in C isn't
13731 // visible elsewhere, so merely issue a warning.
13732 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13733 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13735 Diag(NameLoc, diag::err_redefinition) << Name;
13736 notePreviousDefinition(Def,
13737 NameLoc.isValid() ? NameLoc : KWLoc);
13738 // If this is a redefinition, recover by making this
13739 // struct be anonymous, which will make any later
13740 // references get the previous definition.
13746 // If the type is currently being defined, complain
13747 // about a nested redefinition.
13748 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13749 if (TD->isBeingDefined()) {
13750 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13751 Diag(PrevTagDecl->getLocation(),
13752 diag::note_previous_definition);
13759 // Okay, this is definition of a previously declared or referenced
13760 // tag. We're going to create a new Decl for it.
13763 // Okay, we're going to make a redeclaration. If this is some kind
13764 // of reference, make sure we build the redeclaration in the same DC
13765 // as the original, and ignore the current access specifier.
13766 if (TUK == TUK_Friend || TUK == TUK_Reference) {
13767 SearchDC = PrevTagDecl->getDeclContext();
13771 // If we get here we have (another) forward declaration or we
13772 // have a definition. Just create a new decl.
13775 // If we get here, this is a definition of a new tag type in a nested
13776 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13777 // new decl/type. We set PrevDecl to NULL so that the entities
13778 // have distinct types.
13781 // If we get here, we're going to create a new Decl. If PrevDecl
13782 // is non-NULL, it's a definition of the tag declared by
13783 // PrevDecl. If it's NULL, we have a new definition.
13785 // Otherwise, PrevDecl is not a tag, but was found with tag
13786 // lookup. This is only actually possible in C++, where a few
13787 // things like templates still live in the tag namespace.
13789 // Use a better diagnostic if an elaborated-type-specifier
13790 // found the wrong kind of type on the first
13791 // (non-redeclaration) lookup.
13792 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13793 !Previous.isForRedeclaration()) {
13794 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13795 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13797 Diag(PrevDecl->getLocation(), diag::note_declared_at);
13800 // Otherwise, only diagnose if the declaration is in scope.
13801 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13802 SS.isNotEmpty() || isMemberSpecialization)) {
13805 // Diagnose implicit declarations introduced by elaborated types.
13806 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13807 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13808 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13809 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13812 // Otherwise it's a declaration. Call out a particularly common
13814 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13816 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13817 Diag(NameLoc, diag::err_tag_definition_of_typedef)
13818 << Name << Kind << TND->getUnderlyingType();
13819 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13822 // Otherwise, diagnose.
13824 // The tag name clashes with something else in the target scope,
13825 // issue an error and recover by making this tag be anonymous.
13826 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13827 notePreviousDefinition(PrevDecl, NameLoc);
13832 // The existing declaration isn't relevant to us; we're in a
13833 // new scope, so clear out the previous declaration.
13840 TagDecl *PrevDecl = nullptr;
13841 if (Previous.isSingleResult())
13842 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13844 // If there is an identifier, use the location of the identifier as the
13845 // location of the decl, otherwise use the location of the struct/union
13847 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13849 // Otherwise, create a new declaration. If there is a previous
13850 // declaration of the same entity, the two will be linked via
13854 bool IsForwardReference = false;
13855 if (Kind == TTK_Enum) {
13856 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13857 // enum X { A, B, C } D; D should chain to X.
13858 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13859 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13860 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13862 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13863 StdAlignValT = cast<EnumDecl>(New);
13865 // If this is an undefined enum, warn.
13866 if (TUK != TUK_Definition && !Invalid) {
13868 if (!EnumUnderlyingIsImplicit &&
13869 (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13870 cast<EnumDecl>(New)->isFixed()) {
13871 // C++0x: 7.2p2: opaque-enum-declaration.
13872 // Conflicts are diagnosed above. Do nothing.
13874 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13875 Diag(Loc, diag::ext_forward_ref_enum_def)
13877 Diag(Def->getLocation(), diag::note_previous_definition);
13879 unsigned DiagID = diag::ext_forward_ref_enum;
13880 if (getLangOpts().MSVCCompat)
13881 DiagID = diag::ext_ms_forward_ref_enum;
13882 else if (getLangOpts().CPlusPlus)
13883 DiagID = diag::err_forward_ref_enum;
13886 // If this is a forward-declared reference to an enumeration, make a
13887 // note of it; we won't actually be introducing the declaration into
13888 // the declaration context.
13889 if (TUK == TUK_Reference)
13890 IsForwardReference = true;
13894 if (EnumUnderlying) {
13895 EnumDecl *ED = cast<EnumDecl>(New);
13896 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13897 ED->setIntegerTypeSourceInfo(TI);
13899 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13900 ED->setPromotionType(ED->getIntegerType());
13903 // struct/union/class
13905 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13906 // struct X { int A; } D; D should chain to X.
13907 if (getLangOpts().CPlusPlus) {
13908 // FIXME: Look for a way to use RecordDecl for simple structs.
13909 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13910 cast_or_null<CXXRecordDecl>(PrevDecl));
13912 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13913 StdBadAlloc = cast<CXXRecordDecl>(New);
13915 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13916 cast_or_null<RecordDecl>(PrevDecl));
13919 // C++11 [dcl.type]p3:
13920 // A type-specifier-seq shall not define a class or enumeration [...].
13921 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
13922 TUK == TUK_Definition) {
13923 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13924 << Context.getTagDeclType(New);
13928 // Maybe add qualifier info.
13929 if (SS.isNotEmpty()) {
13931 // If this is either a declaration or a definition, check the
13932 // nested-name-specifier against the current context. We don't do this
13933 // for explicit specializations, because they have similar checking
13934 // (with more specific diagnostics) in the call to
13935 // CheckMemberSpecialization, below.
13936 if (!isMemberSpecialization &&
13937 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13938 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13941 New->setQualifierInfo(SS.getWithLocInContext(Context));
13942 if (TemplateParameterLists.size() > 0) {
13943 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13950 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13951 // Add alignment attributes if necessary; these attributes are checked when
13952 // the ASTContext lays out the structure.
13954 // It is important for implementing the correct semantics that this
13955 // happen here (in ActOnTag). The #pragma pack stack is
13956 // maintained as a result of parser callbacks which can occur at
13957 // many points during the parsing of a struct declaration (because
13958 // the #pragma tokens are effectively skipped over during the
13959 // parsing of the struct).
13960 if (TUK == TUK_Definition) {
13961 AddAlignmentAttributesForRecord(RD);
13962 AddMsStructLayoutForRecord(RD);
13966 if (ModulePrivateLoc.isValid()) {
13967 if (isMemberSpecialization)
13968 Diag(New->getLocation(), diag::err_module_private_specialization)
13970 << FixItHint::CreateRemoval(ModulePrivateLoc);
13971 // __module_private__ does not apply to local classes. However, we only
13972 // diagnose this as an error when the declaration specifiers are
13973 // freestanding. Here, we just ignore the __module_private__.
13974 else if (!SearchDC->isFunctionOrMethod())
13975 New->setModulePrivate();
13978 // If this is a specialization of a member class (of a class template),
13979 // check the specialization.
13980 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13983 // If we're declaring or defining a tag in function prototype scope in C,
13984 // note that this type can only be used within the function and add it to
13985 // the list of decls to inject into the function definition scope.
13986 if ((Name || Kind == TTK_Enum) &&
13987 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13988 if (getLangOpts().CPlusPlus) {
13989 // C++ [dcl.fct]p6:
13990 // Types shall not be defined in return or parameter types.
13991 if (TUK == TUK_Definition && !IsTypeSpecifier) {
13992 Diag(Loc, diag::err_type_defined_in_param_type)
13996 } else if (!PrevDecl) {
13997 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14002 New->setInvalidDecl();
14004 // Set the lexical context. If the tag has a C++ scope specifier, the
14005 // lexical context will be different from the semantic context.
14006 New->setLexicalDeclContext(CurContext);
14008 // Mark this as a friend decl if applicable.
14009 // In Microsoft mode, a friend declaration also acts as a forward
14010 // declaration so we always pass true to setObjectOfFriendDecl to make
14011 // the tag name visible.
14012 if (TUK == TUK_Friend)
14013 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14015 // Set the access specifier.
14016 if (!Invalid && SearchDC->isRecord())
14017 SetMemberAccessSpecifier(New, PrevDecl, AS);
14019 if (TUK == TUK_Definition)
14020 New->startDefinition();
14023 ProcessDeclAttributeList(S, New, Attr);
14024 AddPragmaAttributes(S, New);
14026 // If this has an identifier, add it to the scope stack.
14027 if (TUK == TUK_Friend) {
14028 // We might be replacing an existing declaration in the lookup tables;
14029 // if so, borrow its access specifier.
14031 New->setAccess(PrevDecl->getAccess());
14033 DeclContext *DC = New->getDeclContext()->getRedeclContext();
14034 DC->makeDeclVisibleInContext(New);
14035 if (Name) // can be null along some error paths
14036 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14037 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14039 S = getNonFieldDeclScope(S);
14040 PushOnScopeChains(New, S, !IsForwardReference);
14041 if (IsForwardReference)
14042 SearchDC->makeDeclVisibleInContext(New);
14044 CurContext->addDecl(New);
14047 // If this is the C FILE type, notify the AST context.
14048 if (IdentifierInfo *II = New->getIdentifier())
14049 if (!New->isInvalidDecl() &&
14050 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14052 Context.setFILEDecl(New);
14055 mergeDeclAttributes(New, PrevDecl);
14057 // If there's a #pragma GCC visibility in scope, set the visibility of this
14059 AddPushedVisibilityAttribute(New);
14061 if (isMemberSpecialization && !New->isInvalidDecl())
14062 CompleteMemberSpecialization(New, Previous);
14065 // In C++, don't return an invalid declaration. We can't recover well from
14066 // the cases where we make the type anonymous.
14067 if (Invalid && getLangOpts().CPlusPlus) {
14068 if (New->isBeingDefined())
14069 if (auto RD = dyn_cast<RecordDecl>(New))
14070 RD->completeDefinition();
14077 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14078 AdjustDeclIfTemplate(TagD);
14079 TagDecl *Tag = cast<TagDecl>(TagD);
14081 // Enter the tag context.
14082 PushDeclContext(S, Tag);
14084 ActOnDocumentableDecl(TagD);
14086 // If there's a #pragma GCC visibility in scope, set the visibility of this
14088 AddPushedVisibilityAttribute(Tag);
14091 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14092 SkipBodyInfo &SkipBody) {
14093 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14096 // Make the previous decl visible.
14097 makeMergedDefinitionVisible(SkipBody.Previous);
14101 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14102 assert(isa<ObjCContainerDecl>(IDecl) &&
14103 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14104 DeclContext *OCD = cast<DeclContext>(IDecl);
14105 assert(getContainingDC(OCD) == CurContext &&
14106 "The next DeclContext should be lexically contained in the current one.");
14111 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14112 SourceLocation FinalLoc,
14113 bool IsFinalSpelledSealed,
14114 SourceLocation LBraceLoc) {
14115 AdjustDeclIfTemplate(TagD);
14116 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14118 FieldCollector->StartClass();
14120 if (!Record->getIdentifier())
14123 if (FinalLoc.isValid())
14124 Record->addAttr(new (Context)
14125 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14128 // [...] The class-name is also inserted into the scope of the
14129 // class itself; this is known as the injected-class-name. For
14130 // purposes of access checking, the injected-class-name is treated
14131 // as if it were a public member name.
14132 CXXRecordDecl *InjectedClassName
14133 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14134 Record->getLocStart(), Record->getLocation(),
14135 Record->getIdentifier(),
14136 /*PrevDecl=*/nullptr,
14137 /*DelayTypeCreation=*/true);
14138 Context.getTypeDeclType(InjectedClassName, Record);
14139 InjectedClassName->setImplicit();
14140 InjectedClassName->setAccess(AS_public);
14141 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14142 InjectedClassName->setDescribedClassTemplate(Template);
14143 PushOnScopeChains(InjectedClassName, S);
14144 assert(InjectedClassName->isInjectedClassName() &&
14145 "Broken injected-class-name");
14148 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14149 SourceRange BraceRange) {
14150 AdjustDeclIfTemplate(TagD);
14151 TagDecl *Tag = cast<TagDecl>(TagD);
14152 Tag->setBraceRange(BraceRange);
14154 // Make sure we "complete" the definition even it is invalid.
14155 if (Tag->isBeingDefined()) {
14156 assert(Tag->isInvalidDecl() && "We should already have completed it");
14157 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14158 RD->completeDefinition();
14161 if (isa<CXXRecordDecl>(Tag)) {
14162 FieldCollector->FinishClass();
14165 // Exit this scope of this tag's definition.
14168 if (getCurLexicalContext()->isObjCContainer() &&
14169 Tag->getDeclContext()->isFileContext())
14170 Tag->setTopLevelDeclInObjCContainer();
14172 // Notify the consumer that we've defined a tag.
14173 if (!Tag->isInvalidDecl())
14174 Consumer.HandleTagDeclDefinition(Tag);
14177 void Sema::ActOnObjCContainerFinishDefinition() {
14178 // Exit this scope of this interface definition.
14182 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14183 assert(DC == CurContext && "Mismatch of container contexts");
14184 OriginalLexicalContext = DC;
14185 ActOnObjCContainerFinishDefinition();
14188 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14189 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14190 OriginalLexicalContext = nullptr;
14193 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14194 AdjustDeclIfTemplate(TagD);
14195 TagDecl *Tag = cast<TagDecl>(TagD);
14196 Tag->setInvalidDecl();
14198 // Make sure we "complete" the definition even it is invalid.
14199 if (Tag->isBeingDefined()) {
14200 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14201 RD->completeDefinition();
14204 // We're undoing ActOnTagStartDefinition here, not
14205 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14206 // the FieldCollector.
14211 // Note that FieldName may be null for anonymous bitfields.
14212 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14213 IdentifierInfo *FieldName,
14214 QualType FieldTy, bool IsMsStruct,
14215 Expr *BitWidth, bool *ZeroWidth) {
14216 // Default to true; that shouldn't confuse checks for emptiness
14220 // C99 6.7.2.1p4 - verify the field type.
14221 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14222 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14223 // Handle incomplete types with specific error.
14224 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14225 return ExprError();
14227 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14228 << FieldName << FieldTy << BitWidth->getSourceRange();
14229 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14230 << FieldTy << BitWidth->getSourceRange();
14231 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14232 UPPC_BitFieldWidth))
14233 return ExprError();
14235 // If the bit-width is type- or value-dependent, don't try to check
14237 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14240 llvm::APSInt Value;
14241 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14242 if (ICE.isInvalid())
14244 BitWidth = ICE.get();
14246 if (Value != 0 && ZeroWidth)
14247 *ZeroWidth = false;
14249 // Zero-width bitfield is ok for anonymous field.
14250 if (Value == 0 && FieldName)
14251 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14253 if (Value.isSigned() && Value.isNegative()) {
14255 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14256 << FieldName << Value.toString(10);
14257 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14258 << Value.toString(10);
14261 if (!FieldTy->isDependentType()) {
14262 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14263 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14264 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14266 // Over-wide bitfields are an error in C or when using the MSVC bitfield
14268 bool CStdConstraintViolation =
14269 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14270 bool MSBitfieldViolation =
14271 Value.ugt(TypeStorageSize) &&
14272 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14273 if (CStdConstraintViolation || MSBitfieldViolation) {
14274 unsigned DiagWidth =
14275 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14277 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14278 << FieldName << (unsigned)Value.getZExtValue()
14279 << !CStdConstraintViolation << DiagWidth;
14281 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14282 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14286 // Warn on types where the user might conceivably expect to get all
14287 // specified bits as value bits: that's all integral types other than
14289 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14291 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14292 << FieldName << (unsigned)Value.getZExtValue()
14293 << (unsigned)TypeWidth;
14295 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14296 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14303 /// ActOnField - Each field of a C struct/union is passed into this in order
14304 /// to create a FieldDecl object for it.
14305 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14306 Declarator &D, Expr *BitfieldWidth) {
14307 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14308 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14309 /*InitStyle=*/ICIS_NoInit, AS_public);
14313 /// HandleField - Analyze a field of a C struct or a C++ data member.
14315 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14316 SourceLocation DeclStart,
14317 Declarator &D, Expr *BitWidth,
14318 InClassInitStyle InitStyle,
14319 AccessSpecifier AS) {
14320 if (D.isDecompositionDeclarator()) {
14321 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14322 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14323 << Decomp.getSourceRange();
14327 IdentifierInfo *II = D.getIdentifier();
14328 SourceLocation Loc = DeclStart;
14329 if (II) Loc = D.getIdentifierLoc();
14331 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14332 QualType T = TInfo->getType();
14333 if (getLangOpts().CPlusPlus) {
14334 CheckExtraCXXDefaultArguments(D);
14336 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14337 UPPC_DataMemberType)) {
14338 D.setInvalidType();
14340 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14344 // TR 18037 does not allow fields to be declared with address spaces.
14345 if (T.getQualifiers().hasAddressSpace()) {
14346 Diag(Loc, diag::err_field_with_address_space);
14347 D.setInvalidType();
14350 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14351 // used as structure or union field: image, sampler, event or block types.
14352 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14353 T->isSamplerT() || T->isBlockPointerType())) {
14354 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14355 D.setInvalidType();
14358 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14360 if (D.getDeclSpec().isInlineSpecified())
14361 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14362 << getLangOpts().CPlusPlus1z;
14363 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14364 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14365 diag::err_invalid_thread)
14366 << DeclSpec::getSpecifierName(TSCS);
14368 // Check to see if this name was declared as a member previously
14369 NamedDecl *PrevDecl = nullptr;
14370 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14371 LookupName(Previous, S);
14372 switch (Previous.getResultKind()) {
14373 case LookupResult::Found:
14374 case LookupResult::FoundUnresolvedValue:
14375 PrevDecl = Previous.getAsSingle<NamedDecl>();
14378 case LookupResult::FoundOverloaded:
14379 PrevDecl = Previous.getRepresentativeDecl();
14382 case LookupResult::NotFound:
14383 case LookupResult::NotFoundInCurrentInstantiation:
14384 case LookupResult::Ambiguous:
14387 Previous.suppressDiagnostics();
14389 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14390 // Maybe we will complain about the shadowed template parameter.
14391 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14392 // Just pretend that we didn't see the previous declaration.
14393 PrevDecl = nullptr;
14396 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14397 PrevDecl = nullptr;
14400 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14401 SourceLocation TSSL = D.getLocStart();
14403 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14404 TSSL, AS, PrevDecl, &D);
14406 if (NewFD->isInvalidDecl())
14407 Record->setInvalidDecl();
14409 if (D.getDeclSpec().isModulePrivateSpecified())
14410 NewFD->setModulePrivate();
14412 if (NewFD->isInvalidDecl() && PrevDecl) {
14413 // Don't introduce NewFD into scope; there's already something
14414 // with the same name in the same scope.
14416 PushOnScopeChains(NewFD, S);
14418 Record->addDecl(NewFD);
14423 /// \brief Build a new FieldDecl and check its well-formedness.
14425 /// This routine builds a new FieldDecl given the fields name, type,
14426 /// record, etc. \p PrevDecl should refer to any previous declaration
14427 /// with the same name and in the same scope as the field to be
14430 /// \returns a new FieldDecl.
14432 /// \todo The Declarator argument is a hack. It will be removed once
14433 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14434 TypeSourceInfo *TInfo,
14435 RecordDecl *Record, SourceLocation Loc,
14436 bool Mutable, Expr *BitWidth,
14437 InClassInitStyle InitStyle,
14438 SourceLocation TSSL,
14439 AccessSpecifier AS, NamedDecl *PrevDecl,
14441 IdentifierInfo *II = Name.getAsIdentifierInfo();
14442 bool InvalidDecl = false;
14443 if (D) InvalidDecl = D->isInvalidType();
14445 // If we receive a broken type, recover by assuming 'int' and
14446 // marking this declaration as invalid.
14448 InvalidDecl = true;
14452 QualType EltTy = Context.getBaseElementType(T);
14453 if (!EltTy->isDependentType()) {
14454 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14455 // Fields of incomplete type force their record to be invalid.
14456 Record->setInvalidDecl();
14457 InvalidDecl = true;
14460 EltTy->isIncompleteType(&Def);
14461 if (Def && Def->isInvalidDecl()) {
14462 Record->setInvalidDecl();
14463 InvalidDecl = true;
14468 // OpenCL v1.2 s6.9.c: bitfields are not supported.
14469 if (BitWidth && getLangOpts().OpenCL) {
14470 Diag(Loc, diag::err_opencl_bitfields);
14471 InvalidDecl = true;
14474 // C99 6.7.2.1p8: A member of a structure or union may have any type other
14475 // than a variably modified type.
14476 if (!InvalidDecl && T->isVariablyModifiedType()) {
14477 bool SizeIsNegative;
14478 llvm::APSInt Oversized;
14480 TypeSourceInfo *FixedTInfo =
14481 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14485 Diag(Loc, diag::warn_illegal_constant_array_size);
14486 TInfo = FixedTInfo;
14487 T = FixedTInfo->getType();
14489 if (SizeIsNegative)
14490 Diag(Loc, diag::err_typecheck_negative_array_size);
14491 else if (Oversized.getBoolValue())
14492 Diag(Loc, diag::err_array_too_large)
14493 << Oversized.toString(10);
14495 Diag(Loc, diag::err_typecheck_field_variable_size);
14496 InvalidDecl = true;
14500 // Fields can not have abstract class types
14501 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14502 diag::err_abstract_type_in_decl,
14503 AbstractFieldType))
14504 InvalidDecl = true;
14506 bool ZeroWidth = false;
14508 BitWidth = nullptr;
14509 // If this is declared as a bit-field, check the bit-field.
14511 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14514 InvalidDecl = true;
14515 BitWidth = nullptr;
14520 // Check that 'mutable' is consistent with the type of the declaration.
14521 if (!InvalidDecl && Mutable) {
14522 unsigned DiagID = 0;
14523 if (T->isReferenceType())
14524 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14525 : diag::err_mutable_reference;
14526 else if (T.isConstQualified())
14527 DiagID = diag::err_mutable_const;
14530 SourceLocation ErrLoc = Loc;
14531 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14532 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14533 Diag(ErrLoc, DiagID);
14534 if (DiagID != diag::ext_mutable_reference) {
14536 InvalidDecl = true;
14541 // C++11 [class.union]p8 (DR1460):
14542 // At most one variant member of a union may have a
14543 // brace-or-equal-initializer.
14544 if (InitStyle != ICIS_NoInit)
14545 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14547 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14548 BitWidth, Mutable, InitStyle);
14550 NewFD->setInvalidDecl();
14552 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14553 Diag(Loc, diag::err_duplicate_member) << II;
14554 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14555 NewFD->setInvalidDecl();
14558 if (!InvalidDecl && getLangOpts().CPlusPlus) {
14559 if (Record->isUnion()) {
14560 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14561 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14562 if (RDecl->getDefinition()) {
14563 // C++ [class.union]p1: An object of a class with a non-trivial
14564 // constructor, a non-trivial copy constructor, a non-trivial
14565 // destructor, or a non-trivial copy assignment operator
14566 // cannot be a member of a union, nor can an array of such
14568 if (CheckNontrivialField(NewFD))
14569 NewFD->setInvalidDecl();
14573 // C++ [class.union]p1: If a union contains a member of reference type,
14574 // the program is ill-formed, except when compiling with MSVC extensions
14576 if (EltTy->isReferenceType()) {
14577 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14578 diag::ext_union_member_of_reference_type :
14579 diag::err_union_member_of_reference_type)
14580 << NewFD->getDeclName() << EltTy;
14581 if (!getLangOpts().MicrosoftExt)
14582 NewFD->setInvalidDecl();
14587 // FIXME: We need to pass in the attributes given an AST
14588 // representation, not a parser representation.
14590 // FIXME: The current scope is almost... but not entirely... correct here.
14591 ProcessDeclAttributes(getCurScope(), NewFD, *D);
14593 if (NewFD->hasAttrs())
14594 CheckAlignasUnderalignment(NewFD);
14597 // In auto-retain/release, infer strong retension for fields of
14598 // retainable type.
14599 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14600 NewFD->setInvalidDecl();
14602 if (T.isObjCGCWeak())
14603 Diag(Loc, diag::warn_attribute_weak_on_field);
14605 NewFD->setAccess(AS);
14609 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14611 assert(getLangOpts().CPlusPlus && "valid check only for C++");
14613 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14616 QualType EltTy = Context.getBaseElementType(FD->getType());
14617 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14618 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14619 if (RDecl->getDefinition()) {
14620 // We check for copy constructors before constructors
14621 // because otherwise we'll never get complaints about
14622 // copy constructors.
14624 CXXSpecialMember member = CXXInvalid;
14625 // We're required to check for any non-trivial constructors. Since the
14626 // implicit default constructor is suppressed if there are any
14627 // user-declared constructors, we just need to check that there is a
14628 // trivial default constructor and a trivial copy constructor. (We don't
14629 // worry about move constructors here, since this is a C++98 check.)
14630 if (RDecl->hasNonTrivialCopyConstructor())
14631 member = CXXCopyConstructor;
14632 else if (!RDecl->hasTrivialDefaultConstructor())
14633 member = CXXDefaultConstructor;
14634 else if (RDecl->hasNonTrivialCopyAssignment())
14635 member = CXXCopyAssignment;
14636 else if (RDecl->hasNonTrivialDestructor())
14637 member = CXXDestructor;
14639 if (member != CXXInvalid) {
14640 if (!getLangOpts().CPlusPlus11 &&
14641 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14642 // Objective-C++ ARC: it is an error to have a non-trivial field of
14643 // a union. However, system headers in Objective-C programs
14644 // occasionally have Objective-C lifetime objects within unions,
14645 // and rather than cause the program to fail, we make those
14646 // members unavailable.
14647 SourceLocation Loc = FD->getLocation();
14648 if (getSourceManager().isInSystemHeader(Loc)) {
14649 if (!FD->hasAttr<UnavailableAttr>())
14650 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14651 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14656 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14657 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14658 diag::err_illegal_union_or_anon_struct_member)
14659 << FD->getParent()->isUnion() << FD->getDeclName() << member;
14660 DiagnoseNontrivial(RDecl, member);
14661 return !getLangOpts().CPlusPlus11;
14669 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14670 /// AST enum value.
14671 static ObjCIvarDecl::AccessControl
14672 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14673 switch (ivarVisibility) {
14674 default: llvm_unreachable("Unknown visitibility kind");
14675 case tok::objc_private: return ObjCIvarDecl::Private;
14676 case tok::objc_public: return ObjCIvarDecl::Public;
14677 case tok::objc_protected: return ObjCIvarDecl::Protected;
14678 case tok::objc_package: return ObjCIvarDecl::Package;
14682 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14683 /// in order to create an IvarDecl object for it.
14684 Decl *Sema::ActOnIvar(Scope *S,
14685 SourceLocation DeclStart,
14686 Declarator &D, Expr *BitfieldWidth,
14687 tok::ObjCKeywordKind Visibility) {
14689 IdentifierInfo *II = D.getIdentifier();
14690 Expr *BitWidth = (Expr*)BitfieldWidth;
14691 SourceLocation Loc = DeclStart;
14692 if (II) Loc = D.getIdentifierLoc();
14694 // FIXME: Unnamed fields can be handled in various different ways, for
14695 // example, unnamed unions inject all members into the struct namespace!
14697 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14698 QualType T = TInfo->getType();
14701 // 6.7.2.1p3, 6.7.2.1p4
14702 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14704 D.setInvalidType();
14711 if (T->isReferenceType()) {
14712 Diag(Loc, diag::err_ivar_reference_type);
14713 D.setInvalidType();
14715 // C99 6.7.2.1p8: A member of a structure or union may have any type other
14716 // than a variably modified type.
14717 else if (T->isVariablyModifiedType()) {
14718 Diag(Loc, diag::err_typecheck_ivar_variable_size);
14719 D.setInvalidType();
14722 // Get the visibility (access control) for this ivar.
14723 ObjCIvarDecl::AccessControl ac =
14724 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14725 : ObjCIvarDecl::None;
14726 // Must set ivar's DeclContext to its enclosing interface.
14727 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14728 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14730 ObjCContainerDecl *EnclosingContext;
14731 if (ObjCImplementationDecl *IMPDecl =
14732 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14733 if (LangOpts.ObjCRuntime.isFragile()) {
14734 // Case of ivar declared in an implementation. Context is that of its class.
14735 EnclosingContext = IMPDecl->getClassInterface();
14736 assert(EnclosingContext && "Implementation has no class interface!");
14739 EnclosingContext = EnclosingDecl;
14741 if (ObjCCategoryDecl *CDecl =
14742 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14743 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14744 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14748 EnclosingContext = EnclosingDecl;
14751 // Construct the decl.
14752 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14753 DeclStart, Loc, II, T,
14754 TInfo, ac, (Expr *)BitfieldWidth);
14757 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14759 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14760 && !isa<TagDecl>(PrevDecl)) {
14761 Diag(Loc, diag::err_duplicate_member) << II;
14762 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14763 NewID->setInvalidDecl();
14767 // Process attributes attached to the ivar.
14768 ProcessDeclAttributes(S, NewID, D);
14770 if (D.isInvalidType())
14771 NewID->setInvalidDecl();
14773 // In ARC, infer 'retaining' for ivars of retainable type.
14774 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14775 NewID->setInvalidDecl();
14777 if (D.getDeclSpec().isModulePrivateSpecified())
14778 NewID->setModulePrivate();
14781 // FIXME: When interfaces are DeclContexts, we'll need to add
14782 // these to the interface.
14784 IdResolver.AddDecl(NewID);
14787 if (LangOpts.ObjCRuntime.isNonFragile() &&
14788 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14789 Diag(Loc, diag::warn_ivars_in_interface);
14794 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14795 /// class and class extensions. For every class \@interface and class
14796 /// extension \@interface, if the last ivar is a bitfield of any type,
14797 /// then add an implicit `char :0` ivar to the end of that interface.
14798 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14799 SmallVectorImpl<Decl *> &AllIvarDecls) {
14800 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14803 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14804 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14806 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14808 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14810 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14811 if (!CD->IsClassExtension())
14814 // No need to add this to end of @implementation.
14818 // All conditions are met. Add a new bitfield to the tail end of ivars.
14819 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14820 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14822 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14823 DeclLoc, DeclLoc, nullptr,
14825 Context.getTrivialTypeSourceInfo(Context.CharTy,
14827 ObjCIvarDecl::Private, BW,
14829 AllIvarDecls.push_back(Ivar);
14832 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14833 ArrayRef<Decl *> Fields, SourceLocation LBrac,
14834 SourceLocation RBrac, AttributeList *Attr) {
14835 assert(EnclosingDecl && "missing record or interface decl");
14837 // If this is an Objective-C @implementation or category and we have
14838 // new fields here we should reset the layout of the interface since
14839 // it will now change.
14840 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14841 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14842 switch (DC->getKind()) {
14844 case Decl::ObjCCategory:
14845 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14847 case Decl::ObjCImplementation:
14849 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14854 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14856 // Start counting up the number of named members; make sure to include
14857 // members of anonymous structs and unions in the total.
14858 unsigned NumNamedMembers = 0;
14860 for (const auto *I : Record->decls()) {
14861 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14862 if (IFD->getDeclName())
14867 // Verify that all the fields are okay.
14868 SmallVector<FieldDecl*, 32> RecFields;
14870 bool ObjCFieldLifetimeErrReported = false;
14871 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14873 FieldDecl *FD = cast<FieldDecl>(*i);
14875 // Get the type for the field.
14876 const Type *FDTy = FD->getType().getTypePtr();
14878 if (!FD->isAnonymousStructOrUnion()) {
14879 // Remember all fields written by the user.
14880 RecFields.push_back(FD);
14883 // If the field is already invalid for some reason, don't emit more
14884 // diagnostics about it.
14885 if (FD->isInvalidDecl()) {
14886 EnclosingDecl->setInvalidDecl();
14891 // A structure or union shall not contain a member with
14892 // incomplete or function type (hence, a structure shall not
14893 // contain an instance of itself, but may contain a pointer to
14894 // an instance of itself), except that the last member of a
14895 // structure with more than one named member may have incomplete
14896 // array type; such a structure (and any union containing,
14897 // possibly recursively, a member that is such a structure)
14898 // shall not be a member of a structure or an element of an
14900 if (FDTy->isFunctionType()) {
14901 // Field declared as a function.
14902 Diag(FD->getLocation(), diag::err_field_declared_as_function)
14903 << FD->getDeclName();
14904 FD->setInvalidDecl();
14905 EnclosingDecl->setInvalidDecl();
14907 } else if (FDTy->isIncompleteArrayType() && Record &&
14908 ((i + 1 == Fields.end() && !Record->isUnion()) ||
14909 ((getLangOpts().MicrosoftExt ||
14910 getLangOpts().CPlusPlus) &&
14911 (i + 1 == Fields.end() || Record->isUnion())))) {
14912 // Flexible array member.
14913 // Microsoft and g++ is more permissive regarding flexible array.
14914 // It will accept flexible array in union and also
14915 // as the sole element of a struct/class.
14916 unsigned DiagID = 0;
14917 if (Record->isUnion())
14918 DiagID = getLangOpts().MicrosoftExt
14919 ? diag::ext_flexible_array_union_ms
14920 : getLangOpts().CPlusPlus
14921 ? diag::ext_flexible_array_union_gnu
14922 : diag::err_flexible_array_union;
14923 else if (NumNamedMembers < 1)
14924 DiagID = getLangOpts().MicrosoftExt
14925 ? diag::ext_flexible_array_empty_aggregate_ms
14926 : getLangOpts().CPlusPlus
14927 ? diag::ext_flexible_array_empty_aggregate_gnu
14928 : diag::err_flexible_array_empty_aggregate;
14931 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14932 << Record->getTagKind();
14933 // While the layout of types that contain virtual bases is not specified
14934 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14935 // virtual bases after the derived members. This would make a flexible
14936 // array member declared at the end of an object not adjacent to the end
14938 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14939 if (RD->getNumVBases() != 0)
14940 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14941 << FD->getDeclName() << Record->getTagKind();
14942 if (!getLangOpts().C99)
14943 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14944 << FD->getDeclName() << Record->getTagKind();
14946 // If the element type has a non-trivial destructor, we would not
14947 // implicitly destroy the elements, so disallow it for now.
14949 // FIXME: GCC allows this. We should probably either implicitly delete
14950 // the destructor of the containing class, or just allow this.
14951 QualType BaseElem = Context.getBaseElementType(FD->getType());
14952 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14953 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14954 << FD->getDeclName() << FD->getType();
14955 FD->setInvalidDecl();
14956 EnclosingDecl->setInvalidDecl();
14959 // Okay, we have a legal flexible array member at the end of the struct.
14960 Record->setHasFlexibleArrayMember(true);
14961 } else if (!FDTy->isDependentType() &&
14962 RequireCompleteType(FD->getLocation(), FD->getType(),
14963 diag::err_field_incomplete)) {
14965 FD->setInvalidDecl();
14966 EnclosingDecl->setInvalidDecl();
14968 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14969 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14970 // A type which contains a flexible array member is considered to be a
14971 // flexible array member.
14972 Record->setHasFlexibleArrayMember(true);
14973 if (!Record->isUnion()) {
14974 // If this is a struct/class and this is not the last element, reject
14975 // it. Note that GCC supports variable sized arrays in the middle of
14977 if (i + 1 != Fields.end())
14978 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14979 << FD->getDeclName() << FD->getType();
14981 // We support flexible arrays at the end of structs in
14982 // other structs as an extension.
14983 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14984 << FD->getDeclName();
14988 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14989 RequireNonAbstractType(FD->getLocation(), FD->getType(),
14990 diag::err_abstract_type_in_decl,
14991 AbstractIvarType)) {
14992 // Ivars can not have abstract class types
14993 FD->setInvalidDecl();
14995 if (Record && FDTTy->getDecl()->hasObjectMember())
14996 Record->setHasObjectMember(true);
14997 if (Record && FDTTy->getDecl()->hasVolatileMember())
14998 Record->setHasVolatileMember(true);
14999 } else if (FDTy->isObjCObjectType()) {
15000 /// A field cannot be an Objective-c object
15001 Diag(FD->getLocation(), diag::err_statically_allocated_object)
15002 << FixItHint::CreateInsertion(FD->getLocation(), "*");
15003 QualType T = Context.getObjCObjectPointerType(FD->getType());
15005 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15006 Record && !ObjCFieldLifetimeErrReported &&
15007 (!getLangOpts().CPlusPlus || Record->isUnion())) {
15008 // It's an error in ARC or Weak if a field has lifetime.
15009 // We don't want to report this in a system header, though,
15010 // so we just make the field unavailable.
15011 // FIXME: that's really not sufficient; we need to make the type
15012 // itself invalid to, say, initialize or copy.
15013 QualType T = FD->getType();
15014 if (T.hasNonTrivialObjCLifetime()) {
15015 SourceLocation loc = FD->getLocation();
15016 if (getSourceManager().isInSystemHeader(loc)) {
15017 if (!FD->hasAttr<UnavailableAttr>()) {
15018 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15019 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15022 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15023 << T->isBlockPointerType() << Record->getTagKind();
15025 ObjCFieldLifetimeErrReported = true;
15027 } else if (getLangOpts().ObjC1 &&
15028 getLangOpts().getGC() != LangOptions::NonGC &&
15029 Record && !Record->hasObjectMember()) {
15030 if (FD->getType()->isObjCObjectPointerType() ||
15031 FD->getType().isObjCGCStrong())
15032 Record->setHasObjectMember(true);
15033 else if (Context.getAsArrayType(FD->getType())) {
15034 QualType BaseType = Context.getBaseElementType(FD->getType());
15035 if (BaseType->isRecordType() &&
15036 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15037 Record->setHasObjectMember(true);
15038 else if (BaseType->isObjCObjectPointerType() ||
15039 BaseType.isObjCGCStrong())
15040 Record->setHasObjectMember(true);
15043 if (Record && FD->getType().isVolatileQualified())
15044 Record->setHasVolatileMember(true);
15045 // Keep track of the number of named members.
15046 if (FD->getIdentifier())
15050 // Okay, we successfully defined 'Record'.
15052 bool Completed = false;
15053 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15054 if (!CXXRecord->isInvalidDecl()) {
15055 // Set access bits correctly on the directly-declared conversions.
15056 for (CXXRecordDecl::conversion_iterator
15057 I = CXXRecord->conversion_begin(),
15058 E = CXXRecord->conversion_end(); I != E; ++I)
15059 I.setAccess((*I)->getAccess());
15062 if (!CXXRecord->isDependentType()) {
15063 if (CXXRecord->hasUserDeclaredDestructor()) {
15064 // Adjust user-defined destructor exception spec.
15065 if (getLangOpts().CPlusPlus11)
15066 AdjustDestructorExceptionSpec(CXXRecord,
15067 CXXRecord->getDestructor());
15070 if (!CXXRecord->isInvalidDecl()) {
15071 // Add any implicitly-declared members to this class.
15072 AddImplicitlyDeclaredMembersToClass(CXXRecord);
15074 // If we have virtual base classes, we may end up finding multiple
15075 // final overriders for a given virtual function. Check for this
15077 if (CXXRecord->getNumVBases()) {
15078 CXXFinalOverriderMap FinalOverriders;
15079 CXXRecord->getFinalOverriders(FinalOverriders);
15081 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15082 MEnd = FinalOverriders.end();
15084 for (OverridingMethods::iterator SO = M->second.begin(),
15085 SOEnd = M->second.end();
15086 SO != SOEnd; ++SO) {
15087 assert(SO->second.size() > 0 &&
15088 "Virtual function without overridding functions?");
15089 if (SO->second.size() == 1)
15092 // C++ [class.virtual]p2:
15093 // In a derived class, if a virtual member function of a base
15094 // class subobject has more than one final overrider the
15095 // program is ill-formed.
15096 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15097 << (const NamedDecl *)M->first << Record;
15098 Diag(M->first->getLocation(),
15099 diag::note_overridden_virtual_function);
15100 for (OverridingMethods::overriding_iterator
15101 OM = SO->second.begin(),
15102 OMEnd = SO->second.end();
15104 Diag(OM->Method->getLocation(), diag::note_final_overrider)
15105 << (const NamedDecl *)M->first << OM->Method->getParent();
15107 Record->setInvalidDecl();
15110 CXXRecord->completeDefinition(&FinalOverriders);
15118 Record->completeDefinition();
15120 // We may have deferred checking for a deleted destructor. Check now.
15121 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15122 auto *Dtor = CXXRecord->getDestructor();
15123 if (Dtor && Dtor->isImplicit() &&
15124 ShouldDeleteSpecialMember(Dtor, CXXDestructor))
15125 SetDeclDeleted(Dtor, CXXRecord->getLocation());
15128 if (Record->hasAttrs()) {
15129 CheckAlignasUnderalignment(Record);
15131 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15132 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15133 IA->getRange(), IA->getBestCase(),
15134 IA->getSemanticSpelling());
15137 // Check if the structure/union declaration is a type that can have zero
15138 // size in C. For C this is a language extension, for C++ it may cause
15139 // compatibility problems.
15140 bool CheckForZeroSize;
15141 if (!getLangOpts().CPlusPlus) {
15142 CheckForZeroSize = true;
15144 // For C++ filter out types that cannot be referenced in C code.
15145 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15147 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15148 !CXXRecord->isDependentType() &&
15149 CXXRecord->isCLike();
15151 if (CheckForZeroSize) {
15152 bool ZeroSize = true;
15153 bool IsEmpty = true;
15154 unsigned NonBitFields = 0;
15155 for (RecordDecl::field_iterator I = Record->field_begin(),
15156 E = Record->field_end();
15157 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15159 if (I->isUnnamedBitfield()) {
15160 if (I->getBitWidthValue(Context) > 0)
15164 QualType FieldType = I->getType();
15165 if (FieldType->isIncompleteType() ||
15166 !Context.getTypeSizeInChars(FieldType).isZero())
15171 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15172 // allowed in C++, but warn if its declaration is inside
15173 // extern "C" block.
15175 Diag(RecLoc, getLangOpts().CPlusPlus ?
15176 diag::warn_zero_size_struct_union_in_extern_c :
15177 diag::warn_zero_size_struct_union_compat)
15178 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15181 // Structs without named members are extension in C (C99 6.7.2.1p7),
15182 // but are accepted by GCC.
15183 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15184 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15185 diag::ext_no_named_members_in_struct_union)
15186 << Record->isUnion();
15190 ObjCIvarDecl **ClsFields =
15191 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15192 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15193 ID->setEndOfDefinitionLoc(RBrac);
15194 // Add ivar's to class's DeclContext.
15195 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15196 ClsFields[i]->setLexicalDeclContext(ID);
15197 ID->addDecl(ClsFields[i]);
15199 // Must enforce the rule that ivars in the base classes may not be
15201 if (ID->getSuperClass())
15202 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15203 } else if (ObjCImplementationDecl *IMPDecl =
15204 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15205 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15206 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15207 // Ivar declared in @implementation never belongs to the implementation.
15208 // Only it is in implementation's lexical context.
15209 ClsFields[I]->setLexicalDeclContext(IMPDecl);
15210 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15211 IMPDecl->setIvarLBraceLoc(LBrac);
15212 IMPDecl->setIvarRBraceLoc(RBrac);
15213 } else if (ObjCCategoryDecl *CDecl =
15214 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15215 // case of ivars in class extension; all other cases have been
15216 // reported as errors elsewhere.
15217 // FIXME. Class extension does not have a LocEnd field.
15218 // CDecl->setLocEnd(RBrac);
15219 // Add ivar's to class extension's DeclContext.
15220 // Diagnose redeclaration of private ivars.
15221 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15222 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15224 if (const ObjCIvarDecl *ClsIvar =
15225 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15226 Diag(ClsFields[i]->getLocation(),
15227 diag::err_duplicate_ivar_declaration);
15228 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15231 for (const auto *Ext : IDecl->known_extensions()) {
15232 if (const ObjCIvarDecl *ClsExtIvar
15233 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15234 Diag(ClsFields[i]->getLocation(),
15235 diag::err_duplicate_ivar_declaration);
15236 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15241 ClsFields[i]->setLexicalDeclContext(CDecl);
15242 CDecl->addDecl(ClsFields[i]);
15244 CDecl->setIvarLBraceLoc(LBrac);
15245 CDecl->setIvarRBraceLoc(RBrac);
15250 ProcessDeclAttributeList(S, Record, Attr);
15253 /// \brief Determine whether the given integral value is representable within
15254 /// the given type T.
15255 static bool isRepresentableIntegerValue(ASTContext &Context,
15256 llvm::APSInt &Value,
15258 assert(T->isIntegralType(Context) && "Integral type required!");
15259 unsigned BitWidth = Context.getIntWidth(T);
15261 if (Value.isUnsigned() || Value.isNonNegative()) {
15262 if (T->isSignedIntegerOrEnumerationType())
15264 return Value.getActiveBits() <= BitWidth;
15266 return Value.getMinSignedBits() <= BitWidth;
15269 // \brief Given an integral type, return the next larger integral type
15270 // (or a NULL type of no such type exists).
15271 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15272 // FIXME: Int128/UInt128 support, which also needs to be introduced into
15273 // enum checking below.
15274 assert(T->isIntegralType(Context) && "Integral type required!");
15275 const unsigned NumTypes = 4;
15276 QualType SignedIntegralTypes[NumTypes] = {
15277 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15279 QualType UnsignedIntegralTypes[NumTypes] = {
15280 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15281 Context.UnsignedLongLongTy
15284 unsigned BitWidth = Context.getTypeSize(T);
15285 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15286 : UnsignedIntegralTypes;
15287 for (unsigned I = 0; I != NumTypes; ++I)
15288 if (Context.getTypeSize(Types[I]) > BitWidth)
15294 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15295 EnumConstantDecl *LastEnumConst,
15296 SourceLocation IdLoc,
15297 IdentifierInfo *Id,
15299 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15300 llvm::APSInt EnumVal(IntWidth);
15303 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15307 Val = DefaultLvalueConversion(Val).get();
15310 if (Enum->isDependentType() || Val->isTypeDependent())
15311 EltTy = Context.DependentTy;
15313 SourceLocation ExpLoc;
15314 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15315 !getLangOpts().MSVCCompat) {
15316 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15317 // constant-expression in the enumerator-definition shall be a converted
15318 // constant expression of the underlying type.
15319 EltTy = Enum->getIntegerType();
15320 ExprResult Converted =
15321 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15323 if (Converted.isInvalid())
15326 Val = Converted.get();
15327 } else if (!Val->isValueDependent() &&
15328 !(Val = VerifyIntegerConstantExpression(Val,
15329 &EnumVal).get())) {
15330 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15332 if (Enum->isFixed()) {
15333 EltTy = Enum->getIntegerType();
15335 // In Obj-C and Microsoft mode, require the enumeration value to be
15336 // representable in the underlying type of the enumeration. In C++11,
15337 // we perform a non-narrowing conversion as part of converted constant
15338 // expression checking.
15339 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15340 if (getLangOpts().MSVCCompat) {
15341 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15342 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15344 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15346 Val = ImpCastExprToType(Val, EltTy,
15347 EltTy->isBooleanType() ?
15348 CK_IntegralToBoolean : CK_IntegralCast)
15350 } else if (getLangOpts().CPlusPlus) {
15351 // C++11 [dcl.enum]p5:
15352 // If the underlying type is not fixed, the type of each enumerator
15353 // is the type of its initializing value:
15354 // - If an initializer is specified for an enumerator, the
15355 // initializing value has the same type as the expression.
15356 EltTy = Val->getType();
15359 // The expression that defines the value of an enumeration constant
15360 // shall be an integer constant expression that has a value
15361 // representable as an int.
15363 // Complain if the value is not representable in an int.
15364 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15365 Diag(IdLoc, diag::ext_enum_value_not_int)
15366 << EnumVal.toString(10) << Val->getSourceRange()
15367 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15368 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15369 // Force the type of the expression to 'int'.
15370 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15372 EltTy = Val->getType();
15379 if (Enum->isDependentType())
15380 EltTy = Context.DependentTy;
15381 else if (!LastEnumConst) {
15382 // C++0x [dcl.enum]p5:
15383 // If the underlying type is not fixed, the type of each enumerator
15384 // is the type of its initializing value:
15385 // - If no initializer is specified for the first enumerator, the
15386 // initializing value has an unspecified integral type.
15388 // GCC uses 'int' for its unspecified integral type, as does
15390 if (Enum->isFixed()) {
15391 EltTy = Enum->getIntegerType();
15394 EltTy = Context.IntTy;
15397 // Assign the last value + 1.
15398 EnumVal = LastEnumConst->getInitVal();
15400 EltTy = LastEnumConst->getType();
15402 // Check for overflow on increment.
15403 if (EnumVal < LastEnumConst->getInitVal()) {
15404 // C++0x [dcl.enum]p5:
15405 // If the underlying type is not fixed, the type of each enumerator
15406 // is the type of its initializing value:
15408 // - Otherwise the type of the initializing value is the same as
15409 // the type of the initializing value of the preceding enumerator
15410 // unless the incremented value is not representable in that type,
15411 // in which case the type is an unspecified integral type
15412 // sufficient to contain the incremented value. If no such type
15413 // exists, the program is ill-formed.
15414 QualType T = getNextLargerIntegralType(Context, EltTy);
15415 if (T.isNull() || Enum->isFixed()) {
15416 // There is no integral type larger enough to represent this
15417 // value. Complain, then allow the value to wrap around.
15418 EnumVal = LastEnumConst->getInitVal();
15419 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15421 if (Enum->isFixed())
15422 // When the underlying type is fixed, this is ill-formed.
15423 Diag(IdLoc, diag::err_enumerator_wrapped)
15424 << EnumVal.toString(10)
15427 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15428 << EnumVal.toString(10);
15433 // Retrieve the last enumerator's value, extent that type to the
15434 // type that is supposed to be large enough to represent the incremented
15435 // value, then increment.
15436 EnumVal = LastEnumConst->getInitVal();
15437 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15438 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15441 // If we're not in C++, diagnose the overflow of enumerator values,
15442 // which in C99 means that the enumerator value is not representable in
15443 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15444 // permits enumerator values that are representable in some larger
15446 if (!getLangOpts().CPlusPlus && !T.isNull())
15447 Diag(IdLoc, diag::warn_enum_value_overflow);
15448 } else if (!getLangOpts().CPlusPlus &&
15449 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15450 // Enforce C99 6.7.2.2p2 even when we compute the next value.
15451 Diag(IdLoc, diag::ext_enum_value_not_int)
15452 << EnumVal.toString(10) << 1;
15457 if (!EltTy->isDependentType()) {
15458 // Make the enumerator value match the signedness and size of the
15459 // enumerator's type.
15460 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15461 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15464 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15468 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15469 SourceLocation IILoc) {
15470 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15471 !getLangOpts().CPlusPlus)
15472 return SkipBodyInfo();
15474 // We have an anonymous enum definition. Look up the first enumerator to
15475 // determine if we should merge the definition with an existing one and
15477 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15479 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15481 return SkipBodyInfo();
15483 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15485 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15487 Skip.Previous = Hidden;
15491 return SkipBodyInfo();
15494 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15495 SourceLocation IdLoc, IdentifierInfo *Id,
15496 AttributeList *Attr,
15497 SourceLocation EqualLoc, Expr *Val) {
15498 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15499 EnumConstantDecl *LastEnumConst =
15500 cast_or_null<EnumConstantDecl>(lastEnumConst);
15502 // The scope passed in may not be a decl scope. Zip up the scope tree until
15503 // we find one that is.
15504 S = getNonFieldDeclScope(S);
15506 // Verify that there isn't already something declared with this name in this
15508 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15510 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15511 // Maybe we will complain about the shadowed template parameter.
15512 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15513 // Just pretend that we didn't see the previous declaration.
15514 PrevDecl = nullptr;
15517 // C++ [class.mem]p15:
15518 // If T is the name of a class, then each of the following shall have a name
15519 // different from T:
15520 // - every enumerator of every member of class T that is an unscoped
15522 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15523 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15524 DeclarationNameInfo(Id, IdLoc));
15526 EnumConstantDecl *New =
15527 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15532 // When in C++, we may get a TagDecl with the same name; in this case the
15533 // enum constant will 'hide' the tag.
15534 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15535 "Received TagDecl when not in C++!");
15536 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15537 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15538 if (isa<EnumConstantDecl>(PrevDecl))
15539 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15541 Diag(IdLoc, diag::err_redefinition) << Id;
15542 notePreviousDefinition(PrevDecl, IdLoc);
15547 // Process attributes.
15548 if (Attr) ProcessDeclAttributeList(S, New, Attr);
15549 AddPragmaAttributes(S, New);
15551 // Register this decl in the current scope stack.
15552 New->setAccess(TheEnumDecl->getAccess());
15553 PushOnScopeChains(New, S);
15555 ActOnDocumentableDecl(New);
15560 // Returns true when the enum initial expression does not trigger the
15561 // duplicate enum warning. A few common cases are exempted as follows:
15562 // Element2 = Element1
15563 // Element2 = Element1 + 1
15564 // Element2 = Element1 - 1
15565 // Where Element2 and Element1 are from the same enum.
15566 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15567 Expr *InitExpr = ECD->getInitExpr();
15570 InitExpr = InitExpr->IgnoreImpCasts();
15572 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15573 if (!BO->isAdditiveOp())
15575 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15578 if (IL->getValue() != 1)
15581 InitExpr = BO->getLHS();
15584 // This checks if the elements are from the same enum.
15585 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15589 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15593 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15603 bool isTombstoneOrEmptyKey;
15604 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15605 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15608 static DupKey GetDupKey(const llvm::APSInt& Val) {
15609 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15613 struct DenseMapInfoDupKey {
15614 static DupKey getEmptyKey() { return DupKey(0, true); }
15615 static DupKey getTombstoneKey() { return DupKey(1, true); }
15616 static unsigned getHashValue(const DupKey Key) {
15617 return (unsigned)(Key.val * 37);
15619 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15620 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15621 LHS.val == RHS.val;
15624 } // end anonymous namespace
15626 // Emits a warning when an element is implicitly set a value that
15627 // a previous element has already been set to.
15628 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15630 QualType EnumType) {
15631 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15633 // Avoid anonymous enums
15634 if (!Enum->getIdentifier())
15637 // Only check for small enums.
15638 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15641 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15642 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15644 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15645 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15648 DuplicatesVector DupVector;
15649 ValueToVectorMap EnumMap;
15651 // Populate the EnumMap with all values represented by enum constants without
15653 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15654 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15656 // Null EnumConstantDecl means a previous diagnostic has been emitted for
15657 // this constant. Skip this enum since it may be ill-formed.
15662 if (ECD->getInitExpr())
15665 DupKey Key = GetDupKey(ECD->getInitVal());
15666 DeclOrVector &Entry = EnumMap[Key];
15668 // First time encountering this value.
15669 if (Entry.isNull())
15673 // Create vectors for any values that has duplicates.
15674 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15675 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15676 if (!ValidDuplicateEnum(ECD, Enum))
15679 DupKey Key = GetDupKey(ECD->getInitVal());
15681 DeclOrVector& Entry = EnumMap[Key];
15682 if (Entry.isNull())
15685 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15686 // Ensure constants are different.
15690 // Create new vector and push values onto it.
15691 ECDVector *Vec = new ECDVector();
15693 Vec->push_back(ECD);
15695 // Update entry to point to the duplicates vector.
15698 // Store the vector somewhere we can consult later for quick emission of
15700 DupVector.push_back(Vec);
15704 ECDVector *Vec = Entry.get<ECDVector*>();
15705 // Make sure constants are not added more than once.
15706 if (*Vec->begin() == ECD)
15709 Vec->push_back(ECD);
15712 // Emit diagnostics.
15713 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15714 DupVectorEnd = DupVector.end();
15715 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15716 ECDVector *Vec = *DupVectorIter;
15717 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15719 // Emit warning for one enum constant.
15720 ECDVector::iterator I = Vec->begin();
15721 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15722 << (*I)->getName() << (*I)->getInitVal().toString(10)
15723 << (*I)->getSourceRange();
15726 // Emit one note for each of the remaining enum constants with
15728 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15729 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15730 << (*I)->getName() << (*I)->getInitVal().toString(10)
15731 << (*I)->getSourceRange();
15736 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15737 bool AllowMask) const {
15738 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15739 assert(ED->isCompleteDefinition() && "expected enum definition");
15741 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15742 llvm::APInt &FlagBits = R.first->second;
15745 for (auto *E : ED->enumerators()) {
15746 const auto &EVal = E->getInitVal();
15747 // Only single-bit enumerators introduce new flag values.
15748 if (EVal.isPowerOf2())
15749 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15753 // A value is in a flag enum if either its bits are a subset of the enum's
15754 // flag bits (the first condition) or we are allowing masks and the same is
15755 // true of its complement (the second condition). When masks are allowed, we
15756 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15758 // While it's true that any value could be used as a mask, the assumption is
15759 // that a mask will have all of the insignificant bits set. Anything else is
15760 // likely a logic error.
15761 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15762 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15765 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15767 ArrayRef<Decl *> Elements,
15768 Scope *S, AttributeList *Attr) {
15769 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15770 QualType EnumType = Context.getTypeDeclType(Enum);
15773 ProcessDeclAttributeList(S, Enum, Attr);
15775 if (Enum->isDependentType()) {
15776 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15777 EnumConstantDecl *ECD =
15778 cast_or_null<EnumConstantDecl>(Elements[i]);
15779 if (!ECD) continue;
15781 ECD->setType(EnumType);
15784 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15788 // TODO: If the result value doesn't fit in an int, it must be a long or long
15789 // long value. ISO C does not support this, but GCC does as an extension,
15791 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15792 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15793 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15795 // Verify that all the values are okay, compute the size of the values, and
15796 // reverse the list.
15797 unsigned NumNegativeBits = 0;
15798 unsigned NumPositiveBits = 0;
15800 // Keep track of whether all elements have type int.
15801 bool AllElementsInt = true;
15803 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15804 EnumConstantDecl *ECD =
15805 cast_or_null<EnumConstantDecl>(Elements[i]);
15806 if (!ECD) continue; // Already issued a diagnostic.
15808 const llvm::APSInt &InitVal = ECD->getInitVal();
15810 // Keep track of the size of positive and negative values.
15811 if (InitVal.isUnsigned() || InitVal.isNonNegative())
15812 NumPositiveBits = std::max(NumPositiveBits,
15813 (unsigned)InitVal.getActiveBits());
15815 NumNegativeBits = std::max(NumNegativeBits,
15816 (unsigned)InitVal.getMinSignedBits());
15818 // Keep track of whether every enum element has type int (very commmon).
15819 if (AllElementsInt)
15820 AllElementsInt = ECD->getType() == Context.IntTy;
15823 // Figure out the type that should be used for this enum.
15825 unsigned BestWidth;
15827 // C++0x N3000 [conv.prom]p3:
15828 // An rvalue of an unscoped enumeration type whose underlying
15829 // type is not fixed can be converted to an rvalue of the first
15830 // of the following types that can represent all the values of
15831 // the enumeration: int, unsigned int, long int, unsigned long
15832 // int, long long int, or unsigned long long int.
15834 // An identifier declared as an enumeration constant has type int.
15835 // The C99 rule is modified by a gcc extension
15836 QualType BestPromotionType;
15838 bool Packed = Enum->hasAttr<PackedAttr>();
15839 // -fshort-enums is the equivalent to specifying the packed attribute on all
15840 // enum definitions.
15841 if (LangOpts.ShortEnums)
15844 if (Enum->isFixed()) {
15845 BestType = Enum->getIntegerType();
15846 if (BestType->isPromotableIntegerType())
15847 BestPromotionType = Context.getPromotedIntegerType(BestType);
15849 BestPromotionType = BestType;
15851 BestWidth = Context.getIntWidth(BestType);
15853 else if (NumNegativeBits) {
15854 // If there is a negative value, figure out the smallest integer type (of
15855 // int/long/longlong) that fits.
15856 // If it's packed, check also if it fits a char or a short.
15857 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15858 BestType = Context.SignedCharTy;
15859 BestWidth = CharWidth;
15860 } else if (Packed && NumNegativeBits <= ShortWidth &&
15861 NumPositiveBits < ShortWidth) {
15862 BestType = Context.ShortTy;
15863 BestWidth = ShortWidth;
15864 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15865 BestType = Context.IntTy;
15866 BestWidth = IntWidth;
15868 BestWidth = Context.getTargetInfo().getLongWidth();
15870 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15871 BestType = Context.LongTy;
15873 BestWidth = Context.getTargetInfo().getLongLongWidth();
15875 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15876 Diag(Enum->getLocation(), diag::ext_enum_too_large);
15877 BestType = Context.LongLongTy;
15880 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15882 // If there is no negative value, figure out the smallest type that fits
15883 // all of the enumerator values.
15884 // If it's packed, check also if it fits a char or a short.
15885 if (Packed && NumPositiveBits <= CharWidth) {
15886 BestType = Context.UnsignedCharTy;
15887 BestPromotionType = Context.IntTy;
15888 BestWidth = CharWidth;
15889 } else if (Packed && NumPositiveBits <= ShortWidth) {
15890 BestType = Context.UnsignedShortTy;
15891 BestPromotionType = Context.IntTy;
15892 BestWidth = ShortWidth;
15893 } else if (NumPositiveBits <= IntWidth) {
15894 BestType = Context.UnsignedIntTy;
15895 BestWidth = IntWidth;
15897 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15898 ? Context.UnsignedIntTy : Context.IntTy;
15899 } else if (NumPositiveBits <=
15900 (BestWidth = Context.getTargetInfo().getLongWidth())) {
15901 BestType = Context.UnsignedLongTy;
15903 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15904 ? Context.UnsignedLongTy : Context.LongTy;
15906 BestWidth = Context.getTargetInfo().getLongLongWidth();
15907 assert(NumPositiveBits <= BestWidth &&
15908 "How could an initializer get larger than ULL?");
15909 BestType = Context.UnsignedLongLongTy;
15911 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15912 ? Context.UnsignedLongLongTy : Context.LongLongTy;
15916 // Loop over all of the enumerator constants, changing their types to match
15917 // the type of the enum if needed.
15918 for (auto *D : Elements) {
15919 auto *ECD = cast_or_null<EnumConstantDecl>(D);
15920 if (!ECD) continue; // Already issued a diagnostic.
15922 // Standard C says the enumerators have int type, but we allow, as an
15923 // extension, the enumerators to be larger than int size. If each
15924 // enumerator value fits in an int, type it as an int, otherwise type it the
15925 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
15926 // that X has type 'int', not 'unsigned'.
15928 // Determine whether the value fits into an int.
15929 llvm::APSInt InitVal = ECD->getInitVal();
15931 // If it fits into an integer type, force it. Otherwise force it to match
15932 // the enum decl type.
15936 if (!getLangOpts().CPlusPlus &&
15937 !Enum->isFixed() &&
15938 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15939 NewTy = Context.IntTy;
15940 NewWidth = IntWidth;
15942 } else if (ECD->getType() == BestType) {
15943 // Already the right type!
15944 if (getLangOpts().CPlusPlus)
15945 // C++ [dcl.enum]p4: Following the closing brace of an
15946 // enum-specifier, each enumerator has the type of its
15948 ECD->setType(EnumType);
15952 NewWidth = BestWidth;
15953 NewSign = BestType->isSignedIntegerOrEnumerationType();
15956 // Adjust the APSInt value.
15957 InitVal = InitVal.extOrTrunc(NewWidth);
15958 InitVal.setIsSigned(NewSign);
15959 ECD->setInitVal(InitVal);
15961 // Adjust the Expr initializer and type.
15962 if (ECD->getInitExpr() &&
15963 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15964 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15966 ECD->getInitExpr(),
15967 /*base paths*/ nullptr,
15969 if (getLangOpts().CPlusPlus)
15970 // C++ [dcl.enum]p4: Following the closing brace of an
15971 // enum-specifier, each enumerator has the type of its
15973 ECD->setType(EnumType);
15975 ECD->setType(NewTy);
15978 Enum->completeDefinition(BestType, BestPromotionType,
15979 NumPositiveBits, NumNegativeBits);
15981 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15983 if (Enum->isClosedFlag()) {
15984 for (Decl *D : Elements) {
15985 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15986 if (!ECD) continue; // Already issued a diagnostic.
15988 llvm::APSInt InitVal = ECD->getInitVal();
15989 if (InitVal != 0 && !InitVal.isPowerOf2() &&
15990 !IsValueInFlagEnum(Enum, InitVal, true))
15991 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15996 // Now that the enum type is defined, ensure it's not been underaligned.
15997 if (Enum->hasAttrs())
15998 CheckAlignasUnderalignment(Enum);
16001 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16002 SourceLocation StartLoc,
16003 SourceLocation EndLoc) {
16004 StringLiteral *AsmString = cast<StringLiteral>(expr);
16006 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16007 AsmString, StartLoc,
16009 CurContext->addDecl(New);
16013 static void checkModuleImportContext(Sema &S, Module *M,
16014 SourceLocation ImportLoc, DeclContext *DC,
16015 bool FromInclude = false) {
16016 SourceLocation ExternCLoc;
16018 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16019 switch (LSD->getLanguage()) {
16020 case LinkageSpecDecl::lang_c:
16021 if (ExternCLoc.isInvalid())
16022 ExternCLoc = LSD->getLocStart();
16024 case LinkageSpecDecl::lang_cxx:
16027 DC = LSD->getParent();
16030 while (isa<LinkageSpecDecl>(DC))
16031 DC = DC->getParent();
16033 if (!isa<TranslationUnitDecl>(DC)) {
16034 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16035 ? diag::ext_module_import_not_at_top_level_noop
16036 : diag::err_module_import_not_at_top_level_fatal)
16037 << M->getFullModuleName() << DC;
16038 S.Diag(cast<Decl>(DC)->getLocStart(),
16039 diag::note_module_import_not_at_top_level) << DC;
16040 } else if (!M->IsExternC && ExternCLoc.isValid()) {
16041 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16042 << M->getFullModuleName();
16043 S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16047 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16048 SourceLocation ModuleLoc,
16049 ModuleDeclKind MDK,
16050 ModuleIdPath Path) {
16051 // A module implementation unit requires that we are not compiling a module
16052 // of any kind. A module interface unit requires that we are not compiling a
16054 switch (getLangOpts().getCompilingModule()) {
16055 case LangOptions::CMK_None:
16056 // It's OK to compile a module interface as a normal translation unit.
16059 case LangOptions::CMK_ModuleInterface:
16060 if (MDK != ModuleDeclKind::Implementation)
16063 // We were asked to compile a module interface unit but this is a module
16064 // implementation unit. That indicates the 'export' is missing.
16065 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16066 << FixItHint::CreateInsertion(ModuleLoc, "export ");
16069 case LangOptions::CMK_ModuleMap:
16070 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16074 // FIXME: Most of this work should be done by the preprocessor rather than
16075 // here, in order to support macro import.
16077 // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16078 // modules, the dots here are just another character that can appear in a
16080 std::string ModuleName;
16081 for (auto &Piece : Path) {
16082 if (!ModuleName.empty())
16084 ModuleName += Piece.first->getName();
16087 // FIXME: If we've already seen a module-declaration, report an error.
16089 // If a module name was explicitly specified on the command line, it must be
16091 if (!getLangOpts().CurrentModule.empty() &&
16092 getLangOpts().CurrentModule != ModuleName) {
16093 Diag(Path.front().second, diag::err_current_module_name_mismatch)
16094 << SourceRange(Path.front().second, Path.back().second)
16095 << getLangOpts().CurrentModule;
16098 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16100 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16104 case ModuleDeclKind::Module: {
16105 // FIXME: Check we're not in a submodule.
16107 // We can't have parsed or imported a definition of this module or parsed a
16108 // module map defining it already.
16109 if (auto *M = Map.findModule(ModuleName)) {
16110 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16111 if (M->DefinitionLoc.isValid())
16112 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16113 else if (const auto *FE = M->getASTFile())
16114 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16119 // Create a Module for the module that we're defining.
16120 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
16121 assert(Mod && "module creation should not fail");
16125 case ModuleDeclKind::Partition:
16126 // FIXME: Check we are in a submodule of the named module.
16129 case ModuleDeclKind::Implementation:
16130 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16131 PP.getIdentifierInfo(ModuleName), Path[0].second);
16132 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16133 /*IsIncludeDirective=*/false);
16139 // Enter the semantic scope of the module.
16140 ModuleScopes.push_back({});
16141 ModuleScopes.back().Module = Mod;
16142 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16143 VisibleModules.setVisible(Mod, ModuleLoc);
16145 // From now on, we have an owning module for all declarations we see.
16146 // However, those declarations are module-private unless explicitly
16148 Context.getTranslationUnitDecl()->setLocalOwningModule(Mod);
16150 // FIXME: Create a ModuleDecl.
16154 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16155 SourceLocation ImportLoc,
16156 ModuleIdPath Path) {
16158 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16159 /*IsIncludeDirective=*/false);
16163 VisibleModules.setVisible(Mod, ImportLoc);
16165 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16167 // FIXME: we should support importing a submodule within a different submodule
16168 // of the same top-level module. Until we do, make it an error rather than
16169 // silently ignoring the import.
16170 // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16171 // warn on a redundant import of the current module?
16172 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16173 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16174 Diag(ImportLoc, getLangOpts().isCompilingModule()
16175 ? diag::err_module_self_import
16176 : diag::err_module_import_in_implementation)
16177 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16179 SmallVector<SourceLocation, 2> IdentifierLocs;
16180 Module *ModCheck = Mod;
16181 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16182 // If we've run out of module parents, just drop the remaining identifiers.
16183 // We need the length to be consistent.
16186 ModCheck = ModCheck->Parent;
16188 IdentifierLocs.push_back(Path[I].second);
16191 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16192 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
16193 Mod, IdentifierLocs);
16194 if (!ModuleScopes.empty())
16195 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16196 TU->addDecl(Import);
16200 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16201 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16202 BuildModuleInclude(DirectiveLoc, Mod);
16205 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16206 // Determine whether we're in the #include buffer for a module. The #includes
16207 // in that buffer do not qualify as module imports; they're just an
16208 // implementation detail of us building the module.
16210 // FIXME: Should we even get ActOnModuleInclude calls for those?
16211 bool IsInModuleIncludes =
16212 TUKind == TU_Module &&
16213 getSourceManager().isWrittenInMainFile(DirectiveLoc);
16215 bool ShouldAddImport = !IsInModuleIncludes;
16217 // If this module import was due to an inclusion directive, create an
16218 // implicit import declaration to capture it in the AST.
16219 if (ShouldAddImport) {
16220 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16221 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16224 if (!ModuleScopes.empty())
16225 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16226 TU->addDecl(ImportD);
16227 Consumer.HandleImplicitImportDecl(ImportD);
16230 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16231 VisibleModules.setVisible(Mod, DirectiveLoc);
16234 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16235 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16237 ModuleScopes.push_back({});
16238 ModuleScopes.back().Module = Mod;
16239 if (getLangOpts().ModulesLocalVisibility)
16240 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16242 VisibleModules.setVisible(Mod, DirectiveLoc);
16244 // The enclosing context is now part of this module.
16245 // FIXME: Consider creating a child DeclContext to hold the entities
16246 // lexically within the module.
16247 if (getLangOpts().trackLocalOwningModule()) {
16248 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16249 cast<Decl>(DC)->setModuleOwnershipKind(
16250 getLangOpts().ModulesLocalVisibility
16251 ? Decl::ModuleOwnershipKind::VisibleWhenImported
16252 : Decl::ModuleOwnershipKind::Visible);
16253 cast<Decl>(DC)->setLocalOwningModule(Mod);
16258 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16259 if (getLangOpts().ModulesLocalVisibility) {
16260 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16261 // Leaving a module hides namespace names, so our visible namespace cache
16262 // is now out of date.
16263 VisibleNamespaceCache.clear();
16266 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16267 "left the wrong module scope");
16268 ModuleScopes.pop_back();
16270 // We got to the end of processing a local module. Create an
16271 // ImportDecl as we would for an imported module.
16272 FileID File = getSourceManager().getFileID(EomLoc);
16273 SourceLocation DirectiveLoc;
16274 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16275 // We reached the end of a #included module header. Use the #include loc.
16276 assert(File != getSourceManager().getMainFileID() &&
16277 "end of submodule in main source file");
16278 DirectiveLoc = getSourceManager().getIncludeLoc(File);
16280 // We reached an EOM pragma. Use the pragma location.
16281 DirectiveLoc = EomLoc;
16283 BuildModuleInclude(DirectiveLoc, Mod);
16285 // Any further declarations are in whatever module we returned to.
16286 if (getLangOpts().trackLocalOwningModule()) {
16287 // The parser guarantees that this is the same context that we entered
16288 // the module within.
16289 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16290 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16291 if (!getCurrentModule())
16292 cast<Decl>(DC)->setModuleOwnershipKind(
16293 Decl::ModuleOwnershipKind::Unowned);
16298 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16300 // Bail if we're not allowed to implicitly import a module here.
16301 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16302 VisibleModules.isVisible(Mod))
16305 // Create the implicit import declaration.
16306 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16307 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16309 TU->addDecl(ImportD);
16310 Consumer.HandleImplicitImportDecl(ImportD);
16312 // Make the module visible.
16313 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16314 VisibleModules.setVisible(Mod, Loc);
16317 /// We have parsed the start of an export declaration, including the '{'
16319 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16320 SourceLocation LBraceLoc) {
16321 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16323 // C++ Modules TS draft:
16324 // An export-declaration shall appear in the purview of a module other than
16325 // the global module.
16326 if (ModuleScopes.empty() || !ModuleScopes.back().Module ||
16327 ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
16328 Diag(ExportLoc, diag::err_export_not_in_module_interface);
16330 // An export-declaration [...] shall not contain more than one
16333 // The intent here is that an export-declaration cannot appear within another
16334 // export-declaration.
16335 if (D->isExported())
16336 Diag(ExportLoc, diag::err_export_within_export);
16338 CurContext->addDecl(D);
16339 PushDeclContext(S, D);
16340 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16344 /// Complete the definition of an export declaration.
16345 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16346 auto *ED = cast<ExportDecl>(D);
16347 if (RBraceLoc.isValid())
16348 ED->setRBraceLoc(RBraceLoc);
16350 // FIXME: Diagnose export of internal-linkage declaration (including
16351 // anonymous namespace).
16357 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16358 IdentifierInfo* AliasName,
16359 SourceLocation PragmaLoc,
16360 SourceLocation NameLoc,
16361 SourceLocation AliasNameLoc) {
16362 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16363 LookupOrdinaryName);
16364 AsmLabelAttr *Attr =
16365 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16367 // If a declaration that:
16368 // 1) declares a function or a variable
16369 // 2) has external linkage
16370 // already exists, add a label attribute to it.
16371 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16372 if (isDeclExternC(PrevDecl))
16373 PrevDecl->addAttr(Attr);
16375 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16376 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16377 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16379 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16382 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16383 SourceLocation PragmaLoc,
16384 SourceLocation NameLoc) {
16385 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16388 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16390 (void)WeakUndeclaredIdentifiers.insert(
16391 std::pair<IdentifierInfo*,WeakInfo>
16392 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16396 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16397 IdentifierInfo* AliasName,
16398 SourceLocation PragmaLoc,
16399 SourceLocation NameLoc,
16400 SourceLocation AliasNameLoc) {
16401 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16402 LookupOrdinaryName);
16403 WeakInfo W = WeakInfo(Name, NameLoc);
16405 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16406 if (!PrevDecl->hasAttr<AliasAttr>())
16407 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16408 DeclApplyPragmaWeak(TUScope, ND, W);
16410 (void)WeakUndeclaredIdentifiers.insert(
16411 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16415 Decl *Sema::getObjCDeclContext() const {
16416 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));