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
407 case LookupResult::FoundOverloaded:
408 case LookupResult::FoundUnresolvedValue:
409 Result.suppressDiagnostics();
412 case LookupResult::Ambiguous:
413 // Recover from type-hiding ambiguities by hiding the type. We'll
414 // do the lookup again when looking for an object, and we can
415 // diagnose the error then. If we don't do this, then the error
416 // about hiding the type will be immediately followed by an error
417 // that only makes sense if the identifier was treated like a type.
418 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
419 Result.suppressDiagnostics();
423 // Look to see if we have a type anywhere in the list of results.
424 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
425 Res != ResEnd; ++Res) {
426 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
427 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
429 (*Res)->getLocation().getRawEncoding() <
430 IIDecl->getLocation().getRawEncoding())
436 // None of the entities we found is a type, so there is no way
437 // to even assume that the result is a type. In this case, don't
438 // complain about the ambiguity. The parser will either try to
439 // perform this lookup again (e.g., as an object name), which
440 // will produce the ambiguity, or will complain that it expected
442 Result.suppressDiagnostics();
446 // We found a type within the ambiguous lookup; diagnose the
447 // ambiguity and then return that type. This might be the right
448 // answer, or it might not be, but it suppresses any attempt to
449 // perform the name lookup again.
452 case LookupResult::Found:
453 IIDecl = Result.getFoundDecl();
457 assert(IIDecl && "Didn't find decl");
460 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
461 // C++ [class.qual]p2: A lookup that would find the injected-class-name
462 // instead names the constructors of the class, except when naming a class.
463 // This is ill-formed when we're not actually forming a ctor or dtor name.
464 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
465 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
466 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
467 FoundRD->isInjectedClassName() &&
468 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
469 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
472 DiagnoseUseOfDecl(IIDecl, NameLoc);
474 T = Context.getTypeDeclType(TD);
475 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
476 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
477 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
479 T = Context.getObjCInterfaceType(IDecl);
480 } else if (AllowDeducedTemplate) {
481 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
482 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
487 // If it's not plausibly a type, suppress diagnostics.
488 Result.suppressDiagnostics();
492 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
493 // constructor or destructor name (in such a case, the scope specifier
494 // will be attached to the enclosing Expr or Decl node).
495 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
496 !isa<ObjCInterfaceDecl>(IIDecl)) {
497 if (WantNontrivialTypeSourceInfo) {
498 // Construct a type with type-source information.
499 TypeLocBuilder Builder;
500 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
502 T = getElaboratedType(ETK_None, *SS, T);
503 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
504 ElabTL.setElaboratedKeywordLoc(SourceLocation());
505 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
506 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
508 T = getElaboratedType(ETK_None, *SS, T);
512 return ParsedType::make(T);
515 // Builds a fake NNS for the given decl context.
516 static NestedNameSpecifier *
517 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
518 for (;; DC = DC->getLookupParent()) {
519 DC = DC->getPrimaryContext();
520 auto *ND = dyn_cast<NamespaceDecl>(DC);
521 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
522 return NestedNameSpecifier::Create(Context, nullptr, ND);
523 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
524 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
525 RD->getTypeForDecl());
526 else if (isa<TranslationUnitDecl>(DC))
527 return NestedNameSpecifier::GlobalSpecifier(Context);
529 llvm_unreachable("something isn't in TU scope?");
532 /// Find the parent class with dependent bases of the innermost enclosing method
533 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
534 /// up allowing unqualified dependent type names at class-level, which MSVC
535 /// correctly rejects.
536 static const CXXRecordDecl *
537 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
538 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
539 DC = DC->getPrimaryContext();
540 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
541 if (MD->getParent()->hasAnyDependentBases())
542 return MD->getParent();
547 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
548 SourceLocation NameLoc,
549 bool IsTemplateTypeArg) {
550 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
552 NestedNameSpecifier *NNS = nullptr;
553 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
554 // If we weren't able to parse a default template argument, delay lookup
555 // until instantiation time by making a non-dependent DependentTypeName. We
556 // pretend we saw a NestedNameSpecifier referring to the current scope, and
557 // lookup is retried.
558 // FIXME: This hurts our diagnostic quality, since we get errors like "no
559 // type named 'Foo' in 'current_namespace'" when the user didn't write any
561 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
562 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
563 } else if (const CXXRecordDecl *RD =
564 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
565 // Build a DependentNameType that will perform lookup into RD at
566 // instantiation time.
567 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
568 RD->getTypeForDecl());
570 // Diagnose that this identifier was undeclared, and retry the lookup during
571 // template instantiation.
572 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
575 // This is not a situation that we should recover from.
579 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
581 // Build type location information. We synthesized the qualifier, so we have
582 // to build a fake NestedNameSpecifierLoc.
583 NestedNameSpecifierLocBuilder NNSLocBuilder;
584 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
585 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
587 TypeLocBuilder Builder;
588 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
589 DepTL.setNameLoc(NameLoc);
590 DepTL.setElaboratedKeywordLoc(SourceLocation());
591 DepTL.setQualifierLoc(QualifierLoc);
592 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
595 /// isTagName() - This method is called *for error recovery purposes only*
596 /// to determine if the specified name is a valid tag name ("struct foo"). If
597 /// so, this returns the TST for the tag corresponding to it (TST_enum,
598 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
599 /// cases in C where the user forgot to specify the tag.
600 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
601 // Do a tag name lookup in this scope.
602 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
603 LookupName(R, S, false);
604 R.suppressDiagnostics();
605 if (R.getResultKind() == LookupResult::Found)
606 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
607 switch (TD->getTagKind()) {
608 case TTK_Struct: return DeclSpec::TST_struct;
609 case TTK_Interface: return DeclSpec::TST_interface;
610 case TTK_Union: return DeclSpec::TST_union;
611 case TTK_Class: return DeclSpec::TST_class;
612 case TTK_Enum: return DeclSpec::TST_enum;
616 return DeclSpec::TST_unspecified;
619 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
620 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
621 /// then downgrade the missing typename error to a warning.
622 /// This is needed for MSVC compatibility; Example:
624 /// template<class T> class A {
626 /// typedef int TYPE;
628 /// template<class T> class B : public A<T> {
630 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
633 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
634 if (CurContext->isRecord()) {
635 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
638 const Type *Ty = SS->getScopeRep()->getAsType();
640 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
641 for (const auto &Base : RD->bases())
642 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
644 return S->isFunctionPrototypeScope();
646 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
649 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
650 SourceLocation IILoc,
653 ParsedType &SuggestedType,
654 bool IsTemplateName) {
655 // Don't report typename errors for editor placeholders.
656 if (II->isEditorPlaceholder())
658 // We don't have anything to suggest (yet).
659 SuggestedType = nullptr;
661 // There may have been a typo in the name of the type. Look up typo
662 // results, in case we have something that we can suggest.
663 if (TypoCorrection Corrected =
664 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
665 llvm::make_unique<TypeNameValidatorCCC>(
666 false, false, IsTemplateName, !IsTemplateName),
667 CTK_ErrorRecovery)) {
668 // FIXME: Support error recovery for the template-name case.
669 bool CanRecover = !IsTemplateName;
670 if (Corrected.isKeyword()) {
671 // We corrected to a keyword.
672 diagnoseTypo(Corrected,
673 PDiag(IsTemplateName ? diag::err_no_template_suggest
674 : diag::err_unknown_typename_suggest)
676 II = Corrected.getCorrectionAsIdentifierInfo();
678 // We found a similarly-named type or interface; suggest that.
679 if (!SS || !SS->isSet()) {
680 diagnoseTypo(Corrected,
681 PDiag(IsTemplateName ? diag::err_no_template_suggest
682 : diag::err_unknown_typename_suggest)
684 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
685 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
686 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
687 II->getName().equals(CorrectedStr);
688 diagnoseTypo(Corrected,
690 ? diag::err_no_member_template_suggest
691 : diag::err_unknown_nested_typename_suggest)
692 << II << DC << DroppedSpecifier << SS->getRange(),
695 llvm_unreachable("could not have corrected a typo here");
702 if (Corrected.getCorrectionSpecifier())
703 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
705 // FIXME: Support class template argument deduction here.
707 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
708 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
709 /*IsCtorOrDtorName=*/false,
710 /*NonTrivialTypeSourceInfo=*/true);
715 if (getLangOpts().CPlusPlus && !IsTemplateName) {
716 // See if II is a class template that the user forgot to pass arguments to.
718 Name.setIdentifier(II, IILoc);
719 CXXScopeSpec EmptySS;
720 TemplateTy TemplateResult;
721 bool MemberOfUnknownSpecialization;
722 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
723 Name, nullptr, true, TemplateResult,
724 MemberOfUnknownSpecialization) == TNK_Type_template) {
725 TemplateName TplName = TemplateResult.get();
726 Diag(IILoc, diag::err_template_missing_args)
727 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
728 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
729 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
730 << TplDecl->getTemplateParameters()->getSourceRange();
736 // FIXME: Should we move the logic that tries to recover from a missing tag
737 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
739 if (!SS || (!SS->isSet() && !SS->isInvalid()))
740 Diag(IILoc, IsTemplateName ? diag::err_no_template
741 : diag::err_unknown_typename)
743 else if (DeclContext *DC = computeDeclContext(*SS, false))
744 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
745 : diag::err_typename_nested_not_found)
746 << II << DC << SS->getRange();
747 else if (isDependentScopeSpecifier(*SS)) {
748 unsigned DiagID = diag::err_typename_missing;
749 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
750 DiagID = diag::ext_typename_missing;
752 Diag(SS->getRange().getBegin(), DiagID)
753 << SS->getScopeRep() << II->getName()
754 << SourceRange(SS->getRange().getBegin(), IILoc)
755 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
756 SuggestedType = ActOnTypenameType(S, SourceLocation(),
757 *SS, *II, IILoc).get();
759 assert(SS && SS->isInvalid() &&
760 "Invalid scope specifier has already been diagnosed");
764 /// \brief Determine whether the given result set contains either a type name
766 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
767 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
768 NextToken.is(tok::less);
770 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
771 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
774 if (CheckTemplate && isa<TemplateDecl>(*I))
781 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
782 Scope *S, CXXScopeSpec &SS,
783 IdentifierInfo *&Name,
784 SourceLocation NameLoc) {
785 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
786 SemaRef.LookupParsedName(R, S, &SS);
787 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
788 StringRef FixItTagName;
789 switch (Tag->getTagKind()) {
791 FixItTagName = "class ";
795 FixItTagName = "enum ";
799 FixItTagName = "struct ";
803 FixItTagName = "__interface ";
807 FixItTagName = "union ";
811 StringRef TagName = FixItTagName.drop_back();
812 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
813 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
814 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
816 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
818 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
821 // Replace lookup results with just the tag decl.
822 Result.clear(Sema::LookupTagName);
823 SemaRef.LookupParsedName(Result, S, &SS);
830 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
831 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
832 QualType T, SourceLocation NameLoc) {
833 ASTContext &Context = S.Context;
835 TypeLocBuilder Builder;
836 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
838 T = S.getElaboratedType(ETK_None, SS, T);
839 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
840 ElabTL.setElaboratedKeywordLoc(SourceLocation());
841 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
842 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
845 Sema::NameClassification
846 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
847 SourceLocation NameLoc, const Token &NextToken,
848 bool IsAddressOfOperand,
849 std::unique_ptr<CorrectionCandidateCallback> CCC) {
850 DeclarationNameInfo NameInfo(Name, NameLoc);
851 ObjCMethodDecl *CurMethod = getCurMethodDecl();
853 if (NextToken.is(tok::coloncolon)) {
854 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
855 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
856 } else if (getLangOpts().CPlusPlus && SS.isSet() &&
857 isCurrentClassName(*Name, S, &SS)) {
858 // Per [class.qual]p2, this names the constructors of SS, not the
859 // injected-class-name. We don't have a classification for that.
860 // There's not much point caching this result, since the parser
861 // will reject it later.
862 return NameClassification::Unknown();
865 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
866 LookupParsedName(Result, S, &SS, !CurMethod);
868 // For unqualified lookup in a class template in MSVC mode, look into
869 // dependent base classes where the primary class template is known.
870 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
871 if (ParsedType TypeInBase =
872 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
876 // Perform lookup for Objective-C instance variables (including automatically
877 // synthesized instance variables), if we're in an Objective-C method.
878 // FIXME: This lookup really, really needs to be folded in to the normal
879 // unqualified lookup mechanism.
880 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
881 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
882 if (E.get() || E.isInvalid())
886 bool SecondTry = false;
887 bool IsFilteredTemplateName = false;
890 switch (Result.getResultKind()) {
891 case LookupResult::NotFound:
892 // If an unqualified-id is followed by a '(', then we have a function
894 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
895 // In C++, this is an ADL-only call.
897 if (getLangOpts().CPlusPlus)
898 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901 // If the expression that precedes the parenthesized argument list in a
902 // function call consists solely of an identifier, and if no
903 // declaration is visible for this identifier, the identifier is
904 // implicitly declared exactly as if, in the innermost block containing
905 // the function call, the declaration
907 // extern int identifier ();
911 // We also allow this in C99 as an extension.
912 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
914 Result.resolveKind();
915 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
919 // In C, we first see whether there is a tag type by the same name, in
920 // which case it's likely that the user just forgot to write "enum",
921 // "struct", or "union".
922 if (!getLangOpts().CPlusPlus && !SecondTry &&
923 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
927 // Perform typo correction to determine if there is another name that is
928 // close to this name.
929 if (!SecondTry && CCC) {
931 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
932 Result.getLookupKind(), S,
934 CTK_ErrorRecovery)) {
935 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
936 unsigned QualifiedDiag = diag::err_no_member_suggest;
938 NamedDecl *FirstDecl = Corrected.getFoundDecl();
939 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
940 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
941 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
942 UnqualifiedDiag = diag::err_no_template_suggest;
943 QualifiedDiag = diag::err_no_member_template_suggest;
944 } else if (UnderlyingFirstDecl &&
945 (isa<TypeDecl>(UnderlyingFirstDecl) ||
946 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
947 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
948 UnqualifiedDiag = diag::err_unknown_typename_suggest;
949 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
953 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
954 } else {// FIXME: is this even reachable? Test it.
955 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
956 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
957 Name->getName().equals(CorrectedStr);
958 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
959 << Name << computeDeclContext(SS, false)
960 << DroppedSpecifier << SS.getRange());
963 // Update the name, so that the caller has the new name.
964 Name = Corrected.getCorrectionAsIdentifierInfo();
966 // Typo correction corrected to a keyword.
967 if (Corrected.isKeyword())
970 // Also update the LookupResult...
971 // FIXME: This should probably go away at some point
973 Result.setLookupName(Corrected.getCorrection());
975 Result.addDecl(FirstDecl);
977 // If we found an Objective-C instance variable, let
978 // LookupInObjCMethod build the appropriate expression to
979 // reference the ivar.
980 // FIXME: This is a gross hack.
981 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
983 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
991 // We failed to correct; just fall through and let the parser deal with it.
992 Result.suppressDiagnostics();
993 return NameClassification::Unknown();
995 case LookupResult::NotFoundInCurrentInstantiation: {
996 // We performed name lookup into the current instantiation, and there were
997 // dependent bases, so we treat this result the same way as any other
998 // dependent nested-name-specifier.
1000 // C++ [temp.res]p2:
1001 // A name used in a template declaration or definition and that is
1002 // dependent on a template-parameter is assumed not to name a type
1003 // unless the applicable name lookup finds a type name or the name is
1004 // qualified by the keyword typename.
1006 // FIXME: If the next token is '<', we might want to ask the parser to
1007 // perform some heroics to see if we actually have a
1008 // template-argument-list, which would indicate a missing 'template'
1010 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1011 NameInfo, IsAddressOfOperand,
1012 /*TemplateArgs=*/nullptr);
1015 case LookupResult::Found:
1016 case LookupResult::FoundOverloaded:
1017 case LookupResult::FoundUnresolvedValue:
1020 case LookupResult::Ambiguous:
1021 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1022 hasAnyAcceptableTemplateNames(Result)) {
1023 // C++ [temp.local]p3:
1024 // A lookup that finds an injected-class-name (10.2) can result in an
1025 // ambiguity in certain cases (for example, if it is found in more than
1026 // one base class). If all of the injected-class-names that are found
1027 // refer to specializations of the same class template, and if the name
1028 // is followed by a template-argument-list, the reference refers to the
1029 // class template itself and not a specialization thereof, and is not
1032 // This filtering can make an ambiguous result into an unambiguous one,
1033 // so try again after filtering out template names.
1034 FilterAcceptableTemplateNames(Result);
1035 if (!Result.isAmbiguous()) {
1036 IsFilteredTemplateName = true;
1041 // Diagnose the ambiguity and return an error.
1042 return NameClassification::Error();
1045 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1046 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1047 // C++ [temp.names]p3:
1048 // After name lookup (3.4) finds that a name is a template-name or that
1049 // an operator-function-id or a literal- operator-id refers to a set of
1050 // overloaded functions any member of which is a function template if
1051 // this is followed by a <, the < is always taken as the delimiter of a
1052 // template-argument-list and never as the less-than operator.
1053 if (!IsFilteredTemplateName)
1054 FilterAcceptableTemplateNames(Result);
1056 if (!Result.empty()) {
1057 bool IsFunctionTemplate;
1059 TemplateName Template;
1060 if (Result.end() - Result.begin() > 1) {
1061 IsFunctionTemplate = true;
1062 Template = Context.getOverloadedTemplateName(Result.begin(),
1066 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1067 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1068 IsVarTemplate = isa<VarTemplateDecl>(TD);
1070 if (SS.isSet() && !SS.isInvalid())
1071 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1072 /*TemplateKeyword=*/false,
1075 Template = TemplateName(TD);
1078 if (IsFunctionTemplate) {
1079 // Function templates always go through overload resolution, at which
1080 // point we'll perform the various checks (e.g., accessibility) we need
1081 // to based on which function we selected.
1082 Result.suppressDiagnostics();
1084 return NameClassification::FunctionTemplate(Template);
1087 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1088 : NameClassification::TypeTemplate(Template);
1092 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1093 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1094 DiagnoseUseOfDecl(Type, NameLoc);
1095 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1096 QualType T = Context.getTypeDeclType(Type);
1097 if (SS.isNotEmpty())
1098 return buildNestedType(*this, SS, T, NameLoc);
1099 return ParsedType::make(T);
1102 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1104 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1105 if (ObjCCompatibleAliasDecl *Alias =
1106 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1107 Class = Alias->getClassInterface();
1111 DiagnoseUseOfDecl(Class, NameLoc);
1113 if (NextToken.is(tok::period)) {
1114 // Interface. <something> is parsed as a property reference expression.
1115 // Just return "unknown" as a fall-through for now.
1116 Result.suppressDiagnostics();
1117 return NameClassification::Unknown();
1120 QualType T = Context.getObjCInterfaceType(Class);
1121 return ParsedType::make(T);
1124 // We can have a type template here if we're classifying a template argument.
1125 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1126 !isa<VarTemplateDecl>(FirstDecl))
1127 return NameClassification::TypeTemplate(
1128 TemplateName(cast<TemplateDecl>(FirstDecl)));
1130 // Check for a tag type hidden by a non-type decl in a few cases where it
1131 // seems likely a type is wanted instead of the non-type that was found.
1132 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1133 if ((NextToken.is(tok::identifier) ||
1135 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1136 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1137 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1138 DiagnoseUseOfDecl(Type, NameLoc);
1139 QualType T = Context.getTypeDeclType(Type);
1140 if (SS.isNotEmpty())
1141 return buildNestedType(*this, SS, T, NameLoc);
1142 return ParsedType::make(T);
1145 if (FirstDecl->isCXXClassMember())
1146 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1150 return BuildDeclarationNameExpr(SS, Result, ADL);
1153 Sema::TemplateNameKindForDiagnostics
1154 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1155 auto *TD = Name.getAsTemplateDecl();
1157 return TemplateNameKindForDiagnostics::DependentTemplate;
1158 if (isa<ClassTemplateDecl>(TD))
1159 return TemplateNameKindForDiagnostics::ClassTemplate;
1160 if (isa<FunctionTemplateDecl>(TD))
1161 return TemplateNameKindForDiagnostics::FunctionTemplate;
1162 if (isa<VarTemplateDecl>(TD))
1163 return TemplateNameKindForDiagnostics::VarTemplate;
1164 if (isa<TypeAliasTemplateDecl>(TD))
1165 return TemplateNameKindForDiagnostics::AliasTemplate;
1166 if (isa<TemplateTemplateParmDecl>(TD))
1167 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1168 return TemplateNameKindForDiagnostics::DependentTemplate;
1171 // Determines the context to return to after temporarily entering a
1172 // context. This depends in an unnecessarily complicated way on the
1173 // exact ordering of callbacks from the parser.
1174 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1176 // Functions defined inline within classes aren't parsed until we've
1177 // finished parsing the top-level class, so the top-level class is
1178 // the context we'll need to return to.
1179 // A Lambda call operator whose parent is a class must not be treated
1180 // as an inline member function. A Lambda can be used legally
1181 // either as an in-class member initializer or a default argument. These
1182 // are parsed once the class has been marked complete and so the containing
1183 // context would be the nested class (when the lambda is defined in one);
1184 // If the class is not complete, then the lambda is being used in an
1185 // ill-formed fashion (such as to specify the width of a bit-field, or
1186 // in an array-bound) - in which case we still want to return the
1187 // lexically containing DC (which could be a nested class).
1188 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1189 DC = DC->getLexicalParent();
1191 // A function not defined within a class will always return to its
1193 if (!isa<CXXRecordDecl>(DC))
1196 // A C++ inline method/friend is parsed *after* the topmost class
1197 // it was declared in is fully parsed ("complete"); the topmost
1198 // class is the context we need to return to.
1199 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202 // Return the declaration context of the topmost class the inline method is
1207 return DC->getLexicalParent();
1210 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1211 assert(getContainingDC(DC) == CurContext &&
1212 "The next DeclContext should be lexically contained in the current one.");
1217 void Sema::PopDeclContext() {
1218 assert(CurContext && "DeclContext imbalance!");
1220 CurContext = getContainingDC(CurContext);
1221 assert(CurContext && "Popped translation unit!");
1224 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1226 // Unlike PushDeclContext, the context to which we return is not necessarily
1227 // the containing DC of TD, because the new context will be some pre-existing
1228 // TagDecl definition instead of a fresh one.
1229 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1230 CurContext = cast<TagDecl>(D)->getDefinition();
1231 assert(CurContext && "skipping definition of undefined tag");
1232 // Start lookups from the parent of the current context; we don't want to look
1233 // into the pre-existing complete definition.
1234 S->setEntity(CurContext->getLookupParent());
1238 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1239 CurContext = static_cast<decltype(CurContext)>(Context);
1242 /// EnterDeclaratorContext - Used when we must lookup names in the context
1243 /// of a declarator's nested name specifier.
1245 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1246 // C++0x [basic.lookup.unqual]p13:
1247 // A name used in the definition of a static data member of class
1248 // X (after the qualified-id of the static member) is looked up as
1249 // if the name was used in a member function of X.
1250 // C++0x [basic.lookup.unqual]p14:
1251 // If a variable member of a namespace is defined outside of the
1252 // scope of its namespace then any name used in the definition of
1253 // the variable member (after the declarator-id) is looked up as
1254 // if the definition of the variable member occurred in its
1256 // Both of these imply that we should push a scope whose context
1257 // is the semantic context of the declaration. We can't use
1258 // PushDeclContext here because that context is not necessarily
1259 // lexically contained in the current context. Fortunately,
1260 // the containing scope should have the appropriate information.
1262 assert(!S->getEntity() && "scope already has entity");
1265 Scope *Ancestor = S->getParent();
1266 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1267 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1274 void Sema::ExitDeclaratorContext(Scope *S) {
1275 assert(S->getEntity() == CurContext && "Context imbalance!");
1277 // Switch back to the lexical context. The safety of this is
1278 // enforced by an assert in EnterDeclaratorContext.
1279 Scope *Ancestor = S->getParent();
1280 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1281 CurContext = Ancestor->getEntity();
1283 // We don't need to do anything with the scope, which is going to
1287 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1288 // We assume that the caller has already called
1289 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1290 FunctionDecl *FD = D->getAsFunction();
1294 // Same implementation as PushDeclContext, but enters the context
1295 // from the lexical parent, rather than the top-level class.
1296 assert(CurContext == FD->getLexicalParent() &&
1297 "The next DeclContext should be lexically contained in the current one.");
1299 S->setEntity(CurContext);
1301 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1302 ParmVarDecl *Param = FD->getParamDecl(P);
1303 // If the parameter has an identifier, then add it to the scope
1304 if (Param->getIdentifier()) {
1306 IdResolver.AddDecl(Param);
1311 void Sema::ActOnExitFunctionContext() {
1312 // Same implementation as PopDeclContext, but returns to the lexical parent,
1313 // rather than the top-level class.
1314 assert(CurContext && "DeclContext imbalance!");
1315 CurContext = CurContext->getLexicalParent();
1316 assert(CurContext && "Popped translation unit!");
1319 /// \brief Determine whether we allow overloading of the function
1320 /// PrevDecl with another declaration.
1322 /// This routine determines whether overloading is possible, not
1323 /// whether some new function is actually an overload. It will return
1324 /// true in C++ (where we can always provide overloads) or, as an
1325 /// extension, in C when the previous function is already an
1326 /// overloaded function declaration or has the "overloadable"
1328 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1329 ASTContext &Context) {
1330 if (Context.getLangOpts().CPlusPlus)
1333 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1336 return (Previous.getResultKind() == LookupResult::Found
1337 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1340 /// Add this decl to the scope shadowed decl chains.
1341 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1342 // Move up the scope chain until we find the nearest enclosing
1343 // non-transparent context. The declaration will be introduced into this
1345 while (S->getEntity() && S->getEntity()->isTransparentContext())
1348 // Add scoped declarations into their context, so that they can be
1349 // found later. Declarations without a context won't be inserted
1350 // into any context.
1352 CurContext->addDecl(D);
1354 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1355 // are function-local declarations.
1356 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1357 !D->getDeclContext()->getRedeclContext()->Equals(
1358 D->getLexicalDeclContext()->getRedeclContext()) &&
1359 !D->getLexicalDeclContext()->isFunctionOrMethod())
1362 // Template instantiations should also not be pushed into scope.
1363 if (isa<FunctionDecl>(D) &&
1364 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1367 // If this replaces anything in the current scope,
1368 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1369 IEnd = IdResolver.end();
1370 for (; I != IEnd; ++I) {
1371 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1373 IdResolver.RemoveDecl(*I);
1375 // Should only need to replace one decl.
1382 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1383 // Implicitly-generated labels may end up getting generated in an order that
1384 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1385 // the label at the appropriate place in the identifier chain.
1386 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1387 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1388 if (IDC == CurContext) {
1389 if (!S->isDeclScope(*I))
1391 } else if (IDC->Encloses(CurContext))
1395 IdResolver.InsertDeclAfter(I, D);
1397 IdResolver.AddDecl(D);
1401 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1402 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1403 TUScope->AddDecl(D);
1406 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1407 bool AllowInlineNamespace) {
1408 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1411 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1412 DeclContext *TargetDC = DC->getPrimaryContext();
1414 if (DeclContext *ScopeDC = S->getEntity())
1415 if (ScopeDC->getPrimaryContext() == TargetDC)
1417 } while ((S = S->getParent()));
1422 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1426 /// Filters out lookup results that don't fall within the given scope
1427 /// as determined by isDeclInScope.
1428 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1429 bool ConsiderLinkage,
1430 bool AllowInlineNamespace) {
1431 LookupResult::Filter F = R.makeFilter();
1432 while (F.hasNext()) {
1433 NamedDecl *D = F.next();
1435 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1438 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1447 static bool isUsingDecl(NamedDecl *D) {
1448 return isa<UsingShadowDecl>(D) ||
1449 isa<UnresolvedUsingTypenameDecl>(D) ||
1450 isa<UnresolvedUsingValueDecl>(D);
1453 /// Removes using shadow declarations from the lookup results.
1454 static void RemoveUsingDecls(LookupResult &R) {
1455 LookupResult::Filter F = R.makeFilter();
1457 if (isUsingDecl(F.next()))
1463 /// \brief Check for this common pattern:
1466 /// S(const S&); // DO NOT IMPLEMENT
1467 /// void operator=(const S&); // DO NOT IMPLEMENT
1470 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1471 // FIXME: Should check for private access too but access is set after we get
1473 if (D->doesThisDeclarationHaveABody())
1476 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1477 return CD->isCopyConstructor();
1478 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1479 return Method->isCopyAssignmentOperator();
1483 // We need this to handle
1486 // void *foo() { return 0; }
1489 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1490 // for example. If 'A', foo will have external linkage. If we have '*A',
1491 // foo will have no linkage. Since we can't know until we get to the end
1492 // of the typedef, this function finds out if D might have non-external linkage.
1493 // Callers should verify at the end of the TU if it D has external linkage or
1495 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1496 const DeclContext *DC = D->getDeclContext();
1497 while (!DC->isTranslationUnit()) {
1498 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1499 if (!RD->hasNameForLinkage())
1502 DC = DC->getParent();
1505 return !D->isExternallyVisible();
1508 // FIXME: This needs to be refactored; some other isInMainFile users want
1510 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1511 if (S.TUKind != TU_Complete)
1513 return S.SourceMgr.isInMainFile(Loc);
1516 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1519 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1522 // Ignore all entities declared within templates, and out-of-line definitions
1523 // of members of class templates.
1524 if (D->getDeclContext()->isDependentContext() ||
1525 D->getLexicalDeclContext()->isDependentContext())
1528 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1529 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1531 // A non-out-of-line declaration of a member specialization was implicitly
1532 // instantiated; it's the out-of-line declaration that we're interested in.
1533 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1534 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1537 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1538 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1541 // 'static inline' functions are defined in headers; don't warn.
1542 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1546 if (FD->doesThisDeclarationHaveABody() &&
1547 Context.DeclMustBeEmitted(FD))
1549 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1550 // Constants and utility variables are defined in headers with internal
1551 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1553 if (!isMainFileLoc(*this, VD->getLocation()))
1556 if (Context.DeclMustBeEmitted(VD))
1559 if (VD->isStaticDataMember() &&
1560 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1562 if (VD->isStaticDataMember() &&
1563 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1564 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1567 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1573 // Only warn for unused decls internal to the translation unit.
1574 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1575 // for inline functions defined in the main source file, for instance.
1576 return mightHaveNonExternalLinkage(D);
1579 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1583 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1584 const FunctionDecl *First = FD->getFirstDecl();
1585 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1586 return; // First should already be in the vector.
1589 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1590 const VarDecl *First = VD->getFirstDecl();
1591 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1592 return; // First should already be in the vector.
1595 if (ShouldWarnIfUnusedFileScopedDecl(D))
1596 UnusedFileScopedDecls.push_back(D);
1599 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1600 if (D->isInvalidDecl())
1603 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1604 D->hasAttr<ObjCPreciseLifetimeAttr>())
1607 if (isa<LabelDecl>(D))
1610 // Except for labels, we only care about unused decls that are local to
1612 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1613 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1614 // For dependent types, the diagnostic is deferred.
1616 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1617 if (!WithinFunction)
1620 if (isa<TypedefNameDecl>(D))
1623 // White-list anything that isn't a local variable.
1624 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1627 // Types of valid local variables should be complete, so this should succeed.
1628 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1630 // White-list anything with an __attribute__((unused)) type.
1631 const auto *Ty = VD->getType().getTypePtr();
1633 // Only look at the outermost level of typedef.
1634 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1635 if (TT->getDecl()->hasAttr<UnusedAttr>())
1639 // If we failed to complete the type for some reason, or if the type is
1640 // dependent, don't diagnose the variable.
1641 if (Ty->isIncompleteType() || Ty->isDependentType())
1644 // Look at the element type to ensure that the warning behaviour is
1645 // consistent for both scalars and arrays.
1646 Ty = Ty->getBaseElementTypeUnsafe();
1648 if (const TagType *TT = Ty->getAs<TagType>()) {
1649 const TagDecl *Tag = TT->getDecl();
1650 if (Tag->hasAttr<UnusedAttr>())
1653 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1654 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1657 if (const Expr *Init = VD->getInit()) {
1658 if (const ExprWithCleanups *Cleanups =
1659 dyn_cast<ExprWithCleanups>(Init))
1660 Init = Cleanups->getSubExpr();
1661 const CXXConstructExpr *Construct =
1662 dyn_cast<CXXConstructExpr>(Init);
1663 if (Construct && !Construct->isElidable()) {
1664 CXXConstructorDecl *CD = Construct->getConstructor();
1665 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1672 // TODO: __attribute__((unused)) templates?
1678 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1680 if (isa<LabelDecl>(D)) {
1681 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1682 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1683 if (AfterColon.isInvalid())
1685 Hint = FixItHint::CreateRemoval(CharSourceRange::
1686 getCharRange(D->getLocStart(), AfterColon));
1690 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1691 if (D->getTypeForDecl()->isDependentType())
1694 for (auto *TmpD : D->decls()) {
1695 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1696 DiagnoseUnusedDecl(T);
1697 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1698 DiagnoseUnusedNestedTypedefs(R);
1702 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1703 /// unless they are marked attr(unused).
1704 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1705 if (!ShouldDiagnoseUnusedDecl(D))
1708 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1709 // typedefs can be referenced later on, so the diagnostics are emitted
1710 // at end-of-translation-unit.
1711 UnusedLocalTypedefNameCandidates.insert(TD);
1716 GenerateFixForUnusedDecl(D, Context, Hint);
1719 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1720 DiagID = diag::warn_unused_exception_param;
1721 else if (isa<LabelDecl>(D))
1722 DiagID = diag::warn_unused_label;
1724 DiagID = diag::warn_unused_variable;
1726 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1729 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1730 // Verify that we have no forward references left. If so, there was a goto
1731 // or address of a label taken, but no definition of it. Label fwd
1732 // definitions are indicated with a null substmt which is also not a resolved
1733 // MS inline assembly label name.
1734 bool Diagnose = false;
1735 if (L->isMSAsmLabel())
1736 Diagnose = !L->isResolvedMSAsmLabel();
1738 Diagnose = L->getStmt() == nullptr;
1740 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1743 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1744 S->mergeNRVOIntoParent();
1746 if (S->decl_empty()) return;
1747 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1748 "Scope shouldn't contain decls!");
1750 for (auto *TmpD : S->decls()) {
1751 assert(TmpD && "This decl didn't get pushed??");
1753 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1754 NamedDecl *D = cast<NamedDecl>(TmpD);
1756 if (!D->getDeclName()) continue;
1758 // Diagnose unused variables in this scope.
1759 if (!S->hasUnrecoverableErrorOccurred()) {
1760 DiagnoseUnusedDecl(D);
1761 if (const auto *RD = dyn_cast<RecordDecl>(D))
1762 DiagnoseUnusedNestedTypedefs(RD);
1765 // If this was a forward reference to a label, verify it was defined.
1766 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1767 CheckPoppedLabel(LD, *this);
1769 // Remove this name from our lexical scope, and warn on it if we haven't
1771 IdResolver.RemoveDecl(D);
1772 auto ShadowI = ShadowingDecls.find(D);
1773 if (ShadowI != ShadowingDecls.end()) {
1774 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1775 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1776 << D << FD << FD->getParent();
1777 Diag(FD->getLocation(), diag::note_previous_declaration);
1779 ShadowingDecls.erase(ShadowI);
1784 /// \brief Look for an Objective-C class in the translation unit.
1786 /// \param Id The name of the Objective-C class we're looking for. If
1787 /// typo-correction fixes this name, the Id will be updated
1788 /// to the fixed name.
1790 /// \param IdLoc The location of the name in the translation unit.
1792 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1793 /// if there is no class with the given name.
1795 /// \returns The declaration of the named Objective-C class, or NULL if the
1796 /// class could not be found.
1797 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1798 SourceLocation IdLoc,
1799 bool DoTypoCorrection) {
1800 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1801 // creation from this context.
1802 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1804 if (!IDecl && DoTypoCorrection) {
1805 // Perform typo correction at the given location, but only if we
1806 // find an Objective-C class name.
1807 if (TypoCorrection C = CorrectTypo(
1808 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1809 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1810 CTK_ErrorRecovery)) {
1811 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1812 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1813 Id = IDecl->getIdentifier();
1816 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1817 // This routine must always return a class definition, if any.
1818 if (Def && Def->getDefinition())
1819 Def = Def->getDefinition();
1823 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1824 /// from S, where a non-field would be declared. This routine copes
1825 /// with the difference between C and C++ scoping rules in structs and
1826 /// unions. For example, the following code is well-formed in C but
1827 /// ill-formed in C++:
1833 /// void test_S6() {
1838 /// For the declaration of BAR, this routine will return a different
1839 /// scope. The scope S will be the scope of the unnamed enumeration
1840 /// within S6. In C++, this routine will return the scope associated
1841 /// with S6, because the enumeration's scope is a transparent
1842 /// context but structures can contain non-field names. In C, this
1843 /// routine will return the translation unit scope, since the
1844 /// enumeration's scope is a transparent context and structures cannot
1845 /// contain non-field names.
1846 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1847 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1848 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1849 (S->isClassScope() && !getLangOpts().CPlusPlus))
1854 /// \brief Looks up the declaration of "struct objc_super" and
1855 /// saves it for later use in building builtin declaration of
1856 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1857 /// pre-existing declaration exists no action takes place.
1858 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1859 IdentifierInfo *II) {
1860 if (!II->isStr("objc_msgSendSuper"))
1862 ASTContext &Context = ThisSema.Context;
1864 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1865 SourceLocation(), Sema::LookupTagName);
1866 ThisSema.LookupName(Result, S);
1867 if (Result.getResultKind() == LookupResult::Found)
1868 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1869 Context.setObjCSuperType(Context.getTagDeclType(TD));
1872 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1874 case ASTContext::GE_None:
1876 case ASTContext::GE_Missing_stdio:
1878 case ASTContext::GE_Missing_setjmp:
1880 case ASTContext::GE_Missing_ucontext:
1881 return "ucontext.h";
1883 llvm_unreachable("unhandled error kind");
1886 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1887 /// file scope. lazily create a decl for it. ForRedeclaration is true
1888 /// if we're creating this built-in in anticipation of redeclaring the
1890 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1891 Scope *S, bool ForRedeclaration,
1892 SourceLocation Loc) {
1893 LookupPredefedObjCSuperType(*this, S, II);
1895 ASTContext::GetBuiltinTypeError Error;
1896 QualType R = Context.GetBuiltinType(ID, Error);
1898 if (ForRedeclaration)
1899 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1900 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1904 if (!ForRedeclaration &&
1905 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1906 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1907 Diag(Loc, diag::ext_implicit_lib_function_decl)
1908 << Context.BuiltinInfo.getName(ID) << R;
1909 if (Context.BuiltinInfo.getHeaderName(ID) &&
1910 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1911 Diag(Loc, diag::note_include_header_or_declare)
1912 << Context.BuiltinInfo.getHeaderName(ID)
1913 << Context.BuiltinInfo.getName(ID);
1919 DeclContext *Parent = Context.getTranslationUnitDecl();
1920 if (getLangOpts().CPlusPlus) {
1921 LinkageSpecDecl *CLinkageDecl =
1922 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1923 LinkageSpecDecl::lang_c, false);
1924 CLinkageDecl->setImplicit();
1925 Parent->addDecl(CLinkageDecl);
1926 Parent = CLinkageDecl;
1929 FunctionDecl *New = FunctionDecl::Create(Context,
1931 Loc, Loc, II, R, /*TInfo=*/nullptr,
1934 R->isFunctionProtoType());
1937 // Create Decl objects for each parameter, adding them to the
1939 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1940 SmallVector<ParmVarDecl*, 16> Params;
1941 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1943 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1944 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1946 parm->setScopeInfo(0, i);
1947 Params.push_back(parm);
1949 New->setParams(Params);
1952 AddKnownFunctionAttributes(New);
1953 RegisterLocallyScopedExternCDecl(New, S);
1955 // TUScope is the translation-unit scope to insert this function into.
1956 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1957 // relate Scopes to DeclContexts, and probably eliminate CurContext
1958 // entirely, but we're not there yet.
1959 DeclContext *SavedContext = CurContext;
1960 CurContext = Parent;
1961 PushOnScopeChains(New, TUScope);
1962 CurContext = SavedContext;
1966 /// Typedef declarations don't have linkage, but they still denote the same
1967 /// entity if their types are the same.
1968 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1970 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1971 TypedefNameDecl *Decl,
1972 LookupResult &Previous) {
1973 // This is only interesting when modules are enabled.
1974 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1977 // Empty sets are uninteresting.
1978 if (Previous.empty())
1981 LookupResult::Filter Filter = Previous.makeFilter();
1982 while (Filter.hasNext()) {
1983 NamedDecl *Old = Filter.next();
1985 // Non-hidden declarations are never ignored.
1986 if (S.isVisible(Old))
1989 // Declarations of the same entity are not ignored, even if they have
1990 // different linkages.
1991 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1992 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1993 Decl->getUnderlyingType()))
1996 // If both declarations give a tag declaration a typedef name for linkage
1997 // purposes, then they declare the same entity.
1998 if (S.getLangOpts().CPlusPlus &&
1999 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2000 Decl->getAnonDeclWithTypedefName())
2010 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2012 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2013 OldType = OldTypedef->getUnderlyingType();
2015 OldType = Context.getTypeDeclType(Old);
2016 QualType NewType = New->getUnderlyingType();
2018 if (NewType->isVariablyModifiedType()) {
2019 // Must not redefine a typedef with a variably-modified type.
2020 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2021 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2023 if (Old->getLocation().isValid())
2024 notePreviousDefinition(Old, New->getLocation());
2025 New->setInvalidDecl();
2029 if (OldType != NewType &&
2030 !OldType->isDependentType() &&
2031 !NewType->isDependentType() &&
2032 !Context.hasSameType(OldType, NewType)) {
2033 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2034 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2035 << Kind << NewType << OldType;
2036 if (Old->getLocation().isValid())
2037 notePreviousDefinition(Old, New->getLocation());
2038 New->setInvalidDecl();
2044 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2045 /// same name and scope as a previous declaration 'Old'. Figure out
2046 /// how to resolve this situation, merging decls or emitting
2047 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2049 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2050 LookupResult &OldDecls) {
2051 // If the new decl is known invalid already, don't bother doing any
2053 if (New->isInvalidDecl()) return;
2055 // Allow multiple definitions for ObjC built-in typedefs.
2056 // FIXME: Verify the underlying types are equivalent!
2057 if (getLangOpts().ObjC1) {
2058 const IdentifierInfo *TypeID = New->getIdentifier();
2059 switch (TypeID->getLength()) {
2063 if (!TypeID->isStr("id"))
2065 QualType T = New->getUnderlyingType();
2066 if (!T->isPointerType())
2068 if (!T->isVoidPointerType()) {
2069 QualType PT = T->getAs<PointerType>()->getPointeeType();
2070 if (!PT->isStructureType())
2073 Context.setObjCIdRedefinitionType(T);
2074 // Install the built-in type for 'id', ignoring the current definition.
2075 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2079 if (!TypeID->isStr("Class"))
2081 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2082 // Install the built-in type for 'Class', ignoring the current definition.
2083 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2086 if (!TypeID->isStr("SEL"))
2088 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2089 // Install the built-in type for 'SEL', ignoring the current definition.
2090 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2093 // Fall through - the typedef name was not a builtin type.
2096 // Verify the old decl was also a type.
2097 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2099 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2100 << New->getDeclName();
2102 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2103 if (OldD->getLocation().isValid())
2104 notePreviousDefinition(OldD, New->getLocation());
2106 return New->setInvalidDecl();
2109 // If the old declaration is invalid, just give up here.
2110 if (Old->isInvalidDecl())
2111 return New->setInvalidDecl();
2113 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2114 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2115 auto *NewTag = New->getAnonDeclWithTypedefName();
2116 NamedDecl *Hidden = nullptr;
2117 if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2118 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2119 !hasVisibleDefinition(OldTag, &Hidden)) {
2120 // There is a definition of this tag, but it is not visible. Use it
2121 // instead of our tag.
2122 New->setTypeForDecl(OldTD->getTypeForDecl());
2123 if (OldTD->isModed())
2124 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2125 OldTD->getUnderlyingType());
2127 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2129 // Make the old tag definition visible.
2130 makeMergedDefinitionVisible(Hidden);
2132 // If this was an unscoped enumeration, yank all of its enumerators
2133 // out of the scope.
2134 if (isa<EnumDecl>(NewTag)) {
2135 Scope *EnumScope = getNonFieldDeclScope(S);
2136 for (auto *D : NewTag->decls()) {
2137 auto *ED = cast<EnumConstantDecl>(D);
2138 assert(EnumScope->isDeclScope(ED));
2139 EnumScope->RemoveDecl(ED);
2140 IdResolver.RemoveDecl(ED);
2141 ED->getLexicalDeclContext()->removeDecl(ED);
2147 // If the typedef types are not identical, reject them in all languages and
2148 // with any extensions enabled.
2149 if (isIncompatibleTypedef(Old, New))
2152 // The types match. Link up the redeclaration chain and merge attributes if
2153 // the old declaration was a typedef.
2154 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2155 New->setPreviousDecl(Typedef);
2156 mergeDeclAttributes(New, Old);
2159 if (getLangOpts().MicrosoftExt)
2162 if (getLangOpts().CPlusPlus) {
2163 // C++ [dcl.typedef]p2:
2164 // In a given non-class scope, a typedef specifier can be used to
2165 // redefine the name of any type declared in that scope to refer
2166 // to the type to which it already refers.
2167 if (!isa<CXXRecordDecl>(CurContext))
2170 // C++0x [dcl.typedef]p4:
2171 // In a given class scope, a typedef specifier can be used to redefine
2172 // any class-name declared in that scope that is not also a typedef-name
2173 // to refer to the type to which it already refers.
2175 // This wording came in via DR424, which was a correction to the
2176 // wording in DR56, which accidentally banned code like:
2179 // typedef struct A { } A;
2182 // in the C++03 standard. We implement the C++0x semantics, which
2183 // allow the above but disallow
2190 // since that was the intent of DR56.
2191 if (!isa<TypedefNameDecl>(Old))
2194 Diag(New->getLocation(), diag::err_redefinition)
2195 << New->getDeclName();
2196 notePreviousDefinition(Old, New->getLocation());
2197 return New->setInvalidDecl();
2200 // Modules always permit redefinition of typedefs, as does C11.
2201 if (getLangOpts().Modules || getLangOpts().C11)
2204 // If we have a redefinition of a typedef in C, emit a warning. This warning
2205 // is normally mapped to an error, but can be controlled with
2206 // -Wtypedef-redefinition. If either the original or the redefinition is
2207 // in a system header, don't emit this for compatibility with GCC.
2208 if (getDiagnostics().getSuppressSystemWarnings() &&
2209 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2210 (Old->isImplicit() ||
2211 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2212 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2215 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2216 << New->getDeclName();
2217 notePreviousDefinition(Old, New->getLocation());
2220 /// DeclhasAttr - returns true if decl Declaration already has the target
2222 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2223 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2224 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2225 for (const auto *i : D->attrs())
2226 if (i->getKind() == A->getKind()) {
2228 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2232 // FIXME: Don't hardcode this check
2233 if (OA && isa<OwnershipAttr>(i))
2234 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2241 static bool isAttributeTargetADefinition(Decl *D) {
2242 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2243 return VD->isThisDeclarationADefinition();
2244 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2245 return TD->isCompleteDefinition() || TD->isBeingDefined();
2249 /// Merge alignment attributes from \p Old to \p New, taking into account the
2250 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2252 /// \return \c true if any attributes were added to \p New.
2253 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2254 // Look for alignas attributes on Old, and pick out whichever attribute
2255 // specifies the strictest alignment requirement.
2256 AlignedAttr *OldAlignasAttr = nullptr;
2257 AlignedAttr *OldStrictestAlignAttr = nullptr;
2258 unsigned OldAlign = 0;
2259 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2260 // FIXME: We have no way of representing inherited dependent alignments
2262 // template<int A, int B> struct alignas(A) X;
2263 // template<int A, int B> struct alignas(B) X {};
2264 // For now, we just ignore any alignas attributes which are not on the
2265 // definition in such a case.
2266 if (I->isAlignmentDependent())
2272 unsigned Align = I->getAlignment(S.Context);
2273 if (Align > OldAlign) {
2275 OldStrictestAlignAttr = I;
2279 // Look for alignas attributes on New.
2280 AlignedAttr *NewAlignasAttr = nullptr;
2281 unsigned NewAlign = 0;
2282 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2283 if (I->isAlignmentDependent())
2289 unsigned Align = I->getAlignment(S.Context);
2290 if (Align > NewAlign)
2294 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2295 // Both declarations have 'alignas' attributes. We require them to match.
2296 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2297 // fall short. (If two declarations both have alignas, they must both match
2298 // every definition, and so must match each other if there is a definition.)
2300 // If either declaration only contains 'alignas(0)' specifiers, then it
2301 // specifies the natural alignment for the type.
2302 if (OldAlign == 0 || NewAlign == 0) {
2304 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2307 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2310 OldAlign = S.Context.getTypeAlign(Ty);
2312 NewAlign = S.Context.getTypeAlign(Ty);
2315 if (OldAlign != NewAlign) {
2316 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2317 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2318 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2319 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2323 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2324 // C++11 [dcl.align]p6:
2325 // if any declaration of an entity has an alignment-specifier,
2326 // every defining declaration of that entity shall specify an
2327 // equivalent alignment.
2329 // If the definition of an object does not have an alignment
2330 // specifier, any other declaration of that object shall also
2331 // have no alignment specifier.
2332 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2334 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2338 bool AnyAdded = false;
2340 // Ensure we have an attribute representing the strictest alignment.
2341 if (OldAlign > NewAlign) {
2342 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2343 Clone->setInherited(true);
2344 New->addAttr(Clone);
2348 // Ensure we have an alignas attribute if the old declaration had one.
2349 if (OldAlignasAttr && !NewAlignasAttr &&
2350 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2351 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2352 Clone->setInherited(true);
2353 New->addAttr(Clone);
2360 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2361 const InheritableAttr *Attr,
2362 Sema::AvailabilityMergeKind AMK) {
2363 // This function copies an attribute Attr from a previous declaration to the
2364 // new declaration D if the new declaration doesn't itself have that attribute
2365 // yet or if that attribute allows duplicates.
2366 // If you're adding a new attribute that requires logic different from
2367 // "use explicit attribute on decl if present, else use attribute from
2368 // previous decl", for example if the attribute needs to be consistent
2369 // between redeclarations, you need to call a custom merge function here.
2370 InheritableAttr *NewAttr = nullptr;
2371 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2372 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2373 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2374 AA->isImplicit(), AA->getIntroduced(),
2375 AA->getDeprecated(),
2376 AA->getObsoleted(), AA->getUnavailable(),
2377 AA->getMessage(), AA->getStrict(),
2378 AA->getReplacement(), AMK,
2379 AttrSpellingListIndex);
2380 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2381 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2382 AttrSpellingListIndex);
2383 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2384 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2385 AttrSpellingListIndex);
2386 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2387 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2388 AttrSpellingListIndex);
2389 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2390 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2391 AttrSpellingListIndex);
2392 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2393 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2394 FA->getFormatIdx(), FA->getFirstArg(),
2395 AttrSpellingListIndex);
2396 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2397 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2398 AttrSpellingListIndex);
2399 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2400 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2401 AttrSpellingListIndex,
2402 IA->getSemanticSpelling());
2403 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2404 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2405 &S.Context.Idents.get(AA->getSpelling()),
2406 AttrSpellingListIndex);
2407 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2408 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2409 isa<CUDAGlobalAttr>(Attr))) {
2410 // CUDA target attributes are part of function signature for
2411 // overloading purposes and must not be merged.
2413 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2414 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2415 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2416 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2417 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2418 NewAttr = S.mergeInternalLinkageAttr(
2419 D, InternalLinkageA->getRange(),
2420 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2421 AttrSpellingListIndex);
2422 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2423 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2424 &S.Context.Idents.get(CommonA->getSpelling()),
2425 AttrSpellingListIndex);
2426 else if (isa<AlignedAttr>(Attr))
2427 // AlignedAttrs are handled separately, because we need to handle all
2428 // such attributes on a declaration at the same time.
2430 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2431 (AMK == Sema::AMK_Override ||
2432 AMK == Sema::AMK_ProtocolImplementation))
2434 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2435 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2437 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2438 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2441 NewAttr->setInherited(true);
2442 D->addAttr(NewAttr);
2443 if (isa<MSInheritanceAttr>(NewAttr))
2444 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2451 static const NamedDecl *getDefinition(const Decl *D) {
2452 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2453 return TD->getDefinition();
2454 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2455 const VarDecl *Def = VD->getDefinition();
2458 return VD->getActingDefinition();
2460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2461 return FD->getDefinition();
2465 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2466 for (const auto *Attribute : D->attrs())
2467 if (Attribute->getKind() == Kind)
2472 /// checkNewAttributesAfterDef - If we already have a definition, check that
2473 /// there are no new attributes in this declaration.
2474 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2475 if (!New->hasAttrs())
2478 const NamedDecl *Def = getDefinition(Old);
2479 if (!Def || Def == New)
2482 AttrVec &NewAttributes = New->getAttrs();
2483 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2484 const Attr *NewAttribute = NewAttributes[I];
2486 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2487 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2488 Sema::SkipBodyInfo SkipBody;
2489 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2491 // If we're skipping this definition, drop the "alias" attribute.
2492 if (SkipBody.ShouldSkip) {
2493 NewAttributes.erase(NewAttributes.begin() + I);
2498 VarDecl *VD = cast<VarDecl>(New);
2499 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2500 VarDecl::TentativeDefinition
2501 ? diag::err_alias_after_tentative
2502 : diag::err_redefinition;
2503 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2504 if (Diag == diag::err_redefinition)
2505 S.notePreviousDefinition(Def, VD->getLocation());
2507 S.Diag(Def->getLocation(), diag::note_previous_definition);
2508 VD->setInvalidDecl();
2514 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2515 // Tentative definitions are only interesting for the alias check above.
2516 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2522 if (hasAttribute(Def, NewAttribute->getKind())) {
2524 continue; // regular attr merging will take care of validating this.
2527 if (isa<C11NoReturnAttr>(NewAttribute)) {
2528 // C's _Noreturn is allowed to be added to a function after it is defined.
2531 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2532 if (AA->isAlignas()) {
2533 // C++11 [dcl.align]p6:
2534 // if any declaration of an entity has an alignment-specifier,
2535 // every defining declaration of that entity shall specify an
2536 // equivalent alignment.
2538 // If the definition of an object does not have an alignment
2539 // specifier, any other declaration of that object shall also
2540 // have no alignment specifier.
2541 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2543 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2545 NewAttributes.erase(NewAttributes.begin() + I);
2551 S.Diag(NewAttribute->getLocation(),
2552 diag::warn_attribute_precede_definition);
2553 S.Diag(Def->getLocation(), diag::note_previous_definition);
2554 NewAttributes.erase(NewAttributes.begin() + I);
2559 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2560 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2561 AvailabilityMergeKind AMK) {
2562 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2563 UsedAttr *NewAttr = OldAttr->clone(Context);
2564 NewAttr->setInherited(true);
2565 New->addAttr(NewAttr);
2568 if (!Old->hasAttrs() && !New->hasAttrs())
2571 // Attributes declared post-definition are currently ignored.
2572 checkNewAttributesAfterDef(*this, New, Old);
2574 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2575 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2576 if (OldA->getLabel() != NewA->getLabel()) {
2577 // This redeclaration changes __asm__ label.
2578 Diag(New->getLocation(), diag::err_different_asm_label);
2579 Diag(OldA->getLocation(), diag::note_previous_declaration);
2581 } else if (Old->isUsed()) {
2582 // This redeclaration adds an __asm__ label to a declaration that has
2583 // already been ODR-used.
2584 Diag(New->getLocation(), diag::err_late_asm_label_name)
2585 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2589 // Re-declaration cannot add abi_tag's.
2590 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2591 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2592 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2593 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2594 NewTag) == OldAbiTagAttr->tags_end()) {
2595 Diag(NewAbiTagAttr->getLocation(),
2596 diag::err_new_abi_tag_on_redeclaration)
2598 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2602 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2603 Diag(Old->getLocation(), diag::note_previous_declaration);
2607 if (!Old->hasAttrs())
2610 bool foundAny = New->hasAttrs();
2612 // Ensure that any moving of objects within the allocated map is done before
2614 if (!foundAny) New->setAttrs(AttrVec());
2616 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2617 // Ignore deprecated/unavailable/availability attributes if requested.
2618 AvailabilityMergeKind LocalAMK = AMK_None;
2619 if (isa<DeprecatedAttr>(I) ||
2620 isa<UnavailableAttr>(I) ||
2621 isa<AvailabilityAttr>(I)) {
2626 case AMK_Redeclaration:
2628 case AMK_ProtocolImplementation:
2635 if (isa<UsedAttr>(I))
2638 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2642 if (mergeAlignedAttrs(*this, New, Old))
2645 if (!foundAny) New->dropAttrs();
2648 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2650 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2651 const ParmVarDecl *oldDecl,
2653 // C++11 [dcl.attr.depend]p2:
2654 // The first declaration of a function shall specify the
2655 // carries_dependency attribute for its declarator-id if any declaration
2656 // of the function specifies the carries_dependency attribute.
2657 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2658 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2659 S.Diag(CDA->getLocation(),
2660 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2661 // Find the first declaration of the parameter.
2662 // FIXME: Should we build redeclaration chains for function parameters?
2663 const FunctionDecl *FirstFD =
2664 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2665 const ParmVarDecl *FirstVD =
2666 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2667 S.Diag(FirstVD->getLocation(),
2668 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2671 if (!oldDecl->hasAttrs())
2674 bool foundAny = newDecl->hasAttrs();
2676 // Ensure that any moving of objects within the allocated map is
2677 // done before we process them.
2678 if (!foundAny) newDecl->setAttrs(AttrVec());
2680 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2681 if (!DeclHasAttr(newDecl, I)) {
2682 InheritableAttr *newAttr =
2683 cast<InheritableParamAttr>(I->clone(S.Context));
2684 newAttr->setInherited(true);
2685 newDecl->addAttr(newAttr);
2690 if (!foundAny) newDecl->dropAttrs();
2693 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2694 const ParmVarDecl *OldParam,
2696 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2697 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2698 if (*Oldnullability != *Newnullability) {
2699 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2700 << DiagNullabilityKind(
2702 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2704 << DiagNullabilityKind(
2706 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2708 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2711 QualType NewT = NewParam->getType();
2712 NewT = S.Context.getAttributedType(
2713 AttributedType::getNullabilityAttrKind(*Oldnullability),
2715 NewParam->setType(NewT);
2722 /// Used in MergeFunctionDecl to keep track of function parameters in
2724 struct GNUCompatibleParamWarning {
2725 ParmVarDecl *OldParm;
2726 ParmVarDecl *NewParm;
2727 QualType PromotedType;
2730 } // end anonymous namespace
2732 /// getSpecialMember - get the special member enum for a method.
2733 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2734 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2735 if (Ctor->isDefaultConstructor())
2736 return Sema::CXXDefaultConstructor;
2738 if (Ctor->isCopyConstructor())
2739 return Sema::CXXCopyConstructor;
2741 if (Ctor->isMoveConstructor())
2742 return Sema::CXXMoveConstructor;
2743 } else if (isa<CXXDestructorDecl>(MD)) {
2744 return Sema::CXXDestructor;
2745 } else if (MD->isCopyAssignmentOperator()) {
2746 return Sema::CXXCopyAssignment;
2747 } else if (MD->isMoveAssignmentOperator()) {
2748 return Sema::CXXMoveAssignment;
2751 return Sema::CXXInvalid;
2754 // Determine whether the previous declaration was a definition, implicit
2755 // declaration, or a declaration.
2756 template <typename T>
2757 static std::pair<diag::kind, SourceLocation>
2758 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2759 diag::kind PrevDiag;
2760 SourceLocation OldLocation = Old->getLocation();
2761 if (Old->isThisDeclarationADefinition())
2762 PrevDiag = diag::note_previous_definition;
2763 else if (Old->isImplicit()) {
2764 PrevDiag = diag::note_previous_implicit_declaration;
2765 if (OldLocation.isInvalid())
2766 OldLocation = New->getLocation();
2768 PrevDiag = diag::note_previous_declaration;
2769 return std::make_pair(PrevDiag, OldLocation);
2772 /// canRedefineFunction - checks if a function can be redefined. Currently,
2773 /// only extern inline functions can be redefined, and even then only in
2775 static bool canRedefineFunction(const FunctionDecl *FD,
2776 const LangOptions& LangOpts) {
2777 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2778 !LangOpts.CPlusPlus &&
2779 FD->isInlineSpecified() &&
2780 FD->getStorageClass() == SC_Extern);
2783 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2784 const AttributedType *AT = T->getAs<AttributedType>();
2785 while (AT && !AT->isCallingConv())
2786 AT = AT->getModifiedType()->getAs<AttributedType>();
2790 template <typename T>
2791 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2792 const DeclContext *DC = Old->getDeclContext();
2796 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2797 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2799 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2804 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2805 static bool isExternC(VarTemplateDecl *) { return false; }
2807 /// \brief Check whether a redeclaration of an entity introduced by a
2808 /// using-declaration is valid, given that we know it's not an overload
2809 /// (nor a hidden tag declaration).
2810 template<typename ExpectedDecl>
2811 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2812 ExpectedDecl *New) {
2813 // C++11 [basic.scope.declarative]p4:
2814 // Given a set of declarations in a single declarative region, each of
2815 // which specifies the same unqualified name,
2816 // -- they shall all refer to the same entity, or all refer to functions
2817 // and function templates; or
2818 // -- exactly one declaration shall declare a class name or enumeration
2819 // name that is not a typedef name and the other declarations shall all
2820 // refer to the same variable or enumerator, or all refer to functions
2821 // and function templates; in this case the class name or enumeration
2822 // name is hidden (3.3.10).
2824 // C++11 [namespace.udecl]p14:
2825 // If a function declaration in namespace scope or block scope has the
2826 // same name and the same parameter-type-list as a function introduced
2827 // by a using-declaration, and the declarations do not declare the same
2828 // function, the program is ill-formed.
2830 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2832 !Old->getDeclContext()->getRedeclContext()->Equals(
2833 New->getDeclContext()->getRedeclContext()) &&
2834 !(isExternC(Old) && isExternC(New)))
2838 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2839 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2840 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2846 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2847 const FunctionDecl *B) {
2848 assert(A->getNumParams() == B->getNumParams());
2850 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2851 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2852 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2855 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2858 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2861 /// MergeFunctionDecl - We just parsed a function 'New' from
2862 /// declarator D which has the same name and scope as a previous
2863 /// declaration 'Old'. Figure out how to resolve this situation,
2864 /// merging decls or emitting diagnostics as appropriate.
2866 /// In C++, New and Old must be declarations that are not
2867 /// overloaded. Use IsOverload to determine whether New and Old are
2868 /// overloaded, and to select the Old declaration that New should be
2871 /// Returns true if there was an error, false otherwise.
2872 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2873 Scope *S, bool MergeTypeWithOld) {
2874 // Verify the old decl was also a function.
2875 FunctionDecl *Old = OldD->getAsFunction();
2877 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2878 if (New->getFriendObjectKind()) {
2879 Diag(New->getLocation(), diag::err_using_decl_friend);
2880 Diag(Shadow->getTargetDecl()->getLocation(),
2881 diag::note_using_decl_target);
2882 Diag(Shadow->getUsingDecl()->getLocation(),
2883 diag::note_using_decl) << 0;
2887 // Check whether the two declarations might declare the same function.
2888 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2890 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2892 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2893 << New->getDeclName();
2894 notePreviousDefinition(OldD, New->getLocation());
2899 // If the old declaration is invalid, just give up here.
2900 if (Old->isInvalidDecl())
2903 diag::kind PrevDiag;
2904 SourceLocation OldLocation;
2905 std::tie(PrevDiag, OldLocation) =
2906 getNoteDiagForInvalidRedeclaration(Old, New);
2908 // Don't complain about this if we're in GNU89 mode and the old function
2909 // is an extern inline function.
2910 // Don't complain about specializations. They are not supposed to have
2912 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2913 New->getStorageClass() == SC_Static &&
2914 Old->hasExternalFormalLinkage() &&
2915 !New->getTemplateSpecializationInfo() &&
2916 !canRedefineFunction(Old, getLangOpts())) {
2917 if (getLangOpts().MicrosoftExt) {
2918 Diag(New->getLocation(), diag::ext_static_non_static) << New;
2919 Diag(OldLocation, PrevDiag);
2921 Diag(New->getLocation(), diag::err_static_non_static) << New;
2922 Diag(OldLocation, PrevDiag);
2927 if (New->hasAttr<InternalLinkageAttr>() &&
2928 !Old->hasAttr<InternalLinkageAttr>()) {
2929 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2930 << New->getDeclName();
2931 notePreviousDefinition(Old, New->getLocation());
2932 New->dropAttr<InternalLinkageAttr>();
2935 // If a function is first declared with a calling convention, but is later
2936 // declared or defined without one, all following decls assume the calling
2937 // convention of the first.
2939 // It's OK if a function is first declared without a calling convention,
2940 // but is later declared or defined with the default calling convention.
2942 // To test if either decl has an explicit calling convention, we look for
2943 // AttributedType sugar nodes on the type as written. If they are missing or
2944 // were canonicalized away, we assume the calling convention was implicit.
2946 // Note also that we DO NOT return at this point, because we still have
2947 // other tests to run.
2948 QualType OldQType = Context.getCanonicalType(Old->getType());
2949 QualType NewQType = Context.getCanonicalType(New->getType());
2950 const FunctionType *OldType = cast<FunctionType>(OldQType);
2951 const FunctionType *NewType = cast<FunctionType>(NewQType);
2952 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2953 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2954 bool RequiresAdjustment = false;
2956 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2957 FunctionDecl *First = Old->getFirstDecl();
2958 const FunctionType *FT =
2959 First->getType().getCanonicalType()->castAs<FunctionType>();
2960 FunctionType::ExtInfo FI = FT->getExtInfo();
2961 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2962 if (!NewCCExplicit) {
2963 // Inherit the CC from the previous declaration if it was specified
2964 // there but not here.
2965 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2966 RequiresAdjustment = true;
2968 // Calling conventions aren't compatible, so complain.
2969 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2970 Diag(New->getLocation(), diag::err_cconv_change)
2971 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2973 << (!FirstCCExplicit ? "" :
2974 FunctionType::getNameForCallConv(FI.getCC()));
2976 // Put the note on the first decl, since it is the one that matters.
2977 Diag(First->getLocation(), diag::note_previous_declaration);
2982 // FIXME: diagnose the other way around?
2983 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2984 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2985 RequiresAdjustment = true;
2988 // Merge regparm attribute.
2989 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2990 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2991 if (NewTypeInfo.getHasRegParm()) {
2992 Diag(New->getLocation(), diag::err_regparm_mismatch)
2993 << NewType->getRegParmType()
2994 << OldType->getRegParmType();
2995 Diag(OldLocation, diag::note_previous_declaration);
2999 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3000 RequiresAdjustment = true;
3003 // Merge ns_returns_retained attribute.
3004 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3005 if (NewTypeInfo.getProducesResult()) {
3006 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3007 << "'ns_returns_retained'";
3008 Diag(OldLocation, diag::note_previous_declaration);
3012 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3013 RequiresAdjustment = true;
3016 if (OldTypeInfo.getNoCallerSavedRegs() !=
3017 NewTypeInfo.getNoCallerSavedRegs()) {
3018 if (NewTypeInfo.getNoCallerSavedRegs()) {
3019 AnyX86NoCallerSavedRegistersAttr *Attr =
3020 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3021 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3022 Diag(OldLocation, diag::note_previous_declaration);
3026 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3027 RequiresAdjustment = true;
3030 if (RequiresAdjustment) {
3031 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3032 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3033 New->setType(QualType(AdjustedType, 0));
3034 NewQType = Context.getCanonicalType(New->getType());
3035 NewType = cast<FunctionType>(NewQType);
3038 // If this redeclaration makes the function inline, we may need to add it to
3039 // UndefinedButUsed.
3040 if (!Old->isInlined() && New->isInlined() &&
3041 !New->hasAttr<GNUInlineAttr>() &&
3042 !getLangOpts().GNUInline &&
3043 Old->isUsed(false) &&
3044 !Old->isDefined() && !New->isThisDeclarationADefinition())
3045 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3048 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3050 if (New->hasAttr<GNUInlineAttr>() &&
3051 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3052 UndefinedButUsed.erase(Old->getCanonicalDecl());
3055 // If pass_object_size params don't match up perfectly, this isn't a valid
3057 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3058 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3059 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3060 << New->getDeclName();
3061 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3065 if (getLangOpts().CPlusPlus) {
3066 // C++1z [over.load]p2
3067 // Certain function declarations cannot be overloaded:
3068 // -- Function declarations that differ only in the return type,
3069 // the exception specification, or both cannot be overloaded.
3071 // Check the exception specifications match. This may recompute the type of
3072 // both Old and New if it resolved exception specifications, so grab the
3073 // types again after this. Because this updates the type, we do this before
3074 // any of the other checks below, which may update the "de facto" NewQType
3075 // but do not necessarily update the type of New.
3076 if (CheckEquivalentExceptionSpec(Old, New))
3078 OldQType = Context.getCanonicalType(Old->getType());
3079 NewQType = Context.getCanonicalType(New->getType());
3081 // Go back to the type source info to compare the declared return types,
3082 // per C++1y [dcl.type.auto]p13:
3083 // Redeclarations or specializations of a function or function template
3084 // with a declared return type that uses a placeholder type shall also
3085 // use that placeholder, not a deduced type.
3086 QualType OldDeclaredReturnType =
3087 (Old->getTypeSourceInfo()
3088 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3089 : OldType)->getReturnType();
3090 QualType NewDeclaredReturnType =
3091 (New->getTypeSourceInfo()
3092 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3093 : NewType)->getReturnType();
3094 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3095 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3096 New->isLocalExternDecl())) {
3098 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3099 OldDeclaredReturnType->isObjCObjectPointerType())
3100 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3101 if (ResQT.isNull()) {
3102 if (New->isCXXClassMember() && New->isOutOfLine())
3103 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3104 << New << New->getReturnTypeSourceRange();
3106 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3107 << New->getReturnTypeSourceRange();
3108 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3109 << Old->getReturnTypeSourceRange();
3116 QualType OldReturnType = OldType->getReturnType();
3117 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3118 if (OldReturnType != NewReturnType) {
3119 // If this function has a deduced return type and has already been
3120 // defined, copy the deduced value from the old declaration.
3121 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3122 if (OldAT && OldAT->isDeduced()) {
3124 SubstAutoType(New->getType(),
3125 OldAT->isDependentType() ? Context.DependentTy
3126 : OldAT->getDeducedType()));
3127 NewQType = Context.getCanonicalType(
3128 SubstAutoType(NewQType,
3129 OldAT->isDependentType() ? Context.DependentTy
3130 : OldAT->getDeducedType()));
3134 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3135 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3136 if (OldMethod && NewMethod) {
3137 // Preserve triviality.
3138 NewMethod->setTrivial(OldMethod->isTrivial());
3140 // MSVC allows explicit template specialization at class scope:
3141 // 2 CXXMethodDecls referring to the same function will be injected.
3142 // We don't want a redeclaration error.
3143 bool IsClassScopeExplicitSpecialization =
3144 OldMethod->isFunctionTemplateSpecialization() &&
3145 NewMethod->isFunctionTemplateSpecialization();
3146 bool isFriend = NewMethod->getFriendObjectKind();
3148 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3149 !IsClassScopeExplicitSpecialization) {
3150 // -- Member function declarations with the same name and the
3151 // same parameter types cannot be overloaded if any of them
3152 // is a static member function declaration.
3153 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3154 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3155 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3159 // C++ [class.mem]p1:
3160 // [...] A member shall not be declared twice in the
3161 // member-specification, except that a nested class or member
3162 // class template can be declared and then later defined.
3163 if (!inTemplateInstantiation()) {
3165 if (isa<CXXConstructorDecl>(OldMethod))
3166 NewDiag = diag::err_constructor_redeclared;
3167 else if (isa<CXXDestructorDecl>(NewMethod))
3168 NewDiag = diag::err_destructor_redeclared;
3169 else if (isa<CXXConversionDecl>(NewMethod))
3170 NewDiag = diag::err_conv_function_redeclared;
3172 NewDiag = diag::err_member_redeclared;
3174 Diag(New->getLocation(), NewDiag);
3176 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3177 << New << New->getType();
3179 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3182 // Complain if this is an explicit declaration of a special
3183 // member that was initially declared implicitly.
3185 // As an exception, it's okay to befriend such methods in order
3186 // to permit the implicit constructor/destructor/operator calls.
3187 } else if (OldMethod->isImplicit()) {
3189 NewMethod->setImplicit();
3191 Diag(NewMethod->getLocation(),
3192 diag::err_definition_of_implicitly_declared_member)
3193 << New << getSpecialMember(OldMethod);
3196 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3197 Diag(NewMethod->getLocation(),
3198 diag::err_definition_of_explicitly_defaulted_member)
3199 << getSpecialMember(OldMethod);
3204 // C++11 [dcl.attr.noreturn]p1:
3205 // The first declaration of a function shall specify the noreturn
3206 // attribute if any declaration of that function specifies the noreturn
3208 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3209 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3210 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3211 Diag(Old->getFirstDecl()->getLocation(),
3212 diag::note_noreturn_missing_first_decl);
3215 // C++11 [dcl.attr.depend]p2:
3216 // The first declaration of a function shall specify the
3217 // carries_dependency attribute for its declarator-id if any declaration
3218 // of the function specifies the carries_dependency attribute.
3219 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3220 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3221 Diag(CDA->getLocation(),
3222 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3223 Diag(Old->getFirstDecl()->getLocation(),
3224 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3228 // All declarations for a function shall agree exactly in both the
3229 // return type and the parameter-type-list.
3230 // We also want to respect all the extended bits except noreturn.
3232 // noreturn should now match unless the old type info didn't have it.
3233 QualType OldQTypeForComparison = OldQType;
3234 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3235 auto *OldType = OldQType->castAs<FunctionProtoType>();
3236 const FunctionType *OldTypeForComparison
3237 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3238 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3239 assert(OldQTypeForComparison.isCanonical());
3242 if (haveIncompatibleLanguageLinkages(Old, New)) {
3243 // As a special case, retain the language linkage from previous
3244 // declarations of a friend function as an extension.
3246 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3247 // and is useful because there's otherwise no way to specify language
3248 // linkage within class scope.
3250 // Check cautiously as the friend object kind isn't yet complete.
3251 if (New->getFriendObjectKind() != Decl::FOK_None) {
3252 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3253 Diag(OldLocation, PrevDiag);
3255 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3256 Diag(OldLocation, PrevDiag);
3261 if (OldQTypeForComparison == NewQType)
3262 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3264 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3265 New->isLocalExternDecl()) {
3266 // It's OK if we couldn't merge types for a local function declaraton
3267 // if either the old or new type is dependent. We'll merge the types
3268 // when we instantiate the function.
3272 // Fall through for conflicting redeclarations and redefinitions.
3275 // C: Function types need to be compatible, not identical. This handles
3276 // duplicate function decls like "void f(int); void f(enum X);" properly.
3277 if (!getLangOpts().CPlusPlus &&
3278 Context.typesAreCompatible(OldQType, NewQType)) {
3279 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3280 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3281 const FunctionProtoType *OldProto = nullptr;
3282 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3283 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3284 // The old declaration provided a function prototype, but the
3285 // new declaration does not. Merge in the prototype.
3286 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3287 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3289 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3290 OldProto->getExtProtoInfo());
3291 New->setType(NewQType);
3292 New->setHasInheritedPrototype();
3294 // Synthesize parameters with the same types.
3295 SmallVector<ParmVarDecl*, 16> Params;
3296 for (const auto &ParamType : OldProto->param_types()) {
3297 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3298 SourceLocation(), nullptr,
3299 ParamType, /*TInfo=*/nullptr,
3301 Param->setScopeInfo(0, Params.size());
3302 Param->setImplicit();
3303 Params.push_back(Param);
3306 New->setParams(Params);
3309 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3312 // GNU C permits a K&R definition to follow a prototype declaration
3313 // if the declared types of the parameters in the K&R definition
3314 // match the types in the prototype declaration, even when the
3315 // promoted types of the parameters from the K&R definition differ
3316 // from the types in the prototype. GCC then keeps the types from
3319 // If a variadic prototype is followed by a non-variadic K&R definition,
3320 // the K&R definition becomes variadic. This is sort of an edge case, but
3321 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3323 if (!getLangOpts().CPlusPlus &&
3324 Old->hasPrototype() && !New->hasPrototype() &&
3325 New->getType()->getAs<FunctionProtoType>() &&
3326 Old->getNumParams() == New->getNumParams()) {
3327 SmallVector<QualType, 16> ArgTypes;
3328 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3329 const FunctionProtoType *OldProto
3330 = Old->getType()->getAs<FunctionProtoType>();
3331 const FunctionProtoType *NewProto
3332 = New->getType()->getAs<FunctionProtoType>();
3334 // Determine whether this is the GNU C extension.
3335 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3336 NewProto->getReturnType());
3337 bool LooseCompatible = !MergedReturn.isNull();
3338 for (unsigned Idx = 0, End = Old->getNumParams();
3339 LooseCompatible && Idx != End; ++Idx) {
3340 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3341 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3342 if (Context.typesAreCompatible(OldParm->getType(),
3343 NewProto->getParamType(Idx))) {
3344 ArgTypes.push_back(NewParm->getType());
3345 } else if (Context.typesAreCompatible(OldParm->getType(),
3347 /*CompareUnqualified=*/true)) {
3348 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3349 NewProto->getParamType(Idx) };
3350 Warnings.push_back(Warn);
3351 ArgTypes.push_back(NewParm->getType());
3353 LooseCompatible = false;
3356 if (LooseCompatible) {
3357 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3358 Diag(Warnings[Warn].NewParm->getLocation(),
3359 diag::ext_param_promoted_not_compatible_with_prototype)
3360 << Warnings[Warn].PromotedType
3361 << Warnings[Warn].OldParm->getType();
3362 if (Warnings[Warn].OldParm->getLocation().isValid())
3363 Diag(Warnings[Warn].OldParm->getLocation(),
3364 diag::note_previous_declaration);
3367 if (MergeTypeWithOld)
3368 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3369 OldProto->getExtProtoInfo()));
3370 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3373 // Fall through to diagnose conflicting types.
3376 // A function that has already been declared has been redeclared or
3377 // defined with a different type; show an appropriate diagnostic.
3379 // If the previous declaration was an implicitly-generated builtin
3380 // declaration, then at the very least we should use a specialized note.
3382 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3383 // If it's actually a library-defined builtin function like 'malloc'
3384 // or 'printf', just warn about the incompatible redeclaration.
3385 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3386 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3387 Diag(OldLocation, diag::note_previous_builtin_declaration)
3388 << Old << Old->getType();
3390 // If this is a global redeclaration, just forget hereafter
3391 // about the "builtin-ness" of the function.
3393 // Doing this for local extern declarations is problematic. If
3394 // the builtin declaration remains visible, a second invalid
3395 // local declaration will produce a hard error; if it doesn't
3396 // remain visible, a single bogus local redeclaration (which is
3397 // actually only a warning) could break all the downstream code.
3398 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3399 New->getIdentifier()->revertBuiltin();
3404 PrevDiag = diag::note_previous_builtin_declaration;
3407 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3408 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3412 /// \brief Completes the merge of two function declarations that are
3413 /// known to be compatible.
3415 /// This routine handles the merging of attributes and other
3416 /// properties of function declarations from the old declaration to
3417 /// the new declaration, once we know that New is in fact a
3418 /// redeclaration of Old.
3421 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3422 Scope *S, bool MergeTypeWithOld) {
3423 // Merge the attributes
3424 mergeDeclAttributes(New, Old);
3426 // Merge "pure" flag.
3430 // Merge "used" flag.
3431 if (Old->getMostRecentDecl()->isUsed(false))
3434 // Merge attributes from the parameters. These can mismatch with K&R
3436 if (New->getNumParams() == Old->getNumParams())
3437 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3438 ParmVarDecl *NewParam = New->getParamDecl(i);
3439 ParmVarDecl *OldParam = Old->getParamDecl(i);
3440 mergeParamDeclAttributes(NewParam, OldParam, *this);
3441 mergeParamDeclTypes(NewParam, OldParam, *this);
3444 if (getLangOpts().CPlusPlus)
3445 return MergeCXXFunctionDecl(New, Old, S);
3447 // Merge the function types so the we get the composite types for the return
3448 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3450 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3451 if (!Merged.isNull() && MergeTypeWithOld)
3452 New->setType(Merged);
3457 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3458 ObjCMethodDecl *oldMethod) {
3459 // Merge the attributes, including deprecated/unavailable
3460 AvailabilityMergeKind MergeKind =
3461 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3462 ? AMK_ProtocolImplementation
3463 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3466 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3468 // Merge attributes from the parameters.
3469 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3470 oe = oldMethod->param_end();
3471 for (ObjCMethodDecl::param_iterator
3472 ni = newMethod->param_begin(), ne = newMethod->param_end();
3473 ni != ne && oi != oe; ++ni, ++oi)
3474 mergeParamDeclAttributes(*ni, *oi, *this);
3476 CheckObjCMethodOverride(newMethod, oldMethod);
3479 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3480 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3482 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3483 ? diag::err_redefinition_different_type
3484 : diag::err_redeclaration_different_type)
3485 << New->getDeclName() << New->getType() << Old->getType();
3487 diag::kind PrevDiag;
3488 SourceLocation OldLocation;
3489 std::tie(PrevDiag, OldLocation)
3490 = getNoteDiagForInvalidRedeclaration(Old, New);
3491 S.Diag(OldLocation, PrevDiag);
3492 New->setInvalidDecl();
3495 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3496 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3497 /// emitting diagnostics as appropriate.
3499 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3500 /// to here in AddInitializerToDecl. We can't check them before the initializer
3502 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3503 bool MergeTypeWithOld) {
3504 if (New->isInvalidDecl() || Old->isInvalidDecl())
3508 if (getLangOpts().CPlusPlus) {
3509 if (New->getType()->isUndeducedType()) {
3510 // We don't know what the new type is until the initializer is attached.
3512 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3513 // These could still be something that needs exception specs checked.
3514 return MergeVarDeclExceptionSpecs(New, Old);
3516 // C++ [basic.link]p10:
3517 // [...] the types specified by all declarations referring to a given
3518 // object or function shall be identical, except that declarations for an
3519 // array object can specify array types that differ by the presence or
3520 // absence of a major array bound (8.3.4).
3521 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3522 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3523 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3525 // We are merging a variable declaration New into Old. If it has an array
3526 // bound, and that bound differs from Old's bound, we should diagnose the
3528 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3529 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3530 PrevVD = PrevVD->getPreviousDecl()) {
3531 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3532 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3535 if (!Context.hasSameType(NewArray, PrevVDTy))
3536 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3540 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3541 if (Context.hasSameType(OldArray->getElementType(),
3542 NewArray->getElementType()))
3543 MergedT = New->getType();
3545 // FIXME: Check visibility. New is hidden but has a complete type. If New
3546 // has no array bound, it should not inherit one from Old, if Old is not
3548 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3549 if (Context.hasSameType(OldArray->getElementType(),
3550 NewArray->getElementType()))
3551 MergedT = Old->getType();
3554 else if (New->getType()->isObjCObjectPointerType() &&
3555 Old->getType()->isObjCObjectPointerType()) {
3556 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3561 // All declarations that refer to the same object or function shall have
3563 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3565 if (MergedT.isNull()) {
3566 // It's OK if we couldn't merge types if either type is dependent, for a
3567 // block-scope variable. In other cases (static data members of class
3568 // templates, variable templates, ...), we require the types to be
3570 // FIXME: The C++ standard doesn't say anything about this.
3571 if ((New->getType()->isDependentType() ||
3572 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3573 // If the old type was dependent, we can't merge with it, so the new type
3574 // becomes dependent for now. We'll reproduce the original type when we
3575 // instantiate the TypeSourceInfo for the variable.
3576 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3577 New->setType(Context.DependentTy);
3580 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3583 // Don't actually update the type on the new declaration if the old
3584 // declaration was an extern declaration in a different scope.
3585 if (MergeTypeWithOld)
3586 New->setType(MergedT);
3589 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3590 LookupResult &Previous) {
3592 // For an identifier with internal or external linkage declared
3593 // in a scope in which a prior declaration of that identifier is
3594 // visible, if the prior declaration specifies internal or
3595 // external linkage, the type of the identifier at the later
3596 // declaration becomes the composite type.
3598 // If the variable isn't visible, we do not merge with its type.
3599 if (Previous.isShadowed())
3602 if (S.getLangOpts().CPlusPlus) {
3603 // C++11 [dcl.array]p3:
3604 // If there is a preceding declaration of the entity in the same
3605 // scope in which the bound was specified, an omitted array bound
3606 // is taken to be the same as in that earlier declaration.
3607 return NewVD->isPreviousDeclInSameBlockScope() ||
3608 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3609 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3611 // If the old declaration was function-local, don't merge with its
3612 // type unless we're in the same function.
3613 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3614 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3618 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3619 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3620 /// situation, merging decls or emitting diagnostics as appropriate.
3622 /// Tentative definition rules (C99 6.9.2p2) are checked by
3623 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3624 /// definitions here, since the initializer hasn't been attached.
3626 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3627 // If the new decl is already invalid, don't do any other checking.
3628 if (New->isInvalidDecl())
3631 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3634 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3636 // Verify the old decl was also a variable or variable template.
3637 VarDecl *Old = nullptr;
3638 VarTemplateDecl *OldTemplate = nullptr;
3639 if (Previous.isSingleResult()) {
3641 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3642 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3645 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3646 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3647 return New->setInvalidDecl();
3649 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3652 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3653 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3654 return New->setInvalidDecl();
3658 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3659 << New->getDeclName();
3660 notePreviousDefinition(Previous.getRepresentativeDecl(),
3661 New->getLocation());
3662 return New->setInvalidDecl();
3665 // Ensure the template parameters are compatible.
3667 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3668 OldTemplate->getTemplateParameters(),
3669 /*Complain=*/true, TPL_TemplateMatch))
3670 return New->setInvalidDecl();
3672 // C++ [class.mem]p1:
3673 // A member shall not be declared twice in the member-specification [...]
3675 // Here, we need only consider static data members.
3676 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3677 Diag(New->getLocation(), diag::err_duplicate_member)
3678 << New->getIdentifier();
3679 Diag(Old->getLocation(), diag::note_previous_declaration);
3680 New->setInvalidDecl();
3683 mergeDeclAttributes(New, Old);
3684 // Warn if an already-declared variable is made a weak_import in a subsequent
3686 if (New->hasAttr<WeakImportAttr>() &&
3687 Old->getStorageClass() == SC_None &&
3688 !Old->hasAttr<WeakImportAttr>()) {
3689 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3690 notePreviousDefinition(Old, New->getLocation());
3691 // Remove weak_import attribute on new declaration.
3692 New->dropAttr<WeakImportAttr>();
3695 if (New->hasAttr<InternalLinkageAttr>() &&
3696 !Old->hasAttr<InternalLinkageAttr>()) {
3697 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3698 << New->getDeclName();
3699 notePreviousDefinition(Old, New->getLocation());
3700 New->dropAttr<InternalLinkageAttr>();
3704 VarDecl *MostRecent = Old->getMostRecentDecl();
3705 if (MostRecent != Old) {
3706 MergeVarDeclTypes(New, MostRecent,
3707 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3708 if (New->isInvalidDecl())
3712 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3713 if (New->isInvalidDecl())
3716 diag::kind PrevDiag;
3717 SourceLocation OldLocation;
3718 std::tie(PrevDiag, OldLocation) =
3719 getNoteDiagForInvalidRedeclaration(Old, New);
3721 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3722 if (New->getStorageClass() == SC_Static &&
3723 !New->isStaticDataMember() &&
3724 Old->hasExternalFormalLinkage()) {
3725 if (getLangOpts().MicrosoftExt) {
3726 Diag(New->getLocation(), diag::ext_static_non_static)
3727 << New->getDeclName();
3728 Diag(OldLocation, PrevDiag);
3730 Diag(New->getLocation(), diag::err_static_non_static)
3731 << New->getDeclName();
3732 Diag(OldLocation, PrevDiag);
3733 return New->setInvalidDecl();
3737 // For an identifier declared with the storage-class specifier
3738 // extern in a scope in which a prior declaration of that
3739 // identifier is visible,23) if the prior declaration specifies
3740 // internal or external linkage, the linkage of the identifier at
3741 // the later declaration is the same as the linkage specified at
3742 // the prior declaration. If no prior declaration is visible, or
3743 // if the prior declaration specifies no linkage, then the
3744 // identifier has external linkage.
3745 if (New->hasExternalStorage() && Old->hasLinkage())
3747 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3748 !New->isStaticDataMember() &&
3749 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3750 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3751 Diag(OldLocation, PrevDiag);
3752 return New->setInvalidDecl();
3755 // Check if extern is followed by non-extern and vice-versa.
3756 if (New->hasExternalStorage() &&
3757 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3758 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3759 Diag(OldLocation, PrevDiag);
3760 return New->setInvalidDecl();
3762 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3763 !New->hasExternalStorage()) {
3764 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3765 Diag(OldLocation, PrevDiag);
3766 return New->setInvalidDecl();
3769 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3771 // FIXME: The test for external storage here seems wrong? We still
3772 // need to check for mismatches.
3773 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3774 // Don't complain about out-of-line definitions of static members.
3775 !(Old->getLexicalDeclContext()->isRecord() &&
3776 !New->getLexicalDeclContext()->isRecord())) {
3777 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3778 Diag(OldLocation, PrevDiag);
3779 return New->setInvalidDecl();
3782 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3783 if (VarDecl *Def = Old->getDefinition()) {
3784 // C++1z [dcl.fcn.spec]p4:
3785 // If the definition of a variable appears in a translation unit before
3786 // its first declaration as inline, the program is ill-formed.
3787 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3788 Diag(Def->getLocation(), diag::note_previous_definition);
3792 // If this redeclaration makes the function inline, we may need to add it to
3793 // UndefinedButUsed.
3794 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3795 !Old->getDefinition() && !New->isThisDeclarationADefinition())
3796 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3799 if (New->getTLSKind() != Old->getTLSKind()) {
3800 if (!Old->getTLSKind()) {
3801 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3802 Diag(OldLocation, PrevDiag);
3803 } else if (!New->getTLSKind()) {
3804 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3805 Diag(OldLocation, PrevDiag);
3807 // Do not allow redeclaration to change the variable between requiring
3808 // static and dynamic initialization.
3809 // FIXME: GCC allows this, but uses the TLS keyword on the first
3810 // declaration to determine the kind. Do we need to be compatible here?
3811 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3812 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3813 Diag(OldLocation, PrevDiag);
3817 // C++ doesn't have tentative definitions, so go right ahead and check here.
3818 if (getLangOpts().CPlusPlus &&
3819 New->isThisDeclarationADefinition() == VarDecl::Definition) {
3820 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3821 Old->getCanonicalDecl()->isConstexpr()) {
3822 // This definition won't be a definition any more once it's been merged.
3823 Diag(New->getLocation(),
3824 diag::warn_deprecated_redundant_constexpr_static_def);
3825 } else if (VarDecl *Def = Old->getDefinition()) {
3826 if (checkVarDeclRedefinition(Def, New))
3831 if (haveIncompatibleLanguageLinkages(Old, New)) {
3832 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3833 Diag(OldLocation, PrevDiag);
3834 New->setInvalidDecl();
3838 // Merge "used" flag.
3839 if (Old->getMostRecentDecl()->isUsed(false))
3842 // Keep a chain of previous declarations.
3843 New->setPreviousDecl(Old);
3845 NewTemplate->setPreviousDecl(OldTemplate);
3847 // Inherit access appropriately.
3848 New->setAccess(Old->getAccess());
3850 NewTemplate->setAccess(New->getAccess());
3852 if (Old->isInline())
3853 New->setImplicitlyInline();
3856 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3857 SourceManager &SrcMgr = getSourceManager();
3858 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3859 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3860 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3861 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3862 auto &HSI = PP.getHeaderSearchInfo();
3863 StringRef HdrFilename =
3864 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3866 auto noteFromModuleOrInclude = [&](Module *Mod,
3867 SourceLocation IncLoc) -> bool {
3868 // Redefinition errors with modules are common with non modular mapped
3869 // headers, example: a non-modular header H in module A that also gets
3870 // included directly in a TU. Pointing twice to the same header/definition
3871 // is confusing, try to get better diagnostics when modules is on.
3872 if (IncLoc.isValid()) {
3874 Diag(IncLoc, diag::note_redefinition_modules_same_file)
3875 << HdrFilename.str() << Mod->getFullModuleName();
3876 if (!Mod->DefinitionLoc.isInvalid())
3877 Diag(Mod->DefinitionLoc, diag::note_defined_here)
3878 << Mod->getFullModuleName();
3880 Diag(IncLoc, diag::note_redefinition_include_same_file)
3881 << HdrFilename.str();
3889 // Is it the same file and same offset? Provide more information on why
3890 // this leads to a redefinition error.
3891 bool EmittedDiag = false;
3892 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
3893 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
3894 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
3895 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
3896 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
3898 // If the header has no guards, emit a note suggesting one.
3899 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
3900 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
3906 // Redefinition coming from different files or couldn't do better above.
3907 Diag(Old->getLocation(), diag::note_previous_definition);
3910 /// We've just determined that \p Old and \p New both appear to be definitions
3911 /// of the same variable. Either diagnose or fix the problem.
3912 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3913 if (!hasVisibleDefinition(Old) &&
3914 (New->getFormalLinkage() == InternalLinkage ||
3916 New->getDescribedVarTemplate() ||
3917 New->getNumTemplateParameterLists() ||
3918 New->getDeclContext()->isDependentContext())) {
3919 // The previous definition is hidden, and multiple definitions are
3920 // permitted (in separate TUs). Demote this to a declaration.
3921 New->demoteThisDefinitionToDeclaration();
3923 // Make the canonical definition visible.
3924 if (auto *OldTD = Old->getDescribedVarTemplate())
3925 makeMergedDefinitionVisible(OldTD);
3926 makeMergedDefinitionVisible(Old);
3929 Diag(New->getLocation(), diag::err_redefinition) << New;
3930 notePreviousDefinition(Old, New->getLocation());
3931 New->setInvalidDecl();
3936 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3937 /// no declarator (e.g. "struct foo;") is parsed.
3939 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3940 RecordDecl *&AnonRecord) {
3941 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3945 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3946 // disambiguate entities defined in different scopes.
3947 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3949 // We will pick our mangling number depending on which version of MSVC is being
3951 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3952 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3953 ? S->getMSCurManglingNumber()
3954 : S->getMSLastManglingNumber();
3957 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3958 if (!Context.getLangOpts().CPlusPlus)
3961 if (isa<CXXRecordDecl>(Tag->getParent())) {
3962 // If this tag is the direct child of a class, number it if
3964 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3966 MangleNumberingContext &MCtx =
3967 Context.getManglingNumberContext(Tag->getParent());
3968 Context.setManglingNumber(
3969 Tag, MCtx.getManglingNumber(
3970 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3974 // If this tag isn't a direct child of a class, number it if it is local.
3975 Decl *ManglingContextDecl;
3976 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3977 Tag->getDeclContext(), ManglingContextDecl)) {
3978 Context.setManglingNumber(
3979 Tag, MCtx->getManglingNumber(
3980 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3984 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3985 TypedefNameDecl *NewTD) {
3986 if (TagFromDeclSpec->isInvalidDecl())
3989 // Do nothing if the tag already has a name for linkage purposes.
3990 if (TagFromDeclSpec->hasNameForLinkage())
3993 // A well-formed anonymous tag must always be a TUK_Definition.
3994 assert(TagFromDeclSpec->isThisDeclarationADefinition());
3996 // The type must match the tag exactly; no qualifiers allowed.
3997 if (!Context.hasSameType(NewTD->getUnderlyingType(),
3998 Context.getTagDeclType(TagFromDeclSpec))) {
3999 if (getLangOpts().CPlusPlus)
4000 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4004 // If we've already computed linkage for the anonymous tag, then
4005 // adding a typedef name for the anonymous decl can change that
4006 // linkage, which might be a serious problem. Diagnose this as
4007 // unsupported and ignore the typedef name. TODO: we should
4008 // pursue this as a language defect and establish a formal rule
4009 // for how to handle it.
4010 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4011 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4013 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4014 tagLoc = getLocForEndOfToken(tagLoc);
4016 llvm::SmallString<40> textToInsert;
4017 textToInsert += ' ';
4018 textToInsert += NewTD->getIdentifier()->getName();
4019 Diag(tagLoc, diag::note_typedef_changes_linkage)
4020 << FixItHint::CreateInsertion(tagLoc, textToInsert);
4024 // Otherwise, set this is the anon-decl typedef for the tag.
4025 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4028 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4030 case DeclSpec::TST_class:
4032 case DeclSpec::TST_struct:
4034 case DeclSpec::TST_interface:
4036 case DeclSpec::TST_union:
4038 case DeclSpec::TST_enum:
4041 llvm_unreachable("unexpected type specifier");
4045 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4046 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4047 /// parameters to cope with template friend declarations.
4049 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4050 MultiTemplateParamsArg TemplateParams,
4051 bool IsExplicitInstantiation,
4052 RecordDecl *&AnonRecord) {
4053 Decl *TagD = nullptr;
4054 TagDecl *Tag = nullptr;
4055 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4056 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4057 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4058 DS.getTypeSpecType() == DeclSpec::TST_union ||
4059 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4060 TagD = DS.getRepAsDecl();
4062 if (!TagD) // We probably had an error
4065 // Note that the above type specs guarantee that the
4066 // type rep is a Decl, whereas in many of the others
4068 if (isa<TagDecl>(TagD))
4069 Tag = cast<TagDecl>(TagD);
4070 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4071 Tag = CTD->getTemplatedDecl();
4075 handleTagNumbering(Tag, S);
4076 Tag->setFreeStanding();
4077 if (Tag->isInvalidDecl())
4081 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4082 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4083 // or incomplete types shall not be restrict-qualified."
4084 if (TypeQuals & DeclSpec::TQ_restrict)
4085 Diag(DS.getRestrictSpecLoc(),
4086 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4087 << DS.getSourceRange();
4090 if (DS.isInlineSpecified())
4091 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4092 << getLangOpts().CPlusPlus1z;
4094 if (DS.isConstexprSpecified()) {
4095 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4096 // and definitions of functions and variables.
4098 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4099 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4101 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4102 // Don't emit warnings after this error.
4106 if (DS.isConceptSpecified()) {
4107 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4108 // either a function concept and its definition or a variable concept and
4110 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4114 DiagnoseFunctionSpecifiers(DS);
4116 if (DS.isFriendSpecified()) {
4117 // If we're dealing with a decl but not a TagDecl, assume that
4118 // whatever routines created it handled the friendship aspect.
4121 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4124 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4125 bool IsExplicitSpecialization =
4126 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4127 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4128 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4129 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4130 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4131 // nested-name-specifier unless it is an explicit instantiation
4132 // or an explicit specialization.
4134 // FIXME: We allow class template partial specializations here too, per the
4135 // obvious intent of DR1819.
4137 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4138 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4139 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4143 // Track whether this decl-specifier declares anything.
4144 bool DeclaresAnything = true;
4146 // Handle anonymous struct definitions.
4147 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4148 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4149 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4150 if (getLangOpts().CPlusPlus ||
4151 Record->getDeclContext()->isRecord()) {
4152 // If CurContext is a DeclContext that can contain statements,
4153 // RecursiveASTVisitor won't visit the decls that
4154 // BuildAnonymousStructOrUnion() will put into CurContext.
4155 // Also store them here so that they can be part of the
4156 // DeclStmt that gets created in this case.
4157 // FIXME: Also return the IndirectFieldDecls created by
4158 // BuildAnonymousStructOr union, for the same reason?
4159 if (CurContext->isFunctionOrMethod())
4160 AnonRecord = Record;
4161 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4162 Context.getPrintingPolicy());
4165 DeclaresAnything = false;
4170 // A struct-declaration that does not declare an anonymous structure or
4171 // anonymous union shall contain a struct-declarator-list.
4173 // This rule also existed in C89 and C99; the grammar for struct-declaration
4174 // did not permit a struct-declaration without a struct-declarator-list.
4175 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4176 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4177 // Check for Microsoft C extension: anonymous struct/union member.
4178 // Handle 2 kinds of anonymous struct/union:
4182 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4183 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4184 if ((Tag && Tag->getDeclName()) ||
4185 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4186 RecordDecl *Record = nullptr;
4188 Record = dyn_cast<RecordDecl>(Tag);
4189 else if (const RecordType *RT =
4190 DS.getRepAsType().get()->getAsStructureType())
4191 Record = RT->getDecl();
4192 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4193 Record = UT->getDecl();
4195 if (Record && getLangOpts().MicrosoftExt) {
4196 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4197 << Record->isUnion() << DS.getSourceRange();
4198 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4201 DeclaresAnything = false;
4205 // Skip all the checks below if we have a type error.
4206 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4207 (TagD && TagD->isInvalidDecl()))
4210 if (getLangOpts().CPlusPlus &&
4211 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4212 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4213 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4214 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4215 DeclaresAnything = false;
4217 if (!DS.isMissingDeclaratorOk()) {
4218 // Customize diagnostic for a typedef missing a name.
4219 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4220 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4221 << DS.getSourceRange();
4223 DeclaresAnything = false;
4226 if (DS.isModulePrivateSpecified() &&
4227 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4228 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4229 << Tag->getTagKind()
4230 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4232 ActOnDocumentableDecl(TagD);
4235 // A declaration [...] shall declare at least a declarator [...], a tag,
4236 // or the members of an enumeration.
4238 // [If there are no declarators], and except for the declaration of an
4239 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4240 // names into the program, or shall redeclare a name introduced by a
4241 // previous declaration.
4242 if (!DeclaresAnything) {
4243 // In C, we allow this as a (popular) extension / bug. Don't bother
4244 // producing further diagnostics for redundant qualifiers after this.
4245 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4250 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4251 // init-declarator-list of the declaration shall not be empty.
4252 // C++ [dcl.fct.spec]p1:
4253 // If a cv-qualifier appears in a decl-specifier-seq, the
4254 // init-declarator-list of the declaration shall not be empty.
4256 // Spurious qualifiers here appear to be valid in C.
4257 unsigned DiagID = diag::warn_standalone_specifier;
4258 if (getLangOpts().CPlusPlus)
4259 DiagID = diag::ext_standalone_specifier;
4261 // Note that a linkage-specification sets a storage class, but
4262 // 'extern "C" struct foo;' is actually valid and not theoretically
4264 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4265 if (SCS == DeclSpec::SCS_mutable)
4266 // Since mutable is not a viable storage class specifier in C, there is
4267 // no reason to treat it as an extension. Instead, diagnose as an error.
4268 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4269 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4270 Diag(DS.getStorageClassSpecLoc(), DiagID)
4271 << DeclSpec::getSpecifierName(SCS);
4274 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4275 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4276 << DeclSpec::getSpecifierName(TSCS);
4277 if (DS.getTypeQualifiers()) {
4278 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4279 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4280 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4281 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4282 // Restrict is covered above.
4283 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4284 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4285 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4286 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4289 // Warn about ignored type attributes, for example:
4290 // __attribute__((aligned)) struct A;
4291 // Attributes should be placed after tag to apply to type declaration.
4292 if (!DS.getAttributes().empty()) {
4293 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4294 if (TypeSpecType == DeclSpec::TST_class ||
4295 TypeSpecType == DeclSpec::TST_struct ||
4296 TypeSpecType == DeclSpec::TST_interface ||
4297 TypeSpecType == DeclSpec::TST_union ||
4298 TypeSpecType == DeclSpec::TST_enum) {
4299 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4300 attrs = attrs->getNext())
4301 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4302 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4309 /// We are trying to inject an anonymous member into the given scope;
4310 /// check if there's an existing declaration that can't be overloaded.
4312 /// \return true if this is a forbidden redeclaration
4313 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4316 DeclarationName Name,
4317 SourceLocation NameLoc,
4319 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4320 Sema::ForRedeclaration);
4321 if (!SemaRef.LookupName(R, S)) return false;
4323 // Pick a representative declaration.
4324 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4325 assert(PrevDecl && "Expected a non-null Decl");
4327 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4330 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4332 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4337 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4338 /// anonymous struct or union AnonRecord into the owning context Owner
4339 /// and scope S. This routine will be invoked just after we realize
4340 /// that an unnamed union or struct is actually an anonymous union or
4347 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4348 /// // f into the surrounding scope.x
4351 /// This routine is recursive, injecting the names of nested anonymous
4352 /// structs/unions into the owning context and scope as well.
4354 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4355 RecordDecl *AnonRecord, AccessSpecifier AS,
4356 SmallVectorImpl<NamedDecl *> &Chaining) {
4357 bool Invalid = false;
4359 // Look every FieldDecl and IndirectFieldDecl with a name.
4360 for (auto *D : AnonRecord->decls()) {
4361 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4362 cast<NamedDecl>(D)->getDeclName()) {
4363 ValueDecl *VD = cast<ValueDecl>(D);
4364 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4366 AnonRecord->isUnion())) {
4367 // C++ [class.union]p2:
4368 // The names of the members of an anonymous union shall be
4369 // distinct from the names of any other entity in the
4370 // scope in which the anonymous union is declared.
4373 // C++ [class.union]p2:
4374 // For the purpose of name lookup, after the anonymous union
4375 // definition, the members of the anonymous union are
4376 // considered to have been defined in the scope in which the
4377 // anonymous union is declared.
4378 unsigned OldChainingSize = Chaining.size();
4379 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4380 Chaining.append(IF->chain_begin(), IF->chain_end());
4382 Chaining.push_back(VD);
4384 assert(Chaining.size() >= 2);
4385 NamedDecl **NamedChain =
4386 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4387 for (unsigned i = 0; i < Chaining.size(); i++)
4388 NamedChain[i] = Chaining[i];
4390 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4391 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4392 VD->getType(), {NamedChain, Chaining.size()});
4394 for (const auto *Attr : VD->attrs())
4395 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4397 IndirectField->setAccess(AS);
4398 IndirectField->setImplicit();
4399 SemaRef.PushOnScopeChains(IndirectField, S);
4401 // That includes picking up the appropriate access specifier.
4402 if (AS != AS_none) IndirectField->setAccess(AS);
4404 Chaining.resize(OldChainingSize);
4412 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4413 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4414 /// illegal input values are mapped to SC_None.
4416 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4417 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4418 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4419 "Parser allowed 'typedef' as storage class VarDecl.");
4420 switch (StorageClassSpec) {
4421 case DeclSpec::SCS_unspecified: return SC_None;
4422 case DeclSpec::SCS_extern:
4423 if (DS.isExternInLinkageSpec())
4426 case DeclSpec::SCS_static: return SC_Static;
4427 case DeclSpec::SCS_auto: return SC_Auto;
4428 case DeclSpec::SCS_register: return SC_Register;
4429 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4430 // Illegal SCSs map to None: error reporting is up to the caller.
4431 case DeclSpec::SCS_mutable: // Fall through.
4432 case DeclSpec::SCS_typedef: return SC_None;
4434 llvm_unreachable("unknown storage class specifier");
4437 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4438 assert(Record->hasInClassInitializer());
4440 for (const auto *I : Record->decls()) {
4441 const auto *FD = dyn_cast<FieldDecl>(I);
4442 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4443 FD = IFD->getAnonField();
4444 if (FD && FD->hasInClassInitializer())
4445 return FD->getLocation();
4448 llvm_unreachable("couldn't find in-class initializer");
4451 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4452 SourceLocation DefaultInitLoc) {
4453 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4456 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4457 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4460 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4461 CXXRecordDecl *AnonUnion) {
4462 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4465 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4468 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4469 /// anonymous structure or union. Anonymous unions are a C++ feature
4470 /// (C++ [class.union]) and a C11 feature; anonymous structures
4471 /// are a C11 feature and GNU C++ extension.
4472 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4475 const PrintingPolicy &Policy) {
4476 DeclContext *Owner = Record->getDeclContext();
4478 // Diagnose whether this anonymous struct/union is an extension.
4479 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4480 Diag(Record->getLocation(), diag::ext_anonymous_union);
4481 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4482 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4483 else if (!Record->isUnion() && !getLangOpts().C11)
4484 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4486 // C and C++ require different kinds of checks for anonymous
4488 bool Invalid = false;
4489 if (getLangOpts().CPlusPlus) {
4490 const char *PrevSpec = nullptr;
4492 if (Record->isUnion()) {
4493 // C++ [class.union]p6:
4494 // Anonymous unions declared in a named namespace or in the
4495 // global namespace shall be declared static.
4496 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4497 (isa<TranslationUnitDecl>(Owner) ||
4498 (isa<NamespaceDecl>(Owner) &&
4499 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4500 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4501 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4503 // Recover by adding 'static'.
4504 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4505 PrevSpec, DiagID, Policy);
4507 // C++ [class.union]p6:
4508 // A storage class is not allowed in a declaration of an
4509 // anonymous union in a class scope.
4510 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4511 isa<RecordDecl>(Owner)) {
4512 Diag(DS.getStorageClassSpecLoc(),
4513 diag::err_anonymous_union_with_storage_spec)
4514 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4516 // Recover by removing the storage specifier.
4517 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4519 PrevSpec, DiagID, Context.getPrintingPolicy());
4523 // Ignore const/volatile/restrict qualifiers.
4524 if (DS.getTypeQualifiers()) {
4525 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4526 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4527 << Record->isUnion() << "const"
4528 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4529 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4530 Diag(DS.getVolatileSpecLoc(),
4531 diag::ext_anonymous_struct_union_qualified)
4532 << Record->isUnion() << "volatile"
4533 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4534 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4535 Diag(DS.getRestrictSpecLoc(),
4536 diag::ext_anonymous_struct_union_qualified)
4537 << Record->isUnion() << "restrict"
4538 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4539 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4540 Diag(DS.getAtomicSpecLoc(),
4541 diag::ext_anonymous_struct_union_qualified)
4542 << Record->isUnion() << "_Atomic"
4543 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4544 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4545 Diag(DS.getUnalignedSpecLoc(),
4546 diag::ext_anonymous_struct_union_qualified)
4547 << Record->isUnion() << "__unaligned"
4548 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4550 DS.ClearTypeQualifiers();
4553 // C++ [class.union]p2:
4554 // The member-specification of an anonymous union shall only
4555 // define non-static data members. [Note: nested types and
4556 // functions cannot be declared within an anonymous union. ]
4557 for (auto *Mem : Record->decls()) {
4558 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4559 // C++ [class.union]p3:
4560 // An anonymous union shall not have private or protected
4561 // members (clause 11).
4562 assert(FD->getAccess() != AS_none);
4563 if (FD->getAccess() != AS_public) {
4564 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4565 << Record->isUnion() << (FD->getAccess() == AS_protected);
4569 // C++ [class.union]p1
4570 // An object of a class with a non-trivial constructor, a non-trivial
4571 // copy constructor, a non-trivial destructor, or a non-trivial copy
4572 // assignment operator cannot be a member of a union, nor can an
4573 // array of such objects.
4574 if (CheckNontrivialField(FD))
4576 } else if (Mem->isImplicit()) {
4577 // Any implicit members are fine.
4578 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4579 // This is a type that showed up in an
4580 // elaborated-type-specifier inside the anonymous struct or
4581 // union, but which actually declares a type outside of the
4582 // anonymous struct or union. It's okay.
4583 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4584 if (!MemRecord->isAnonymousStructOrUnion() &&
4585 MemRecord->getDeclName()) {
4586 // Visual C++ allows type definition in anonymous struct or union.
4587 if (getLangOpts().MicrosoftExt)
4588 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4589 << Record->isUnion();
4591 // This is a nested type declaration.
4592 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4593 << Record->isUnion();
4597 // This is an anonymous type definition within another anonymous type.
4598 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4599 // not part of standard C++.
4600 Diag(MemRecord->getLocation(),
4601 diag::ext_anonymous_record_with_anonymous_type)
4602 << Record->isUnion();
4604 } else if (isa<AccessSpecDecl>(Mem)) {
4605 // Any access specifier is fine.
4606 } else if (isa<StaticAssertDecl>(Mem)) {
4607 // In C++1z, static_assert declarations are also fine.
4609 // We have something that isn't a non-static data
4610 // member. Complain about it.
4611 unsigned DK = diag::err_anonymous_record_bad_member;
4612 if (isa<TypeDecl>(Mem))
4613 DK = diag::err_anonymous_record_with_type;
4614 else if (isa<FunctionDecl>(Mem))
4615 DK = diag::err_anonymous_record_with_function;
4616 else if (isa<VarDecl>(Mem))
4617 DK = diag::err_anonymous_record_with_static;
4619 // Visual C++ allows type definition in anonymous struct or union.
4620 if (getLangOpts().MicrosoftExt &&
4621 DK == diag::err_anonymous_record_with_type)
4622 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4623 << Record->isUnion();
4625 Diag(Mem->getLocation(), DK) << Record->isUnion();
4631 // C++11 [class.union]p8 (DR1460):
4632 // At most one variant member of a union may have a
4633 // brace-or-equal-initializer.
4634 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4636 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4637 cast<CXXRecordDecl>(Record));
4640 if (!Record->isUnion() && !Owner->isRecord()) {
4641 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4642 << getLangOpts().CPlusPlus;
4646 // Mock up a declarator.
4647 Declarator Dc(DS, Declarator::MemberContext);
4648 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4649 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4651 // Create a declaration for this anonymous struct/union.
4652 NamedDecl *Anon = nullptr;
4653 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4654 Anon = FieldDecl::Create(Context, OwningClass,
4656 Record->getLocation(),
4657 /*IdentifierInfo=*/nullptr,
4658 Context.getTypeDeclType(Record),
4660 /*BitWidth=*/nullptr, /*Mutable=*/false,
4661 /*InitStyle=*/ICIS_NoInit);
4662 Anon->setAccess(AS);
4663 if (getLangOpts().CPlusPlus)
4664 FieldCollector->Add(cast<FieldDecl>(Anon));
4666 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4667 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4668 if (SCSpec == DeclSpec::SCS_mutable) {
4669 // mutable can only appear on non-static class members, so it's always
4671 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4676 Anon = VarDecl::Create(Context, Owner,
4678 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4679 Context.getTypeDeclType(Record),
4682 // Default-initialize the implicit variable. This initialization will be
4683 // trivial in almost all cases, except if a union member has an in-class
4685 // union { int n = 0; };
4686 ActOnUninitializedDecl(Anon);
4688 Anon->setImplicit();
4690 // Mark this as an anonymous struct/union type.
4691 Record->setAnonymousStructOrUnion(true);
4693 // Add the anonymous struct/union object to the current
4694 // context. We'll be referencing this object when we refer to one of
4696 Owner->addDecl(Anon);
4698 // Inject the members of the anonymous struct/union into the owning
4699 // context and into the identifier resolver chain for name lookup
4701 SmallVector<NamedDecl*, 2> Chain;
4702 Chain.push_back(Anon);
4704 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4707 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4708 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4709 Decl *ManglingContextDecl;
4710 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4711 NewVD->getDeclContext(), ManglingContextDecl)) {
4712 Context.setManglingNumber(
4713 NewVD, MCtx->getManglingNumber(
4714 NewVD, getMSManglingNumber(getLangOpts(), S)));
4715 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4721 Anon->setInvalidDecl();
4726 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4727 /// Microsoft C anonymous structure.
4728 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4731 /// struct A { int a; };
4732 /// struct B { struct A; int b; };
4739 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4740 RecordDecl *Record) {
4741 assert(Record && "expected a record!");
4743 // Mock up a declarator.
4744 Declarator Dc(DS, Declarator::TypeNameContext);
4745 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4746 assert(TInfo && "couldn't build declarator info for anonymous struct");
4748 auto *ParentDecl = cast<RecordDecl>(CurContext);
4749 QualType RecTy = Context.getTypeDeclType(Record);
4751 // Create a declaration for this anonymous struct.
4752 NamedDecl *Anon = FieldDecl::Create(Context,
4756 /*IdentifierInfo=*/nullptr,
4759 /*BitWidth=*/nullptr, /*Mutable=*/false,
4760 /*InitStyle=*/ICIS_NoInit);
4761 Anon->setImplicit();
4763 // Add the anonymous struct object to the current context.
4764 CurContext->addDecl(Anon);
4766 // Inject the members of the anonymous struct into the current
4767 // context and into the identifier resolver chain for name lookup
4769 SmallVector<NamedDecl*, 2> Chain;
4770 Chain.push_back(Anon);
4772 RecordDecl *RecordDef = Record->getDefinition();
4773 if (RequireCompleteType(Anon->getLocation(), RecTy,
4774 diag::err_field_incomplete) ||
4775 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4777 Anon->setInvalidDecl();
4778 ParentDecl->setInvalidDecl();
4784 /// GetNameForDeclarator - Determine the full declaration name for the
4785 /// given Declarator.
4786 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4787 return GetNameFromUnqualifiedId(D.getName());
4790 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4792 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4793 DeclarationNameInfo NameInfo;
4794 NameInfo.setLoc(Name.StartLocation);
4796 switch (Name.getKind()) {
4798 case UnqualifiedId::IK_ImplicitSelfParam:
4799 case UnqualifiedId::IK_Identifier:
4800 NameInfo.setName(Name.Identifier);
4801 NameInfo.setLoc(Name.StartLocation);
4804 case UnqualifiedId::IK_DeductionGuideName: {
4805 // C++ [temp.deduct.guide]p3:
4806 // The simple-template-id shall name a class template specialization.
4807 // The template-name shall be the same identifier as the template-name
4808 // of the simple-template-id.
4809 // These together intend to imply that the template-name shall name a
4811 // FIXME: template<typename T> struct X {};
4812 // template<typename T> using Y = X<T>;
4813 // Y(int) -> Y<int>;
4814 // satisfies these rules but does not name a class template.
4815 TemplateName TN = Name.TemplateName.get().get();
4816 auto *Template = TN.getAsTemplateDecl();
4817 if (!Template || !isa<ClassTemplateDecl>(Template)) {
4818 Diag(Name.StartLocation,
4819 diag::err_deduction_guide_name_not_class_template)
4820 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4822 Diag(Template->getLocation(), diag::note_template_decl_here);
4823 return DeclarationNameInfo();
4827 Context.DeclarationNames.getCXXDeductionGuideName(Template));
4828 NameInfo.setLoc(Name.StartLocation);
4832 case UnqualifiedId::IK_OperatorFunctionId:
4833 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4834 Name.OperatorFunctionId.Operator));
4835 NameInfo.setLoc(Name.StartLocation);
4836 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4837 = Name.OperatorFunctionId.SymbolLocations[0];
4838 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4839 = Name.EndLocation.getRawEncoding();
4842 case UnqualifiedId::IK_LiteralOperatorId:
4843 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4845 NameInfo.setLoc(Name.StartLocation);
4846 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4849 case UnqualifiedId::IK_ConversionFunctionId: {
4850 TypeSourceInfo *TInfo;
4851 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4853 return DeclarationNameInfo();
4854 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4855 Context.getCanonicalType(Ty)));
4856 NameInfo.setLoc(Name.StartLocation);
4857 NameInfo.setNamedTypeInfo(TInfo);
4861 case UnqualifiedId::IK_ConstructorName: {
4862 TypeSourceInfo *TInfo;
4863 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4865 return DeclarationNameInfo();
4866 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4867 Context.getCanonicalType(Ty)));
4868 NameInfo.setLoc(Name.StartLocation);
4869 NameInfo.setNamedTypeInfo(TInfo);
4873 case UnqualifiedId::IK_ConstructorTemplateId: {
4874 // In well-formed code, we can only have a constructor
4875 // template-id that refers to the current context, so go there
4876 // to find the actual type being constructed.
4877 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4878 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4879 return DeclarationNameInfo();
4881 // Determine the type of the class being constructed.
4882 QualType CurClassType = Context.getTypeDeclType(CurClass);
4884 // FIXME: Check two things: that the template-id names the same type as
4885 // CurClassType, and that the template-id does not occur when the name
4888 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4889 Context.getCanonicalType(CurClassType)));
4890 NameInfo.setLoc(Name.StartLocation);
4891 // FIXME: should we retrieve TypeSourceInfo?
4892 NameInfo.setNamedTypeInfo(nullptr);
4896 case UnqualifiedId::IK_DestructorName: {
4897 TypeSourceInfo *TInfo;
4898 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4900 return DeclarationNameInfo();
4901 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4902 Context.getCanonicalType(Ty)));
4903 NameInfo.setLoc(Name.StartLocation);
4904 NameInfo.setNamedTypeInfo(TInfo);
4908 case UnqualifiedId::IK_TemplateId: {
4909 TemplateName TName = Name.TemplateId->Template.get();
4910 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4911 return Context.getNameForTemplate(TName, TNameLoc);
4914 } // switch (Name.getKind())
4916 llvm_unreachable("Unknown name kind");
4919 static QualType getCoreType(QualType Ty) {
4921 if (Ty->isPointerType() || Ty->isReferenceType())
4922 Ty = Ty->getPointeeType();
4923 else if (Ty->isArrayType())
4924 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4926 return Ty.withoutLocalFastQualifiers();
4930 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4931 /// and Definition have "nearly" matching parameters. This heuristic is
4932 /// used to improve diagnostics in the case where an out-of-line function
4933 /// definition doesn't match any declaration within the class or namespace.
4934 /// Also sets Params to the list of indices to the parameters that differ
4935 /// between the declaration and the definition. If hasSimilarParameters
4936 /// returns true and Params is empty, then all of the parameters match.
4937 static bool hasSimilarParameters(ASTContext &Context,
4938 FunctionDecl *Declaration,
4939 FunctionDecl *Definition,
4940 SmallVectorImpl<unsigned> &Params) {
4942 if (Declaration->param_size() != Definition->param_size())
4944 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4945 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4946 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4948 // The parameter types are identical
4949 if (Context.hasSameType(DefParamTy, DeclParamTy))
4952 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4953 QualType DefParamBaseTy = getCoreType(DefParamTy);
4954 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4955 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4957 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4958 (DeclTyName && DeclTyName == DefTyName))
4959 Params.push_back(Idx);
4960 else // The two parameters aren't even close
4967 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4968 /// declarator needs to be rebuilt in the current instantiation.
4969 /// Any bits of declarator which appear before the name are valid for
4970 /// consideration here. That's specifically the type in the decl spec
4971 /// and the base type in any member-pointer chunks.
4972 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4973 DeclarationName Name) {
4974 // The types we specifically need to rebuild are:
4975 // - typenames, typeofs, and decltypes
4976 // - types which will become injected class names
4977 // Of course, we also need to rebuild any type referencing such a
4978 // type. It's safest to just say "dependent", but we call out a
4981 DeclSpec &DS = D.getMutableDeclSpec();
4982 switch (DS.getTypeSpecType()) {
4983 case DeclSpec::TST_typename:
4984 case DeclSpec::TST_typeofType:
4985 case DeclSpec::TST_underlyingType:
4986 case DeclSpec::TST_atomic: {
4987 // Grab the type from the parser.
4988 TypeSourceInfo *TSI = nullptr;
4989 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4990 if (T.isNull() || !T->isDependentType()) break;
4992 // Make sure there's a type source info. This isn't really much
4993 // of a waste; most dependent types should have type source info
4994 // attached already.
4996 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4998 // Rebuild the type in the current instantiation.
4999 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5000 if (!TSI) return true;
5002 // Store the new type back in the decl spec.
5003 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5004 DS.UpdateTypeRep(LocType);
5008 case DeclSpec::TST_decltype:
5009 case DeclSpec::TST_typeofExpr: {
5010 Expr *E = DS.getRepAsExpr();
5011 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5012 if (Result.isInvalid()) return true;
5013 DS.UpdateExprRep(Result.get());
5018 // Nothing to do for these decl specs.
5022 // It doesn't matter what order we do this in.
5023 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5024 DeclaratorChunk &Chunk = D.getTypeObject(I);
5026 // The only type information in the declarator which can come
5027 // before the declaration name is the base type of a member
5029 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5032 // Rebuild the scope specifier in-place.
5033 CXXScopeSpec &SS = Chunk.Mem.Scope();
5034 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5041 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5042 D.setFunctionDefinitionKind(FDK_Declaration);
5043 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5045 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5046 Dcl && Dcl->getDeclContext()->isFileContext())
5047 Dcl->setTopLevelDeclInObjCContainer();
5049 if (getLangOpts().OpenCL)
5050 setCurrentOpenCLExtensionForDecl(Dcl);
5055 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5056 /// If T is the name of a class, then each of the following shall have a
5057 /// name different from T:
5058 /// - every static data member of class T;
5059 /// - every member function of class T
5060 /// - every member of class T that is itself a type;
5061 /// \returns true if the declaration name violates these rules.
5062 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5063 DeclarationNameInfo NameInfo) {
5064 DeclarationName Name = NameInfo.getName();
5066 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5067 while (Record && Record->isAnonymousStructOrUnion())
5068 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5069 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5070 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5077 /// \brief Diagnose a declaration whose declarator-id has the given
5078 /// nested-name-specifier.
5080 /// \param SS The nested-name-specifier of the declarator-id.
5082 /// \param DC The declaration context to which the nested-name-specifier
5085 /// \param Name The name of the entity being declared.
5087 /// \param Loc The location of the name of the entity being declared.
5089 /// \returns true if we cannot safely recover from this error, false otherwise.
5090 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5091 DeclarationName Name,
5092 SourceLocation Loc) {
5093 DeclContext *Cur = CurContext;
5094 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5095 Cur = Cur->getParent();
5097 // If the user provided a superfluous scope specifier that refers back to the
5098 // class in which the entity is already declared, diagnose and ignore it.
5104 // Note, it was once ill-formed to give redundant qualification in all
5105 // contexts, but that rule was removed by DR482.
5106 if (Cur->Equals(DC)) {
5107 if (Cur->isRecord()) {
5108 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5109 : diag::err_member_extra_qualification)
5110 << Name << FixItHint::CreateRemoval(SS.getRange());
5113 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5118 // Check whether the qualifying scope encloses the scope of the original
5120 if (!Cur->Encloses(DC)) {
5121 if (Cur->isRecord())
5122 Diag(Loc, diag::err_member_qualification)
5123 << Name << SS.getRange();
5124 else if (isa<TranslationUnitDecl>(DC))
5125 Diag(Loc, diag::err_invalid_declarator_global_scope)
5126 << Name << SS.getRange();
5127 else if (isa<FunctionDecl>(Cur))
5128 Diag(Loc, diag::err_invalid_declarator_in_function)
5129 << Name << SS.getRange();
5130 else if (isa<BlockDecl>(Cur))
5131 Diag(Loc, diag::err_invalid_declarator_in_block)
5132 << Name << SS.getRange();
5134 Diag(Loc, diag::err_invalid_declarator_scope)
5135 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5140 if (Cur->isRecord()) {
5141 // Cannot qualify members within a class.
5142 Diag(Loc, diag::err_member_qualification)
5143 << Name << SS.getRange();
5146 // C++ constructors and destructors with incorrect scopes can break
5147 // our AST invariants by having the wrong underlying types. If
5148 // that's the case, then drop this declaration entirely.
5149 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5150 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5151 !Context.hasSameType(Name.getCXXNameType(),
5152 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5158 // C++11 [dcl.meaning]p1:
5159 // [...] "The nested-name-specifier of the qualified declarator-id shall
5160 // not begin with a decltype-specifer"
5161 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5162 while (SpecLoc.getPrefix())
5163 SpecLoc = SpecLoc.getPrefix();
5164 if (dyn_cast_or_null<DecltypeType>(
5165 SpecLoc.getNestedNameSpecifier()->getAsType()))
5166 Diag(Loc, diag::err_decltype_in_declarator)
5167 << SpecLoc.getTypeLoc().getSourceRange();
5172 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5173 MultiTemplateParamsArg TemplateParamLists) {
5174 // TODO: consider using NameInfo for diagnostic.
5175 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5176 DeclarationName Name = NameInfo.getName();
5178 // All of these full declarators require an identifier. If it doesn't have
5179 // one, the ParsedFreeStandingDeclSpec action should be used.
5180 if (D.isDecompositionDeclarator()) {
5181 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5183 if (!D.isInvalidType()) // Reject this if we think it is valid.
5184 Diag(D.getDeclSpec().getLocStart(),
5185 diag::err_declarator_need_ident)
5186 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5188 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5191 // The scope passed in may not be a decl scope. Zip up the scope tree until
5192 // we find one that is.
5193 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5194 (S->getFlags() & Scope::TemplateParamScope) != 0)
5197 DeclContext *DC = CurContext;
5198 if (D.getCXXScopeSpec().isInvalid())
5200 else if (D.getCXXScopeSpec().isSet()) {
5201 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5202 UPPC_DeclarationQualifier))
5205 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5206 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5207 if (!DC || isa<EnumDecl>(DC)) {
5208 // If we could not compute the declaration context, it's because the
5209 // declaration context is dependent but does not refer to a class,
5210 // class template, or class template partial specialization. Complain
5211 // and return early, to avoid the coming semantic disaster.
5212 Diag(D.getIdentifierLoc(),
5213 diag::err_template_qualified_declarator_no_match)
5214 << D.getCXXScopeSpec().getScopeRep()
5215 << D.getCXXScopeSpec().getRange();
5218 bool IsDependentContext = DC->isDependentContext();
5220 if (!IsDependentContext &&
5221 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5224 // If a class is incomplete, do not parse entities inside it.
5225 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5226 Diag(D.getIdentifierLoc(),
5227 diag::err_member_def_undefined_record)
5228 << Name << DC << D.getCXXScopeSpec().getRange();
5231 if (!D.getDeclSpec().isFriendSpecified()) {
5232 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5233 Name, D.getIdentifierLoc())) {
5241 // Check whether we need to rebuild the type of the given
5242 // declaration in the current instantiation.
5243 if (EnteringContext && IsDependentContext &&
5244 TemplateParamLists.size() != 0) {
5245 ContextRAII SavedContext(*this, DC);
5246 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5251 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5252 QualType R = TInfo->getType();
5254 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5255 // If this is a typedef, we'll end up spewing multiple diagnostics.
5256 // Just return early; it's safer. If this is a function, let the
5257 // "constructor cannot have a return type" diagnostic handle it.
5258 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5261 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5262 UPPC_DeclarationType))
5265 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5268 // See if this is a redefinition of a variable in the same scope.
5269 if (!D.getCXXScopeSpec().isSet()) {
5270 bool IsLinkageLookup = false;
5271 bool CreateBuiltins = false;
5273 // If the declaration we're planning to build will be a function
5274 // or object with linkage, then look for another declaration with
5275 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5277 // If the declaration we're planning to build will be declared with
5278 // external linkage in the translation unit, create any builtin with
5280 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5282 else if (CurContext->isFunctionOrMethod() &&
5283 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5284 R->isFunctionType())) {
5285 IsLinkageLookup = true;
5287 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5288 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5289 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5290 CreateBuiltins = true;
5292 if (IsLinkageLookup)
5293 Previous.clear(LookupRedeclarationWithLinkage);
5295 LookupName(Previous, S, CreateBuiltins);
5296 } else { // Something like "int foo::x;"
5297 LookupQualifiedName(Previous, DC);
5299 // C++ [dcl.meaning]p1:
5300 // When the declarator-id is qualified, the declaration shall refer to a
5301 // previously declared member of the class or namespace to which the
5302 // qualifier refers (or, in the case of a namespace, of an element of the
5303 // inline namespace set of that namespace (7.3.1)) or to a specialization
5306 // Note that we already checked the context above, and that we do not have
5307 // enough information to make sure that Previous contains the declaration
5308 // we want to match. For example, given:
5315 // void X::f(int) { } // ill-formed
5317 // In this case, Previous will point to the overload set
5318 // containing the two f's declared in X, but neither of them
5321 // C++ [dcl.meaning]p1:
5322 // [...] the member shall not merely have been introduced by a
5323 // using-declaration in the scope of the class or namespace nominated by
5324 // the nested-name-specifier of the declarator-id.
5325 RemoveUsingDecls(Previous);
5328 if (Previous.isSingleResult() &&
5329 Previous.getFoundDecl()->isTemplateParameter()) {
5330 // Maybe we will complain about the shadowed template parameter.
5331 if (!D.isInvalidType())
5332 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5333 Previous.getFoundDecl());
5335 // Just pretend that we didn't see the previous declaration.
5339 // In C++, the previous declaration we find might be a tag type
5340 // (class or enum). In this case, the new declaration will hide the
5341 // tag type. Note that this does does not apply if we're declaring a
5342 // typedef (C++ [dcl.typedef]p4).
5343 if (Previous.isSingleTagDecl() &&
5344 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5347 // Check that there are no default arguments other than in the parameters
5348 // of a function declaration (C++ only).
5349 if (getLangOpts().CPlusPlus)
5350 CheckExtraCXXDefaultArguments(D);
5352 if (D.getDeclSpec().isConceptSpecified()) {
5353 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5354 // applied only to the definition of a function template or variable
5355 // template, declared in namespace scope
5356 if (!TemplateParamLists.size()) {
5357 Diag(D.getDeclSpec().getConceptSpecLoc(),
5358 diag:: err_concept_wrong_decl_kind);
5362 if (!DC->getRedeclContext()->isFileContext()) {
5363 Diag(D.getIdentifierLoc(),
5364 diag::err_concept_decls_may_only_appear_in_namespace_scope);
5371 bool AddToScope = true;
5372 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5373 if (TemplateParamLists.size()) {
5374 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5378 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5379 } else if (R->isFunctionType()) {
5380 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5384 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5391 // If this has an identifier and is not a function template specialization,
5392 // add it to the scope stack.
5393 if (New->getDeclName() && AddToScope) {
5394 // Only make a locally-scoped extern declaration visible if it is the first
5395 // declaration of this entity. Qualified lookup for such an entity should
5396 // only find this declaration if there is no visible declaration of it.
5397 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5398 PushOnScopeChains(New, S, AddToContext);
5400 CurContext->addHiddenDecl(New);
5403 if (isInOpenMPDeclareTargetContext())
5404 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5409 /// Helper method to turn variable array types into constant array
5410 /// types in certain situations which would otherwise be errors (for
5411 /// GCC compatibility).
5412 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5413 ASTContext &Context,
5414 bool &SizeIsNegative,
5415 llvm::APSInt &Oversized) {
5416 // This method tries to turn a variable array into a constant
5417 // array even when the size isn't an ICE. This is necessary
5418 // for compatibility with code that depends on gcc's buggy
5419 // constant expression folding, like struct {char x[(int)(char*)2];}
5420 SizeIsNegative = false;
5423 if (T->isDependentType())
5426 QualifierCollector Qs;
5427 const Type *Ty = Qs.strip(T);
5429 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5430 QualType Pointee = PTy->getPointeeType();
5431 QualType FixedType =
5432 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5434 if (FixedType.isNull()) return FixedType;
5435 FixedType = Context.getPointerType(FixedType);
5436 return Qs.apply(Context, FixedType);
5438 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5439 QualType Inner = PTy->getInnerType();
5440 QualType FixedType =
5441 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5443 if (FixedType.isNull()) return FixedType;
5444 FixedType = Context.getParenType(FixedType);
5445 return Qs.apply(Context, FixedType);
5448 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5451 // FIXME: We should probably handle this case
5452 if (VLATy->getElementType()->isVariablyModifiedType())
5456 if (!VLATy->getSizeExpr() ||
5457 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5460 // Check whether the array size is negative.
5461 if (Res.isSigned() && Res.isNegative()) {
5462 SizeIsNegative = true;
5466 // Check whether the array is too large to be addressed.
5467 unsigned ActiveSizeBits
5468 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5470 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5475 return Context.getConstantArrayType(VLATy->getElementType(),
5476 Res, ArrayType::Normal, 0);
5480 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5481 SrcTL = SrcTL.getUnqualifiedLoc();
5482 DstTL = DstTL.getUnqualifiedLoc();
5483 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5484 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5485 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5486 DstPTL.getPointeeLoc());
5487 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5490 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5491 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5492 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5493 DstPTL.getInnerLoc());
5494 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5495 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5498 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5499 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5500 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5501 TypeLoc DstElemTL = DstATL.getElementLoc();
5502 DstElemTL.initializeFullCopy(SrcElemTL);
5503 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5504 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5505 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5508 /// Helper method to turn variable array types into constant array
5509 /// types in certain situations which would otherwise be errors (for
5510 /// GCC compatibility).
5511 static TypeSourceInfo*
5512 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5513 ASTContext &Context,
5514 bool &SizeIsNegative,
5515 llvm::APSInt &Oversized) {
5517 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5518 SizeIsNegative, Oversized);
5519 if (FixedTy.isNull())
5521 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5522 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5523 FixedTInfo->getTypeLoc());
5527 /// \brief Register the given locally-scoped extern "C" declaration so
5528 /// that it can be found later for redeclarations. We include any extern "C"
5529 /// declaration that is not visible in the translation unit here, not just
5530 /// function-scope declarations.
5532 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5533 if (!getLangOpts().CPlusPlus &&
5534 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5535 // Don't need to track declarations in the TU in C.
5538 // Note that we have a locally-scoped external with this name.
5539 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5542 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5543 // FIXME: We can have multiple results via __attribute__((overloadable)).
5544 auto Result = Context.getExternCContextDecl()->lookup(Name);
5545 return Result.empty() ? nullptr : *Result.begin();
5548 /// \brief Diagnose function specifiers on a declaration of an identifier that
5549 /// does not identify a function.
5550 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5551 // FIXME: We should probably indicate the identifier in question to avoid
5552 // confusion for constructs like "virtual int a(), b;"
5553 if (DS.isVirtualSpecified())
5554 Diag(DS.getVirtualSpecLoc(),
5555 diag::err_virtual_non_function);
5557 if (DS.isExplicitSpecified())
5558 Diag(DS.getExplicitSpecLoc(),
5559 diag::err_explicit_non_function);
5561 if (DS.isNoreturnSpecified())
5562 Diag(DS.getNoreturnSpecLoc(),
5563 diag::err_noreturn_non_function);
5567 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5568 TypeSourceInfo *TInfo, LookupResult &Previous) {
5569 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5570 if (D.getCXXScopeSpec().isSet()) {
5571 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5572 << D.getCXXScopeSpec().getRange();
5574 // Pretend we didn't see the scope specifier.
5579 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5581 if (D.getDeclSpec().isInlineSpecified())
5582 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5583 << getLangOpts().CPlusPlus1z;
5584 if (D.getDeclSpec().isConstexprSpecified())
5585 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5587 if (D.getDeclSpec().isConceptSpecified())
5588 Diag(D.getDeclSpec().getConceptSpecLoc(),
5589 diag::err_concept_wrong_decl_kind);
5591 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5592 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5593 Diag(D.getName().StartLocation,
5594 diag::err_deduction_guide_invalid_specifier)
5597 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5598 << D.getName().getSourceRange();
5602 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5603 if (!NewTD) return nullptr;
5605 // Handle attributes prior to checking for duplicates in MergeVarDecl
5606 ProcessDeclAttributes(S, NewTD, D);
5608 CheckTypedefForVariablyModifiedType(S, NewTD);
5610 bool Redeclaration = D.isRedeclaration();
5611 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5612 D.setRedeclaration(Redeclaration);
5617 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5618 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5619 // then it shall have block scope.
5620 // Note that variably modified types must be fixed before merging the decl so
5621 // that redeclarations will match.
5622 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5623 QualType T = TInfo->getType();
5624 if (T->isVariablyModifiedType()) {
5625 getCurFunction()->setHasBranchProtectedScope();
5627 if (S->getFnParent() == nullptr) {
5628 bool SizeIsNegative;
5629 llvm::APSInt Oversized;
5630 TypeSourceInfo *FixedTInfo =
5631 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5635 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5636 NewTD->setTypeSourceInfo(FixedTInfo);
5639 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5640 else if (T->isVariableArrayType())
5641 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5642 else if (Oversized.getBoolValue())
5643 Diag(NewTD->getLocation(), diag::err_array_too_large)
5644 << Oversized.toString(10);
5646 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5647 NewTD->setInvalidDecl();
5653 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5654 /// declares a typedef-name, either using the 'typedef' type specifier or via
5655 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5657 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5658 LookupResult &Previous, bool &Redeclaration) {
5660 // Find the shadowed declaration before filtering for scope.
5661 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5663 // Merge the decl with the existing one if appropriate. If the decl is
5664 // in an outer scope, it isn't the same thing.
5665 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5666 /*AllowInlineNamespace*/false);
5667 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5668 if (!Previous.empty()) {
5669 Redeclaration = true;
5670 MergeTypedefNameDecl(S, NewTD, Previous);
5673 if (ShadowedDecl && !Redeclaration)
5674 CheckShadow(NewTD, ShadowedDecl, Previous);
5676 // If this is the C FILE type, notify the AST context.
5677 if (IdentifierInfo *II = NewTD->getIdentifier())
5678 if (!NewTD->isInvalidDecl() &&
5679 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5680 if (II->isStr("FILE"))
5681 Context.setFILEDecl(NewTD);
5682 else if (II->isStr("jmp_buf"))
5683 Context.setjmp_bufDecl(NewTD);
5684 else if (II->isStr("sigjmp_buf"))
5685 Context.setsigjmp_bufDecl(NewTD);
5686 else if (II->isStr("ucontext_t"))
5687 Context.setucontext_tDecl(NewTD);
5693 /// \brief Determines whether the given declaration is an out-of-scope
5694 /// previous declaration.
5696 /// This routine should be invoked when name lookup has found a
5697 /// previous declaration (PrevDecl) that is not in the scope where a
5698 /// new declaration by the same name is being introduced. If the new
5699 /// declaration occurs in a local scope, previous declarations with
5700 /// linkage may still be considered previous declarations (C99
5701 /// 6.2.2p4-5, C++ [basic.link]p6).
5703 /// \param PrevDecl the previous declaration found by name
5706 /// \param DC the context in which the new declaration is being
5709 /// \returns true if PrevDecl is an out-of-scope previous declaration
5710 /// for a new delcaration with the same name.
5712 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5713 ASTContext &Context) {
5717 if (!PrevDecl->hasLinkage())
5720 if (Context.getLangOpts().CPlusPlus) {
5721 // C++ [basic.link]p6:
5722 // If there is a visible declaration of an entity with linkage
5723 // having the same name and type, ignoring entities declared
5724 // outside the innermost enclosing namespace scope, the block
5725 // scope declaration declares that same entity and receives the
5726 // linkage of the previous declaration.
5727 DeclContext *OuterContext = DC->getRedeclContext();
5728 if (!OuterContext->isFunctionOrMethod())
5729 // This rule only applies to block-scope declarations.
5732 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5733 if (PrevOuterContext->isRecord())
5734 // We found a member function: ignore it.
5737 // Find the innermost enclosing namespace for the new and
5738 // previous declarations.
5739 OuterContext = OuterContext->getEnclosingNamespaceContext();
5740 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5742 // The previous declaration is in a different namespace, so it
5743 // isn't the same function.
5744 if (!OuterContext->Equals(PrevOuterContext))
5751 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5752 CXXScopeSpec &SS = D.getCXXScopeSpec();
5753 if (!SS.isSet()) return;
5754 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5757 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5758 QualType type = decl->getType();
5759 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5760 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5761 // Various kinds of declaration aren't allowed to be __autoreleasing.
5762 unsigned kind = -1U;
5763 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5764 if (var->hasAttr<BlocksAttr>())
5765 kind = 0; // __block
5766 else if (!var->hasLocalStorage())
5768 } else if (isa<ObjCIvarDecl>(decl)) {
5770 } else if (isa<FieldDecl>(decl)) {
5775 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5778 } else if (lifetime == Qualifiers::OCL_None) {
5779 // Try to infer lifetime.
5780 if (!type->isObjCLifetimeType())
5783 lifetime = type->getObjCARCImplicitLifetime();
5784 type = Context.getLifetimeQualifiedType(type, lifetime);
5785 decl->setType(type);
5788 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5789 // Thread-local variables cannot have lifetime.
5790 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5791 var->getTLSKind()) {
5792 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5801 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5802 // Ensure that an auto decl is deduced otherwise the checks below might cache
5803 // the wrong linkage.
5804 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5806 // 'weak' only applies to declarations with external linkage.
5807 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5808 if (!ND.isExternallyVisible()) {
5809 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5810 ND.dropAttr<WeakAttr>();
5813 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5814 if (ND.isExternallyVisible()) {
5815 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5816 ND.dropAttr<WeakRefAttr>();
5817 ND.dropAttr<AliasAttr>();
5821 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5822 if (VD->hasInit()) {
5823 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5824 assert(VD->isThisDeclarationADefinition() &&
5825 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5826 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5827 VD->dropAttr<AliasAttr>();
5832 // 'selectany' only applies to externally visible variable declarations.
5833 // It does not apply to functions.
5834 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5835 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5836 S.Diag(Attr->getLocation(),
5837 diag::err_attribute_selectany_non_extern_data);
5838 ND.dropAttr<SelectAnyAttr>();
5842 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5843 // dll attributes require external linkage. Static locals may have external
5844 // linkage but still cannot be explicitly imported or exported.
5845 auto *VD = dyn_cast<VarDecl>(&ND);
5846 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5847 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5849 ND.setInvalidDecl();
5853 // Virtual functions cannot be marked as 'notail'.
5854 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5855 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5856 if (MD->isVirtual()) {
5857 S.Diag(ND.getLocation(),
5858 diag::err_invalid_attribute_on_virtual_function)
5860 ND.dropAttr<NotTailCalledAttr>();
5864 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5866 bool IsSpecialization,
5867 bool IsDefinition) {
5868 if (OldDecl->isInvalidDecl())
5871 bool IsTemplate = false;
5872 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5873 OldDecl = OldTD->getTemplatedDecl();
5875 if (!IsSpecialization)
5876 IsDefinition = false;
5878 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5879 NewDecl = NewTD->getTemplatedDecl();
5883 if (!OldDecl || !NewDecl)
5886 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5887 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5888 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5889 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5891 // dllimport and dllexport are inheritable attributes so we have to exclude
5892 // inherited attribute instances.
5893 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5894 (NewExportAttr && !NewExportAttr->isInherited());
5896 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5897 // the only exception being explicit specializations.
5898 // Implicitly generated declarations are also excluded for now because there
5899 // is no other way to switch these to use dllimport or dllexport.
5900 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5902 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5903 // Allow with a warning for free functions and global variables.
5904 bool JustWarn = false;
5905 if (!OldDecl->isCXXClassMember()) {
5906 auto *VD = dyn_cast<VarDecl>(OldDecl);
5907 if (VD && !VD->getDescribedVarTemplate())
5909 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5910 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5914 // We cannot change a declaration that's been used because IR has already
5915 // been emitted. Dllimported functions will still work though (modulo
5916 // address equality) as they can use the thunk.
5917 if (OldDecl->isUsed())
5918 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5921 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5922 : diag::err_attribute_dll_redeclaration;
5923 S.Diag(NewDecl->getLocation(), DiagID)
5925 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5926 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5928 NewDecl->setInvalidDecl();
5933 // A redeclaration is not allowed to drop a dllimport attribute, the only
5934 // exceptions being inline function definitions (except for function
5935 // templates), local extern declarations, qualified friend declarations or
5936 // special MSVC extension: in the last case, the declaration is treated as if
5937 // it were marked dllexport.
5938 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5939 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5940 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5941 // Ignore static data because out-of-line definitions are diagnosed
5943 IsStaticDataMember = VD->isStaticDataMember();
5944 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5945 VarDecl::DeclarationOnly;
5946 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5947 IsInline = FD->isInlined();
5948 IsQualifiedFriend = FD->getQualifier() &&
5949 FD->getFriendObjectKind() == Decl::FOK_Declared;
5952 if (OldImportAttr && !HasNewAttr &&
5953 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5954 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5955 if (IsMicrosoft && IsDefinition) {
5956 S.Diag(NewDecl->getLocation(),
5957 diag::warn_redeclaration_without_import_attribute)
5959 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5960 NewDecl->dropAttr<DLLImportAttr>();
5961 NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5962 NewImportAttr->getRange(), S.Context,
5963 NewImportAttr->getSpellingListIndex()));
5965 S.Diag(NewDecl->getLocation(),
5966 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5967 << NewDecl << OldImportAttr;
5968 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5969 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5970 OldDecl->dropAttr<DLLImportAttr>();
5971 NewDecl->dropAttr<DLLImportAttr>();
5973 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5974 // In MinGW, seeing a function declared inline drops the dllimport attribute.
5975 OldDecl->dropAttr<DLLImportAttr>();
5976 NewDecl->dropAttr<DLLImportAttr>();
5977 S.Diag(NewDecl->getLocation(),
5978 diag::warn_dllimport_dropped_from_inline_function)
5979 << NewDecl << OldImportAttr;
5983 /// Given that we are within the definition of the given function,
5984 /// will that definition behave like C99's 'inline', where the
5985 /// definition is discarded except for optimization purposes?
5986 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5987 // Try to avoid calling GetGVALinkageForFunction.
5989 // All cases of this require the 'inline' keyword.
5990 if (!FD->isInlined()) return false;
5992 // This is only possible in C++ with the gnu_inline attribute.
5993 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5996 // Okay, go ahead and call the relatively-more-expensive function.
5997 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6000 /// Determine whether a variable is extern "C" prior to attaching
6001 /// an initializer. We can't just call isExternC() here, because that
6002 /// will also compute and cache whether the declaration is externally
6003 /// visible, which might change when we attach the initializer.
6005 /// This can only be used if the declaration is known to not be a
6006 /// redeclaration of an internal linkage declaration.
6012 /// Attaching the initializer here makes this declaration not externally
6013 /// visible, because its type has internal linkage.
6015 /// FIXME: This is a hack.
6016 template<typename T>
6017 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6018 if (S.getLangOpts().CPlusPlus) {
6019 // In C++, the overloadable attribute negates the effects of extern "C".
6020 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6023 // So do CUDA's host/device attributes.
6024 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6025 D->template hasAttr<CUDAHostAttr>()))
6028 return D->isExternC();
6031 static bool shouldConsiderLinkage(const VarDecl *VD) {
6032 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6033 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6034 return VD->hasExternalStorage();
6035 if (DC->isFileContext())
6039 llvm_unreachable("Unexpected context");
6042 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6043 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6044 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6045 isa<OMPDeclareReductionDecl>(DC))
6049 llvm_unreachable("Unexpected context");
6052 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6053 AttributeList::Kind Kind) {
6054 for (const AttributeList *L = AttrList; L; L = L->getNext())
6055 if (L->getKind() == Kind)
6060 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6061 AttributeList::Kind Kind) {
6062 // Check decl attributes on the DeclSpec.
6063 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6066 // Walk the declarator structure, checking decl attributes that were in a type
6067 // position to the decl itself.
6068 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6069 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6073 // Finally, check attributes on the decl itself.
6074 return hasParsedAttr(S, PD.getAttributes(), Kind);
6077 /// Adjust the \c DeclContext for a function or variable that might be a
6078 /// function-local external declaration.
6079 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6080 if (!DC->isFunctionOrMethod())
6083 // If this is a local extern function or variable declared within a function
6084 // template, don't add it into the enclosing namespace scope until it is
6085 // instantiated; it might have a dependent type right now.
6086 if (DC->isDependentContext())
6089 // C++11 [basic.link]p7:
6090 // When a block scope declaration of an entity with linkage is not found to
6091 // refer to some other declaration, then that entity is a member of the
6092 // innermost enclosing namespace.
6094 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6095 // semantically-enclosing namespace, not a lexically-enclosing one.
6096 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6097 DC = DC->getParent();
6101 /// \brief Returns true if given declaration has external C language linkage.
6102 static bool isDeclExternC(const Decl *D) {
6103 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6104 return FD->isExternC();
6105 if (const auto *VD = dyn_cast<VarDecl>(D))
6106 return VD->isExternC();
6108 llvm_unreachable("Unknown type of decl!");
6111 NamedDecl *Sema::ActOnVariableDeclarator(
6112 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6113 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6114 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6115 QualType R = TInfo->getType();
6116 DeclarationName Name = GetNameForDeclarator(D).getName();
6118 IdentifierInfo *II = Name.getAsIdentifierInfo();
6120 if (D.isDecompositionDeclarator()) {
6122 // Take the name of the first declarator as our name for diagnostic
6124 auto &Decomp = D.getDecompositionDeclarator();
6125 if (!Decomp.bindings().empty()) {
6126 II = Decomp.bindings()[0].Name;
6130 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6134 if (getLangOpts().OpenCL) {
6135 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6136 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6138 if (R->isImageType() || R->isPipeType()) {
6139 Diag(D.getIdentifierLoc(),
6140 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6146 // OpenCL v1.2 s6.9.r:
6147 // The event type cannot be used to declare a program scope variable.
6148 // OpenCL v2.0 s6.9.q:
6149 // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6150 if (NULL == S->getParent()) {
6151 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6152 Diag(D.getIdentifierLoc(),
6153 diag::err_invalid_type_for_program_scope_var) << R;
6159 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6161 while (NR->isPointerType()) {
6162 if (NR->isFunctionPointerType()) {
6163 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
6167 NR = NR->getPointeeType();
6170 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6171 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6172 // half array type (unless the cl_khr_fp16 extension is enabled).
6173 if (Context.getBaseElementType(R)->isHalfType()) {
6174 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6179 if (R->isSamplerT()) {
6180 // OpenCL v1.2 s6.9.b p4:
6181 // The sampler type cannot be used with the __local and __global address
6182 // space qualifiers.
6183 if (R.getAddressSpace() == LangAS::opencl_local ||
6184 R.getAddressSpace() == LangAS::opencl_global) {
6185 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6188 // OpenCL v1.2 s6.12.14.1:
6189 // A global sampler must be declared with either the constant address
6190 // space qualifier or with the const qualifier.
6191 if (DC->isTranslationUnit() &&
6192 !(R.getAddressSpace() == LangAS::opencl_constant ||
6193 R.isConstQualified())) {
6194 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6199 // OpenCL v1.2 s6.9.r:
6200 // The event type cannot be used with the __local, __constant and __global
6201 // address space qualifiers.
6202 if (R->isEventT()) {
6203 if (R.getAddressSpace()) {
6204 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6210 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6211 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6213 // dllimport globals without explicit storage class are treated as extern. We
6214 // have to change the storage class this early to get the right DeclContext.
6215 if (SC == SC_None && !DC->isRecord() &&
6216 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6217 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6220 DeclContext *OriginalDC = DC;
6221 bool IsLocalExternDecl = SC == SC_Extern &&
6222 adjustContextForLocalExternDecl(DC);
6224 if (SCSpec == DeclSpec::SCS_mutable) {
6225 // mutable can only appear on non-static class members, so it's always
6227 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6232 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6233 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6234 D.getDeclSpec().getStorageClassSpecLoc())) {
6235 // In C++11, the 'register' storage class specifier is deprecated.
6236 // Suppress the warning in system macros, it's used in macros in some
6237 // popular C system headers, such as in glibc's htonl() macro.
6238 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6239 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6240 : diag::warn_deprecated_register)
6241 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6244 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6246 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6247 // C99 6.9p2: The storage-class specifiers auto and register shall not
6248 // appear in the declaration specifiers in an external declaration.
6249 // Global Register+Asm is a GNU extension we support.
6250 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6251 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6256 bool IsMemberSpecialization = false;
6257 bool IsVariableTemplateSpecialization = false;
6258 bool IsPartialSpecialization = false;
6259 bool IsVariableTemplate = false;
6260 VarDecl *NewVD = nullptr;
6261 VarTemplateDecl *NewTemplate = nullptr;
6262 TemplateParameterList *TemplateParams = nullptr;
6263 if (!getLangOpts().CPlusPlus) {
6264 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6265 D.getIdentifierLoc(), II,
6268 if (R->getContainedDeducedType())
6269 ParsingInitForAutoVars.insert(NewVD);
6271 if (D.isInvalidType())
6272 NewVD->setInvalidDecl();
6274 bool Invalid = false;
6276 if (DC->isRecord() && !CurContext->isRecord()) {
6277 // This is an out-of-line definition of a static data member.
6282 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6283 diag::err_static_out_of_line)
6284 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6289 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6290 // to names of variables declared in a block or to function parameters.
6291 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6294 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6295 diag::err_storage_class_for_static_member)
6296 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6298 case SC_PrivateExtern:
6299 llvm_unreachable("C storage class in c++!");
6303 if (SC == SC_Static && CurContext->isRecord()) {
6304 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6305 if (RD->isLocalClass())
6306 Diag(D.getIdentifierLoc(),
6307 diag::err_static_data_member_not_allowed_in_local_class)
6308 << Name << RD->getDeclName();
6310 // C++98 [class.union]p1: If a union contains a static data member,
6311 // the program is ill-formed. C++11 drops this restriction.
6313 Diag(D.getIdentifierLoc(),
6314 getLangOpts().CPlusPlus11
6315 ? diag::warn_cxx98_compat_static_data_member_in_union
6316 : diag::ext_static_data_member_in_union) << Name;
6317 // We conservatively disallow static data members in anonymous structs.
6318 else if (!RD->getDeclName())
6319 Diag(D.getIdentifierLoc(),
6320 diag::err_static_data_member_not_allowed_in_anon_struct)
6321 << Name << RD->isUnion();
6325 // Match up the template parameter lists with the scope specifier, then
6326 // determine whether we have a template or a template specialization.
6327 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6328 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6329 D.getCXXScopeSpec(),
6330 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6331 ? D.getName().TemplateId
6334 /*never a friend*/ false, IsMemberSpecialization, Invalid);
6336 if (TemplateParams) {
6337 if (!TemplateParams->size() &&
6338 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6339 // There is an extraneous 'template<>' for this variable. Complain
6340 // about it, but allow the declaration of the variable.
6341 Diag(TemplateParams->getTemplateLoc(),
6342 diag::err_template_variable_noparams)
6344 << SourceRange(TemplateParams->getTemplateLoc(),
6345 TemplateParams->getRAngleLoc());
6346 TemplateParams = nullptr;
6348 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6349 // This is an explicit specialization or a partial specialization.
6350 // FIXME: Check that we can declare a specialization here.
6351 IsVariableTemplateSpecialization = true;
6352 IsPartialSpecialization = TemplateParams->size() > 0;
6353 } else { // if (TemplateParams->size() > 0)
6354 // This is a template declaration.
6355 IsVariableTemplate = true;
6357 // Check that we can declare a template here.
6358 if (CheckTemplateDeclScope(S, TemplateParams))
6361 // Only C++1y supports variable templates (N3651).
6362 Diag(D.getIdentifierLoc(),
6363 getLangOpts().CPlusPlus14
6364 ? diag::warn_cxx11_compat_variable_template
6365 : diag::ext_variable_template);
6370 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6371 "should have a 'template<>' for this decl");
6374 if (IsVariableTemplateSpecialization) {
6375 SourceLocation TemplateKWLoc =
6376 TemplateParamLists.size() > 0
6377 ? TemplateParamLists[0]->getTemplateLoc()
6379 DeclResult Res = ActOnVarTemplateSpecialization(
6380 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6381 IsPartialSpecialization);
6382 if (Res.isInvalid())
6384 NewVD = cast<VarDecl>(Res.get());
6386 } else if (D.isDecompositionDeclarator()) {
6387 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6388 D.getIdentifierLoc(), R, TInfo, SC,
6391 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6392 D.getIdentifierLoc(), II, R, TInfo, SC);
6394 // If this is supposed to be a variable template, create it as such.
6395 if (IsVariableTemplate) {
6397 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6398 TemplateParams, NewVD);
6399 NewVD->setDescribedVarTemplate(NewTemplate);
6402 // If this decl has an auto type in need of deduction, make a note of the
6403 // Decl so we can diagnose uses of it in its own initializer.
6404 if (R->getContainedDeducedType())
6405 ParsingInitForAutoVars.insert(NewVD);
6407 if (D.isInvalidType() || Invalid) {
6408 NewVD->setInvalidDecl();
6410 NewTemplate->setInvalidDecl();
6413 SetNestedNameSpecifier(NewVD, D);
6415 // If we have any template parameter lists that don't directly belong to
6416 // the variable (matching the scope specifier), store them.
6417 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6418 if (TemplateParamLists.size() > VDTemplateParamLists)
6419 NewVD->setTemplateParameterListsInfo(
6420 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6422 if (D.getDeclSpec().isConstexprSpecified()) {
6423 NewVD->setConstexpr(true);
6424 // C++1z [dcl.spec.constexpr]p1:
6425 // A static data member declared with the constexpr specifier is
6426 // implicitly an inline variable.
6427 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6428 NewVD->setImplicitlyInline();
6431 if (D.getDeclSpec().isConceptSpecified()) {
6432 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6435 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6436 // be declared with the thread_local, inline, friend, or constexpr
6437 // specifiers, [...]
6438 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6439 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6440 diag::err_concept_decl_invalid_specifiers)
6442 NewVD->setInvalidDecl(true);
6445 if (D.getDeclSpec().isConstexprSpecified()) {
6446 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6447 diag::err_concept_decl_invalid_specifiers)
6449 NewVD->setInvalidDecl(true);
6452 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6453 // applied only to the definition of a function template or variable
6454 // template, declared in namespace scope.
6455 if (IsVariableTemplateSpecialization) {
6456 Diag(D.getDeclSpec().getConceptSpecLoc(),
6457 diag::err_concept_specified_specialization)
6458 << (IsPartialSpecialization ? 2 : 1);
6461 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6462 // following restrictions:
6463 // - The declared type shall have the type bool.
6464 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6465 !NewVD->isInvalidDecl()) {
6466 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6467 NewVD->setInvalidDecl(true);
6472 if (D.getDeclSpec().isInlineSpecified()) {
6473 if (!getLangOpts().CPlusPlus) {
6474 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6476 } else if (CurContext->isFunctionOrMethod()) {
6477 // 'inline' is not allowed on block scope variable declaration.
6478 Diag(D.getDeclSpec().getInlineSpecLoc(),
6479 diag::err_inline_declaration_block_scope) << Name
6480 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6482 Diag(D.getDeclSpec().getInlineSpecLoc(),
6483 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6484 : diag::ext_inline_variable);
6485 NewVD->setInlineSpecified();
6489 // Set the lexical context. If the declarator has a C++ scope specifier, the
6490 // lexical context will be different from the semantic context.
6491 NewVD->setLexicalDeclContext(CurContext);
6493 NewTemplate->setLexicalDeclContext(CurContext);
6495 if (IsLocalExternDecl) {
6496 if (D.isDecompositionDeclarator())
6497 for (auto *B : Bindings)
6498 B->setLocalExternDecl();
6500 NewVD->setLocalExternDecl();
6503 bool EmitTLSUnsupportedError = false;
6504 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6505 // C++11 [dcl.stc]p4:
6506 // When thread_local is applied to a variable of block scope the
6507 // storage-class-specifier static is implied if it does not appear
6509 // Core issue: 'static' is not implied if the variable is declared
6511 if (NewVD->hasLocalStorage() &&
6512 (SCSpec != DeclSpec::SCS_unspecified ||
6513 TSCS != DeclSpec::TSCS_thread_local ||
6514 !DC->isFunctionOrMethod()))
6515 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6516 diag::err_thread_non_global)
6517 << DeclSpec::getSpecifierName(TSCS);
6518 else if (!Context.getTargetInfo().isTLSSupported()) {
6519 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6520 // Postpone error emission until we've collected attributes required to
6521 // figure out whether it's a host or device variable and whether the
6522 // error should be ignored.
6523 EmitTLSUnsupportedError = true;
6524 // We still need to mark the variable as TLS so it shows up in AST with
6525 // proper storage class for other tools to use even if we're not going
6526 // to emit any code for it.
6527 NewVD->setTSCSpec(TSCS);
6529 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6530 diag::err_thread_unsupported);
6532 NewVD->setTSCSpec(TSCS);
6536 // An inline definition of a function with external linkage shall
6537 // not contain a definition of a modifiable object with static or
6538 // thread storage duration...
6539 // We only apply this when the function is required to be defined
6540 // elsewhere, i.e. when the function is not 'extern inline'. Note
6541 // that a local variable with thread storage duration still has to
6542 // be marked 'static'. Also note that it's possible to get these
6543 // semantics in C++ using __attribute__((gnu_inline)).
6544 if (SC == SC_Static && S->getFnParent() != nullptr &&
6545 !NewVD->getType().isConstQualified()) {
6546 FunctionDecl *CurFD = getCurFunctionDecl();
6547 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6548 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6549 diag::warn_static_local_in_extern_inline);
6550 MaybeSuggestAddingStaticToDecl(CurFD);
6554 if (D.getDeclSpec().isModulePrivateSpecified()) {
6555 if (IsVariableTemplateSpecialization)
6556 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6557 << (IsPartialSpecialization ? 1 : 0)
6558 << FixItHint::CreateRemoval(
6559 D.getDeclSpec().getModulePrivateSpecLoc());
6560 else if (IsMemberSpecialization)
6561 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6563 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6564 else if (NewVD->hasLocalStorage())
6565 Diag(NewVD->getLocation(), diag::err_module_private_local)
6566 << 0 << NewVD->getDeclName()
6567 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6568 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6570 NewVD->setModulePrivate();
6572 NewTemplate->setModulePrivate();
6573 for (auto *B : Bindings)
6574 B->setModulePrivate();
6578 // Handle attributes prior to checking for duplicates in MergeVarDecl
6579 ProcessDeclAttributes(S, NewVD, D);
6581 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6582 if (EmitTLSUnsupportedError &&
6583 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6584 (getLangOpts().OpenMPIsDevice &&
6585 NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6586 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6587 diag::err_thread_unsupported);
6588 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6589 // storage [duration]."
6590 if (SC == SC_None && S->getFnParent() != nullptr &&
6591 (NewVD->hasAttr<CUDASharedAttr>() ||
6592 NewVD->hasAttr<CUDAConstantAttr>())) {
6593 NewVD->setStorageClass(SC_Static);
6597 // Ensure that dllimport globals without explicit storage class are treated as
6598 // extern. The storage class is set above using parsed attributes. Now we can
6599 // check the VarDecl itself.
6600 assert(!NewVD->hasAttr<DLLImportAttr>() ||
6601 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6602 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6604 // In auto-retain/release, infer strong retension for variables of
6606 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6607 NewVD->setInvalidDecl();
6609 // Handle GNU asm-label extension (encoded as an attribute).
6610 if (Expr *E = (Expr*)D.getAsmLabel()) {
6611 // The parser guarantees this is a string.
6612 StringLiteral *SE = cast<StringLiteral>(E);
6613 StringRef Label = SE->getString();
6614 if (S->getFnParent() != nullptr) {
6618 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6621 // Local Named register
6622 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6623 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6624 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6628 case SC_PrivateExtern:
6631 } else if (SC == SC_Register) {
6632 // Global Named register
6633 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6634 const auto &TI = Context.getTargetInfo();
6635 bool HasSizeMismatch;
6637 if (!TI.isValidGCCRegisterName(Label))
6638 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6639 else if (!TI.validateGlobalRegisterVariable(Label,
6640 Context.getTypeSize(R),
6642 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6643 else if (HasSizeMismatch)
6644 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6647 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6648 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6649 NewVD->setInvalidDecl(true);
6653 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6654 Context, Label, 0));
6655 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6656 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6657 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6658 if (I != ExtnameUndeclaredIdentifiers.end()) {
6659 if (isDeclExternC(NewVD)) {
6660 NewVD->addAttr(I->second);
6661 ExtnameUndeclaredIdentifiers.erase(I);
6663 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6664 << /*Variable*/1 << NewVD;
6668 // Find the shadowed declaration before filtering for scope.
6669 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6670 ? getShadowedDeclaration(NewVD, Previous)
6673 // Don't consider existing declarations that are in a different
6674 // scope and are out-of-semantic-context declarations (if the new
6675 // declaration has linkage).
6676 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6677 D.getCXXScopeSpec().isNotEmpty() ||
6678 IsMemberSpecialization ||
6679 IsVariableTemplateSpecialization);
6681 // Check whether the previous declaration is in the same block scope. This
6682 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6683 if (getLangOpts().CPlusPlus &&
6684 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6685 NewVD->setPreviousDeclInSameBlockScope(
6686 Previous.isSingleResult() && !Previous.isShadowed() &&
6687 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6689 if (!getLangOpts().CPlusPlus) {
6690 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6692 // If this is an explicit specialization of a static data member, check it.
6693 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6694 CheckMemberSpecialization(NewVD, Previous))
6695 NewVD->setInvalidDecl();
6697 // Merge the decl with the existing one if appropriate.
6698 if (!Previous.empty()) {
6699 if (Previous.isSingleResult() &&
6700 isa<FieldDecl>(Previous.getFoundDecl()) &&
6701 D.getCXXScopeSpec().isSet()) {
6702 // The user tried to define a non-static data member
6703 // out-of-line (C++ [dcl.meaning]p1).
6704 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6705 << D.getCXXScopeSpec().getRange();
6707 NewVD->setInvalidDecl();
6709 } else if (D.getCXXScopeSpec().isSet()) {
6710 // No previous declaration in the qualifying scope.
6711 Diag(D.getIdentifierLoc(), diag::err_no_member)
6712 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6713 << D.getCXXScopeSpec().getRange();
6714 NewVD->setInvalidDecl();
6717 if (!IsVariableTemplateSpecialization)
6718 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6720 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6721 // an explicit specialization (14.8.3) or a partial specialization of a
6722 // concept definition.
6723 if (IsVariableTemplateSpecialization &&
6724 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6725 Previous.isSingleResult()) {
6726 NamedDecl *PreviousDecl = Previous.getFoundDecl();
6727 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6728 if (VarTmpl->isConcept()) {
6729 Diag(NewVD->getLocation(), diag::err_concept_specialized)
6731 << (IsPartialSpecialization ? 2 /*partially specialized*/
6732 : 1 /*explicitly specialized*/);
6733 Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6734 NewVD->setInvalidDecl();
6740 VarTemplateDecl *PrevVarTemplate =
6741 NewVD->getPreviousDecl()
6742 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6745 // Check the template parameter list of this declaration, possibly
6746 // merging in the template parameter list from the previous variable
6747 // template declaration.
6748 if (CheckTemplateParameterList(
6750 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6752 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6753 DC->isDependentContext())
6754 ? TPC_ClassTemplateMember
6756 NewVD->setInvalidDecl();
6758 // If we are providing an explicit specialization of a static variable
6759 // template, make a note of that.
6760 if (PrevVarTemplate &&
6761 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6762 PrevVarTemplate->setMemberSpecialization();
6766 // Diagnose shadowed variables iff this isn't a redeclaration.
6767 if (ShadowedDecl && !D.isRedeclaration())
6768 CheckShadow(NewVD, ShadowedDecl, Previous);
6770 ProcessPragmaWeak(S, NewVD);
6772 // If this is the first declaration of an extern C variable, update
6773 // the map of such variables.
6774 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6775 isIncompleteDeclExternC(*this, NewVD))
6776 RegisterLocallyScopedExternCDecl(NewVD, S);
6778 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6779 Decl *ManglingContextDecl;
6780 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6781 NewVD->getDeclContext(), ManglingContextDecl)) {
6782 Context.setManglingNumber(
6783 NewVD, MCtx->getManglingNumber(
6784 NewVD, getMSManglingNumber(getLangOpts(), S)));
6785 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6789 // Special handling of variable named 'main'.
6790 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6791 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6792 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6794 // C++ [basic.start.main]p3
6795 // A program that declares a variable main at global scope is ill-formed.
6796 if (getLangOpts().CPlusPlus)
6797 Diag(D.getLocStart(), diag::err_main_global_variable);
6799 // In C, and external-linkage variable named main results in undefined
6801 else if (NewVD->hasExternalFormalLinkage())
6802 Diag(D.getLocStart(), diag::warn_main_redefined);
6805 if (D.isRedeclaration() && !Previous.empty()) {
6806 checkDLLAttributeRedeclaration(
6807 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6808 IsMemberSpecialization, D.isFunctionDefinition());
6812 if (NewVD->isInvalidDecl())
6813 NewTemplate->setInvalidDecl();
6814 ActOnDocumentableDecl(NewTemplate);
6818 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6819 CompleteMemberSpecialization(NewVD, Previous);
6824 /// Enum describing the %select options in diag::warn_decl_shadow.
6825 enum ShadowedDeclKind {
6834 /// Determine what kind of declaration we're shadowing.
6835 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6836 const DeclContext *OldDC) {
6837 if (isa<TypeAliasDecl>(ShadowedDecl))
6839 else if (isa<TypedefDecl>(ShadowedDecl))
6841 else if (isa<RecordDecl>(OldDC))
6842 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6844 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6847 /// Return the location of the capture if the given lambda captures the given
6848 /// variable \p VD, or an invalid source location otherwise.
6849 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6850 const VarDecl *VD) {
6851 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6852 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6853 return Capture.getLocation();
6855 return SourceLocation();
6858 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6859 const LookupResult &R) {
6860 // Only diagnose if we're shadowing an unambiguous field or variable.
6861 if (R.getResultKind() != LookupResult::Found)
6864 // Return false if warning is ignored.
6865 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6868 /// \brief Return the declaration shadowed by the given variable \p D, or null
6869 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6870 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6871 const LookupResult &R) {
6872 if (!shouldWarnIfShadowedDecl(Diags, R))
6875 // Don't diagnose declarations at file scope.
6876 if (D->hasGlobalStorage())
6879 NamedDecl *ShadowedDecl = R.getFoundDecl();
6880 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6885 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6886 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6887 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6888 const LookupResult &R) {
6889 // Don't warn if typedef declaration is part of a class
6890 if (D->getDeclContext()->isRecord())
6893 if (!shouldWarnIfShadowedDecl(Diags, R))
6896 NamedDecl *ShadowedDecl = R.getFoundDecl();
6897 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6900 /// \brief Diagnose variable or built-in function shadowing. Implements
6903 /// This method is called whenever a VarDecl is added to a "useful"
6906 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6907 /// \param R the lookup of the name
6909 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6910 const LookupResult &R) {
6911 DeclContext *NewDC = D->getDeclContext();
6913 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6914 // Fields are not shadowed by variables in C++ static methods.
6915 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6919 // Fields shadowed by constructor parameters are a special case. Usually
6920 // the constructor initializes the field with the parameter.
6921 if (isa<CXXConstructorDecl>(NewDC))
6922 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6923 // Remember that this was shadowed so we can either warn about its
6924 // modification or its existence depending on warning settings.
6925 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6930 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6931 if (shadowedVar->isExternC()) {
6932 // For shadowing external vars, make sure that we point to the global
6933 // declaration, not a locally scoped extern declaration.
6934 for (auto I : shadowedVar->redecls())
6935 if (I->isFileVarDecl()) {
6941 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
6943 unsigned WarningDiag = diag::warn_decl_shadow;
6944 SourceLocation CaptureLoc;
6945 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6946 isa<CXXMethodDecl>(NewDC)) {
6947 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6948 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6949 if (RD->getLambdaCaptureDefault() == LCD_None) {
6950 // Try to avoid warnings for lambdas with an explicit capture list.
6951 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6952 // Warn only when the lambda captures the shadowed decl explicitly.
6953 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6954 if (CaptureLoc.isInvalid())
6955 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6957 // Remember that this was shadowed so we can avoid the warning if the
6958 // shadowed decl isn't captured and the warning settings allow it.
6959 cast<LambdaScopeInfo>(getCurFunction())
6960 ->ShadowingDecls.push_back(
6961 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6968 // Only warn about certain kinds of shadowing for class members.
6969 if (NewDC && NewDC->isRecord()) {
6970 // In particular, don't warn about shadowing non-class members.
6971 if (!OldDC->isRecord())
6974 // TODO: should we warn about static data members shadowing
6975 // static data members from base classes?
6977 // TODO: don't diagnose for inaccessible shadowed members.
6978 // This is hard to do perfectly because we might friend the
6979 // shadowing context, but that's just a false negative.
6983 DeclarationName Name = R.getLookupName();
6985 // Emit warning and note.
6986 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6988 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6989 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6990 if (!CaptureLoc.isInvalid())
6991 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6992 << Name << /*explicitly*/ 1;
6993 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6996 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6997 /// when these variables are captured by the lambda.
6998 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6999 for (const auto &Shadow : LSI->ShadowingDecls) {
7000 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7001 // Try to avoid the warning when the shadowed decl isn't captured.
7002 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7003 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7004 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7005 ? diag::warn_decl_shadow_uncaptured_local
7006 : diag::warn_decl_shadow)
7007 << Shadow.VD->getDeclName()
7008 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7009 if (!CaptureLoc.isInvalid())
7010 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7011 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7012 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7016 /// \brief Check -Wshadow without the advantage of a previous lookup.
7017 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7018 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7021 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7022 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
7024 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7025 CheckShadow(D, ShadowedDecl, R);
7028 /// Check if 'E', which is an expression that is about to be modified, refers
7029 /// to a constructor parameter that shadows a field.
7030 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7031 // Quickly ignore expressions that can't be shadowing ctor parameters.
7032 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7034 E = E->IgnoreParenImpCasts();
7035 auto *DRE = dyn_cast<DeclRefExpr>(E);
7038 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7039 auto I = ShadowingDecls.find(D);
7040 if (I == ShadowingDecls.end())
7042 const NamedDecl *ShadowedDecl = I->second;
7043 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7044 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7045 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7046 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7048 // Avoid issuing multiple warnings about the same decl.
7049 ShadowingDecls.erase(I);
7052 /// Check for conflict between this global or extern "C" declaration and
7053 /// previous global or extern "C" declarations. This is only used in C++.
7054 template<typename T>
7055 static bool checkGlobalOrExternCConflict(
7056 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7057 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7058 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7060 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7061 // The common case: this global doesn't conflict with any extern "C"
7067 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7068 // Both the old and new declarations have C language linkage. This is a
7071 Previous.addDecl(Prev);
7075 // This is a global, non-extern "C" declaration, and there is a previous
7076 // non-global extern "C" declaration. Diagnose if this is a variable
7078 if (!isa<VarDecl>(ND))
7081 // The declaration is extern "C". Check for any declaration in the
7082 // translation unit which might conflict.
7084 // We have already performed the lookup into the translation unit.
7086 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7088 if (isa<VarDecl>(*I)) {
7094 DeclContext::lookup_result R =
7095 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7096 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7098 if (isa<VarDecl>(*I)) {
7102 // FIXME: If we have any other entity with this name in global scope,
7103 // the declaration is ill-formed, but that is a defect: it breaks the
7104 // 'stat' hack, for instance. Only variables can have mangled name
7105 // clashes with extern "C" declarations, so only they deserve a
7114 // Use the first declaration's location to ensure we point at something which
7115 // is lexically inside an extern "C" linkage-spec.
7116 assert(Prev && "should have found a previous declaration to diagnose");
7117 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7118 Prev = FD->getFirstDecl();
7120 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7122 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7124 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7129 /// Apply special rules for handling extern "C" declarations. Returns \c true
7130 /// if we have found that this is a redeclaration of some prior entity.
7132 /// Per C++ [dcl.link]p6:
7133 /// Two declarations [for a function or variable] with C language linkage
7134 /// with the same name that appear in different scopes refer to the same
7135 /// [entity]. An entity with C language linkage shall not be declared with
7136 /// the same name as an entity in global scope.
7137 template<typename T>
7138 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7139 LookupResult &Previous) {
7140 if (!S.getLangOpts().CPlusPlus) {
7141 // In C, when declaring a global variable, look for a corresponding 'extern'
7142 // variable declared in function scope. We don't need this in C++, because
7143 // we find local extern decls in the surrounding file-scope DeclContext.
7144 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7145 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7147 Previous.addDecl(Prev);
7154 // A declaration in the translation unit can conflict with an extern "C"
7156 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7157 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7159 // An extern "C" declaration can conflict with a declaration in the
7160 // translation unit or can be a redeclaration of an extern "C" declaration
7161 // in another scope.
7162 if (isIncompleteDeclExternC(S,ND))
7163 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7165 // Neither global nor extern "C": nothing to do.
7169 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7170 // If the decl is already known invalid, don't check it.
7171 if (NewVD->isInvalidDecl())
7174 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7175 QualType T = TInfo->getType();
7177 // Defer checking an 'auto' type until its initializer is attached.
7178 if (T->isUndeducedType())
7181 if (NewVD->hasAttrs())
7182 CheckAlignasUnderalignment(NewVD);
7184 if (T->isObjCObjectType()) {
7185 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7186 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7187 T = Context.getObjCObjectPointerType(T);
7191 // Emit an error if an address space was applied to decl with local storage.
7192 // This includes arrays of objects with address space qualifiers, but not
7193 // automatic variables that point to other address spaces.
7194 // ISO/IEC TR 18037 S5.1.2
7195 if (!getLangOpts().OpenCL
7196 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7197 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7198 NewVD->setInvalidDecl();
7202 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7204 if (getLangOpts().OpenCLVersion == 120 &&
7205 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7206 NewVD->isStaticLocal()) {
7207 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7208 NewVD->setInvalidDecl();
7212 if (getLangOpts().OpenCL) {
7213 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7214 if (NewVD->hasAttr<BlocksAttr>()) {
7215 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7219 if (T->isBlockPointerType()) {
7220 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7221 // can't use 'extern' storage class.
7222 if (!T.isConstQualified()) {
7223 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7225 NewVD->setInvalidDecl();
7228 if (NewVD->hasExternalStorage()) {
7229 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7230 NewVD->setInvalidDecl();
7234 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7235 // __constant address space.
7236 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7237 // variables inside a function can also be declared in the global
7239 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7240 NewVD->hasExternalStorage()) {
7241 if (!T->isSamplerT() &&
7242 !(T.getAddressSpace() == LangAS::opencl_constant ||
7243 (T.getAddressSpace() == LangAS::opencl_global &&
7244 getLangOpts().OpenCLVersion == 200))) {
7245 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7246 if (getLangOpts().OpenCLVersion == 200)
7247 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7248 << Scope << "global or constant";
7250 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7251 << Scope << "constant";
7252 NewVD->setInvalidDecl();
7256 if (T.getAddressSpace() == LangAS::opencl_global) {
7257 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7258 << 1 /*is any function*/ << "global";
7259 NewVD->setInvalidDecl();
7262 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
7264 if (T.getAddressSpace() == LangAS::opencl_constant ||
7265 T.getAddressSpace() == LangAS::opencl_local) {
7266 FunctionDecl *FD = getCurFunctionDecl();
7267 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7268 if (T.getAddressSpace() == LangAS::opencl_constant)
7269 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7270 << 0 /*non-kernel only*/ << "constant";
7272 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7273 << 0 /*non-kernel only*/ << "local";
7274 NewVD->setInvalidDecl();
7277 } else if (T.getAddressSpace() != LangAS::Default) {
7278 // Do not allow other address spaces on automatic variable.
7279 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7280 NewVD->setInvalidDecl();
7286 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7287 && !NewVD->hasAttr<BlocksAttr>()) {
7288 if (getLangOpts().getGC() != LangOptions::NonGC)
7289 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7291 assert(!getLangOpts().ObjCAutoRefCount);
7292 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7296 bool isVM = T->isVariablyModifiedType();
7297 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7298 NewVD->hasAttr<BlocksAttr>())
7299 getCurFunction()->setHasBranchProtectedScope();
7301 if ((isVM && NewVD->hasLinkage()) ||
7302 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7303 bool SizeIsNegative;
7304 llvm::APSInt Oversized;
7305 TypeSourceInfo *FixedTInfo =
7306 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7307 SizeIsNegative, Oversized);
7308 if (!FixedTInfo && T->isVariableArrayType()) {
7309 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7310 // FIXME: This won't give the correct result for
7312 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7314 if (NewVD->isFileVarDecl())
7315 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7317 else if (NewVD->isStaticLocal())
7318 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7321 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7323 NewVD->setInvalidDecl();
7328 if (NewVD->isFileVarDecl())
7329 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7331 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7332 NewVD->setInvalidDecl();
7336 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7337 NewVD->setType(FixedTInfo->getType());
7338 NewVD->setTypeSourceInfo(FixedTInfo);
7341 if (T->isVoidType()) {
7342 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7343 // of objects and functions.
7344 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7345 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7347 NewVD->setInvalidDecl();
7352 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7353 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7354 NewVD->setInvalidDecl();
7358 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7359 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7360 NewVD->setInvalidDecl();
7364 if (NewVD->isConstexpr() && !T->isDependentType() &&
7365 RequireLiteralType(NewVD->getLocation(), T,
7366 diag::err_constexpr_var_non_literal)) {
7367 NewVD->setInvalidDecl();
7372 /// \brief Perform semantic checking on a newly-created variable
7375 /// This routine performs all of the type-checking required for a
7376 /// variable declaration once it has been built. It is used both to
7377 /// check variables after they have been parsed and their declarators
7378 /// have been translated into a declaration, and to check variables
7379 /// that have been instantiated from a template.
7381 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7383 /// Returns true if the variable declaration is a redeclaration.
7384 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7385 CheckVariableDeclarationType(NewVD);
7387 // If the decl is already known invalid, don't check it.
7388 if (NewVD->isInvalidDecl())
7391 // If we did not find anything by this name, look for a non-visible
7392 // extern "C" declaration with the same name.
7393 if (Previous.empty() &&
7394 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7395 Previous.setShadowed();
7397 if (!Previous.empty()) {
7398 MergeVarDecl(NewVD, Previous);
7405 struct FindOverriddenMethod {
7407 CXXMethodDecl *Method;
7409 /// Member lookup function that determines whether a given C++
7410 /// method overrides a method in a base class, to be used with
7411 /// CXXRecordDecl::lookupInBases().
7412 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7413 RecordDecl *BaseRecord =
7414 Specifier->getType()->getAs<RecordType>()->getDecl();
7416 DeclarationName Name = Method->getDeclName();
7418 // FIXME: Do we care about other names here too?
7419 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7420 // We really want to find the base class destructor here.
7421 QualType T = S->Context.getTypeDeclType(BaseRecord);
7422 CanQualType CT = S->Context.getCanonicalType(T);
7424 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7427 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7428 Path.Decls = Path.Decls.slice(1)) {
7429 NamedDecl *D = Path.Decls.front();
7430 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7431 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7440 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7441 } // end anonymous namespace
7443 /// \brief Report an error regarding overriding, along with any relevant
7444 /// overriden methods.
7446 /// \param DiagID the primary error to report.
7447 /// \param MD the overriding method.
7448 /// \param OEK which overrides to include as notes.
7449 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7450 OverrideErrorKind OEK = OEK_All) {
7451 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7452 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7453 E = MD->end_overridden_methods();
7455 // This check (& the OEK parameter) could be replaced by a predicate, but
7456 // without lambdas that would be overkill. This is still nicer than writing
7457 // out the diag loop 3 times.
7458 if ((OEK == OEK_All) ||
7459 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7460 (OEK == OEK_Deleted && (*I)->isDeleted()))
7461 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7465 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7466 /// and if so, check that it's a valid override and remember it.
7467 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7468 // Look for methods in base classes that this method might override.
7470 FindOverriddenMethod FOM;
7473 bool hasDeletedOverridenMethods = false;
7474 bool hasNonDeletedOverridenMethods = false;
7475 bool AddedAny = false;
7476 if (DC->lookupInBases(FOM, Paths)) {
7477 for (auto *I : Paths.found_decls()) {
7478 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7479 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7480 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7481 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7482 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7483 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7484 hasDeletedOverridenMethods |= OldMD->isDeleted();
7485 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7492 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7493 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7495 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7496 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7503 // Struct for holding all of the extra arguments needed by
7504 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7505 struct ActOnFDArgs {
7508 MultiTemplateParamsArg TemplateParamLists;
7511 } // end anonymous namespace
7515 // Callback to only accept typo corrections that have a non-zero edit distance.
7516 // Also only accept corrections that have the same parent decl.
7517 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7519 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7520 CXXRecordDecl *Parent)
7521 : Context(Context), OriginalFD(TypoFD),
7522 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7524 bool ValidateCandidate(const TypoCorrection &candidate) override {
7525 if (candidate.getEditDistance() == 0)
7528 SmallVector<unsigned, 1> MismatchedParams;
7529 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7530 CDeclEnd = candidate.end();
7531 CDecl != CDeclEnd; ++CDecl) {
7532 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7534 if (FD && !FD->hasBody() &&
7535 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7536 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7537 CXXRecordDecl *Parent = MD->getParent();
7538 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7540 } else if (!ExpectedParent) {
7550 ASTContext &Context;
7551 FunctionDecl *OriginalFD;
7552 CXXRecordDecl *ExpectedParent;
7555 } // end anonymous namespace
7557 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7558 TypoCorrectedFunctionDefinitions.insert(F);
7561 /// \brief Generate diagnostics for an invalid function redeclaration.
7563 /// This routine handles generating the diagnostic messages for an invalid
7564 /// function redeclaration, including finding possible similar declarations
7565 /// or performing typo correction if there are no previous declarations with
7568 /// Returns a NamedDecl iff typo correction was performed and substituting in
7569 /// the new declaration name does not cause new errors.
7570 static NamedDecl *DiagnoseInvalidRedeclaration(
7571 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7572 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7573 DeclarationName Name = NewFD->getDeclName();
7574 DeclContext *NewDC = NewFD->getDeclContext();
7575 SmallVector<unsigned, 1> MismatchedParams;
7576 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7577 TypoCorrection Correction;
7578 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7579 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7580 : diag::err_member_decl_does_not_match;
7581 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7582 IsLocalFriend ? Sema::LookupLocalFriendName
7583 : Sema::LookupOrdinaryName,
7584 Sema::ForRedeclaration);
7586 NewFD->setInvalidDecl();
7588 SemaRef.LookupName(Prev, S);
7590 SemaRef.LookupQualifiedName(Prev, NewDC);
7591 assert(!Prev.isAmbiguous() &&
7592 "Cannot have an ambiguity in previous-declaration lookup");
7593 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7594 if (!Prev.empty()) {
7595 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7596 Func != FuncEnd; ++Func) {
7597 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7599 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7600 // Add 1 to the index so that 0 can mean the mismatch didn't
7601 // involve a parameter
7603 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7604 NearMatches.push_back(std::make_pair(FD, ParamNum));
7607 // If the qualified name lookup yielded nothing, try typo correction
7608 } else if ((Correction = SemaRef.CorrectTypo(
7609 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7610 &ExtraArgs.D.getCXXScopeSpec(),
7611 llvm::make_unique<DifferentNameValidatorCCC>(
7612 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7613 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7614 // Set up everything for the call to ActOnFunctionDeclarator
7615 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7616 ExtraArgs.D.getIdentifierLoc());
7618 Previous.setLookupName(Correction.getCorrection());
7619 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7620 CDeclEnd = Correction.end();
7621 CDecl != CDeclEnd; ++CDecl) {
7622 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7623 if (FD && !FD->hasBody() &&
7624 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7625 Previous.addDecl(FD);
7628 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7631 // Retry building the function declaration with the new previous
7632 // declarations, and with errors suppressed.
7635 Sema::SFINAETrap Trap(SemaRef);
7637 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7638 // pieces need to verify the typo-corrected C++ declaration and hopefully
7639 // eliminate the need for the parameter pack ExtraArgs.
7640 Result = SemaRef.ActOnFunctionDeclarator(
7641 ExtraArgs.S, ExtraArgs.D,
7642 Correction.getCorrectionDecl()->getDeclContext(),
7643 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7644 ExtraArgs.AddToScope);
7646 if (Trap.hasErrorOccurred())
7651 // Determine which correction we picked.
7652 Decl *Canonical = Result->getCanonicalDecl();
7653 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7655 if ((*I)->getCanonicalDecl() == Canonical)
7656 Correction.setCorrectionDecl(*I);
7658 // Let Sema know about the correction.
7659 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7660 SemaRef.diagnoseTypo(
7662 SemaRef.PDiag(IsLocalFriend
7663 ? diag::err_no_matching_local_friend_suggest
7664 : diag::err_member_decl_does_not_match_suggest)
7665 << Name << NewDC << IsDefinition);
7669 // Pretend the typo correction never occurred
7670 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7671 ExtraArgs.D.getIdentifierLoc());
7672 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7674 Previous.setLookupName(Name);
7677 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7678 << Name << NewDC << IsDefinition << NewFD->getLocation();
7680 bool NewFDisConst = false;
7681 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7682 NewFDisConst = NewMD->isConst();
7684 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7685 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7686 NearMatch != NearMatchEnd; ++NearMatch) {
7687 FunctionDecl *FD = NearMatch->first;
7688 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7689 bool FDisConst = MD && MD->isConst();
7690 bool IsMember = MD || !IsLocalFriend;
7692 // FIXME: These notes are poorly worded for the local friend case.
7693 if (unsigned Idx = NearMatch->second) {
7694 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7695 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7696 if (Loc.isInvalid()) Loc = FD->getLocation();
7697 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7698 : diag::note_local_decl_close_param_match)
7699 << Idx << FDParam->getType()
7700 << NewFD->getParamDecl(Idx - 1)->getType();
7701 } else if (FDisConst != NewFDisConst) {
7702 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7703 << NewFDisConst << FD->getSourceRange().getEnd();
7705 SemaRef.Diag(FD->getLocation(),
7706 IsMember ? diag::note_member_def_close_match
7707 : diag::note_local_decl_close_match);
7712 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7713 switch (D.getDeclSpec().getStorageClassSpec()) {
7714 default: llvm_unreachable("Unknown storage class!");
7715 case DeclSpec::SCS_auto:
7716 case DeclSpec::SCS_register:
7717 case DeclSpec::SCS_mutable:
7718 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7719 diag::err_typecheck_sclass_func);
7720 D.getMutableDeclSpec().ClearStorageClassSpecs();
7723 case DeclSpec::SCS_unspecified: break;
7724 case DeclSpec::SCS_extern:
7725 if (D.getDeclSpec().isExternInLinkageSpec())
7728 case DeclSpec::SCS_static: {
7729 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7731 // The declaration of an identifier for a function that has
7732 // block scope shall have no explicit storage-class specifier
7733 // other than extern
7734 // See also (C++ [dcl.stc]p4).
7735 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7736 diag::err_static_block_func);
7741 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7744 // No explicit storage class has already been returned
7748 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7749 DeclContext *DC, QualType &R,
7750 TypeSourceInfo *TInfo,
7752 bool &IsVirtualOkay) {
7753 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7754 DeclarationName Name = NameInfo.getName();
7756 FunctionDecl *NewFD = nullptr;
7757 bool isInline = D.getDeclSpec().isInlineSpecified();
7759 if (!SemaRef.getLangOpts().CPlusPlus) {
7760 // Determine whether the function was written with a
7761 // prototype. This true when:
7762 // - there is a prototype in the declarator, or
7763 // - the type R of the function is some kind of typedef or other non-
7764 // attributed reference to a type name (which eventually refers to a
7767 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7768 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7770 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7771 D.getLocStart(), NameInfo, R,
7772 TInfo, SC, isInline,
7773 HasPrototype, false);
7774 if (D.isInvalidType())
7775 NewFD->setInvalidDecl();
7780 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7781 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7783 // Check that the return type is not an abstract class type.
7784 // For record types, this is done by the AbstractClassUsageDiagnoser once
7785 // the class has been completely parsed.
7786 if (!DC->isRecord() &&
7787 SemaRef.RequireNonAbstractType(
7788 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7789 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7792 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7793 // This is a C++ constructor declaration.
7794 assert(DC->isRecord() &&
7795 "Constructors can only be declared in a member context");
7797 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7798 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7799 D.getLocStart(), NameInfo,
7800 R, TInfo, isExplicit, isInline,
7801 /*isImplicitlyDeclared=*/false,
7804 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7805 // This is a C++ destructor declaration.
7806 if (DC->isRecord()) {
7807 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7808 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7809 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7810 SemaRef.Context, Record,
7812 NameInfo, R, TInfo, isInline,
7813 /*isImplicitlyDeclared=*/false);
7815 // If the class is complete, then we now create the implicit exception
7816 // specification. If the class is incomplete or dependent, we can't do
7818 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7819 Record->getDefinition() && !Record->isBeingDefined() &&
7820 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7821 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7824 IsVirtualOkay = true;
7828 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7831 // Create a FunctionDecl to satisfy the function definition parsing
7833 return FunctionDecl::Create(SemaRef.Context, DC,
7835 D.getIdentifierLoc(), Name, R, TInfo,
7837 /*hasPrototype=*/true, isConstexpr);
7840 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7841 if (!DC->isRecord()) {
7842 SemaRef.Diag(D.getIdentifierLoc(),
7843 diag::err_conv_function_not_member);
7847 SemaRef.CheckConversionDeclarator(D, R, SC);
7848 IsVirtualOkay = true;
7849 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7850 D.getLocStart(), NameInfo,
7851 R, TInfo, isInline, isExplicit,
7852 isConstexpr, SourceLocation());
7854 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7855 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7857 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7858 isExplicit, NameInfo, R, TInfo,
7860 } else if (DC->isRecord()) {
7861 // If the name of the function is the same as the name of the record,
7862 // then this must be an invalid constructor that has a return type.
7863 // (The parser checks for a return type and makes the declarator a
7864 // constructor if it has no return type).
7865 if (Name.getAsIdentifierInfo() &&
7866 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7867 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7868 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7869 << SourceRange(D.getIdentifierLoc());
7873 // This is a C++ method declaration.
7874 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7875 cast<CXXRecordDecl>(DC),
7876 D.getLocStart(), NameInfo, R,
7877 TInfo, SC, isInline,
7878 isConstexpr, SourceLocation());
7879 IsVirtualOkay = !Ret->isStatic();
7883 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7884 if (!isFriend && SemaRef.CurContext->isRecord())
7887 // Determine whether the function was written with a
7888 // prototype. This true when:
7889 // - we're in C++ (where every function has a prototype),
7890 return FunctionDecl::Create(SemaRef.Context, DC,
7892 NameInfo, R, TInfo, SC, isInline,
7893 true/*HasPrototype*/, isConstexpr);
7897 enum OpenCLParamType {
7901 InvalidAddrSpacePtrKernelParam,
7906 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7907 if (PT->isPointerType()) {
7908 QualType PointeeType = PT->getPointeeType();
7909 if (PointeeType->isPointerType())
7910 return PtrPtrKernelParam;
7911 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7912 PointeeType.getAddressSpace() == 0)
7913 return InvalidAddrSpacePtrKernelParam;
7914 return PtrKernelParam;
7917 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7918 // be used as builtin types.
7920 if (PT->isImageType())
7921 return PtrKernelParam;
7923 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
7924 return InvalidKernelParam;
7926 // OpenCL extension spec v1.2 s9.5:
7927 // This extension adds support for half scalar and vector types as built-in
7928 // types that can be used for arithmetic operations, conversions etc.
7929 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7930 return InvalidKernelParam;
7932 if (PT->isRecordType())
7933 return RecordKernelParam;
7935 return ValidKernelParam;
7938 static void checkIsValidOpenCLKernelParameter(
7942 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7943 QualType PT = Param->getType();
7945 // Cache the valid types we encounter to avoid rechecking structs that are
7947 if (ValidTypes.count(PT.getTypePtr()))
7950 switch (getOpenCLKernelParameterType(S, PT)) {
7951 case PtrPtrKernelParam:
7952 // OpenCL v1.2 s6.9.a:
7953 // A kernel function argument cannot be declared as a
7954 // pointer to a pointer type.
7955 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7959 case InvalidAddrSpacePtrKernelParam:
7960 // OpenCL v1.0 s6.5:
7961 // __kernel function arguments declared to be a pointer of a type can point
7962 // to one of the following address spaces only : __global, __local or
7964 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7968 // OpenCL v1.2 s6.9.k:
7969 // Arguments to kernel functions in a program cannot be declared with the
7970 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7971 // uintptr_t or a struct and/or union that contain fields declared to be
7972 // one of these built-in scalar types.
7974 case InvalidKernelParam:
7975 // OpenCL v1.2 s6.8 n:
7976 // A kernel function argument cannot be declared
7978 // Do not diagnose half type since it is diagnosed as invalid argument
7979 // type for any function elsewhere.
7980 if (!PT->isHalfType())
7981 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7985 case PtrKernelParam:
7986 case ValidKernelParam:
7987 ValidTypes.insert(PT.getTypePtr());
7990 case RecordKernelParam:
7994 // Track nested structs we will inspect
7995 SmallVector<const Decl *, 4> VisitStack;
7997 // Track where we are in the nested structs. Items will migrate from
7998 // VisitStack to HistoryStack as we do the DFS for bad field.
7999 SmallVector<const FieldDecl *, 4> HistoryStack;
8000 HistoryStack.push_back(nullptr);
8002 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8003 VisitStack.push_back(PD);
8005 assert(VisitStack.back() && "First decl null?");
8008 const Decl *Next = VisitStack.pop_back_val();
8010 assert(!HistoryStack.empty());
8011 // Found a marker, we have gone up a level
8012 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8013 ValidTypes.insert(Hist->getType().getTypePtr());
8018 // Adds everything except the original parameter declaration (which is not a
8019 // field itself) to the history stack.
8020 const RecordDecl *RD;
8021 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8022 HistoryStack.push_back(Field);
8023 RD = Field->getType()->castAs<RecordType>()->getDecl();
8025 RD = cast<RecordDecl>(Next);
8028 // Add a null marker so we know when we've gone back up a level
8029 VisitStack.push_back(nullptr);
8031 for (const auto *FD : RD->fields()) {
8032 QualType QT = FD->getType();
8034 if (ValidTypes.count(QT.getTypePtr()))
8037 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8038 if (ParamType == ValidKernelParam)
8041 if (ParamType == RecordKernelParam) {
8042 VisitStack.push_back(FD);
8046 // OpenCL v1.2 s6.9.p:
8047 // Arguments to kernel functions that are declared to be a struct or union
8048 // do not allow OpenCL objects to be passed as elements of the struct or
8050 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8051 ParamType == InvalidAddrSpacePtrKernelParam) {
8052 S.Diag(Param->getLocation(),
8053 diag::err_record_with_pointers_kernel_param)
8054 << PT->isUnionType()
8057 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8060 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8061 << PD->getDeclName();
8063 // We have an error, now let's go back up through history and show where
8064 // the offending field came from
8065 for (ArrayRef<const FieldDecl *>::const_iterator
8066 I = HistoryStack.begin() + 1,
8067 E = HistoryStack.end();
8069 const FieldDecl *OuterField = *I;
8070 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8071 << OuterField->getType();
8074 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8075 << QT->isPointerType()
8080 } while (!VisitStack.empty());
8083 /// Find the DeclContext in which a tag is implicitly declared if we see an
8084 /// elaborated type specifier in the specified context, and lookup finds
8086 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8087 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8088 DC = DC->getParent();
8092 /// Find the Scope in which a tag is implicitly declared if we see an
8093 /// elaborated type specifier in the specified context, and lookup finds
8095 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8096 while (S->isClassScope() ||
8097 (LangOpts.CPlusPlus &&
8098 S->isFunctionPrototypeScope()) ||
8099 ((S->getFlags() & Scope::DeclScope) == 0) ||
8100 (S->getEntity() && S->getEntity()->isTransparentContext()))
8106 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8107 TypeSourceInfo *TInfo, LookupResult &Previous,
8108 MultiTemplateParamsArg TemplateParamLists,
8110 QualType R = TInfo->getType();
8112 assert(R.getTypePtr()->isFunctionType());
8114 // TODO: consider using NameInfo for diagnostic.
8115 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8116 DeclarationName Name = NameInfo.getName();
8117 StorageClass SC = getFunctionStorageClass(*this, D);
8119 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8120 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8121 diag::err_invalid_thread)
8122 << DeclSpec::getSpecifierName(TSCS);
8124 if (D.isFirstDeclarationOfMember())
8125 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8126 D.getIdentifierLoc());
8128 bool isFriend = false;
8129 FunctionTemplateDecl *FunctionTemplate = nullptr;
8130 bool isMemberSpecialization = false;
8131 bool isFunctionTemplateSpecialization = false;
8133 bool isDependentClassScopeExplicitSpecialization = false;
8134 bool HasExplicitTemplateArgs = false;
8135 TemplateArgumentListInfo TemplateArgs;
8137 bool isVirtualOkay = false;
8139 DeclContext *OriginalDC = DC;
8140 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8142 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8144 if (!NewFD) return nullptr;
8146 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8147 NewFD->setTopLevelDeclInObjCContainer();
8149 // Set the lexical context. If this is a function-scope declaration, or has a
8150 // C++ scope specifier, or is the object of a friend declaration, the lexical
8151 // context will be different from the semantic context.
8152 NewFD->setLexicalDeclContext(CurContext);
8154 if (IsLocalExternDecl)
8155 NewFD->setLocalExternDecl();
8157 if (getLangOpts().CPlusPlus) {
8158 bool isInline = D.getDeclSpec().isInlineSpecified();
8159 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8160 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8161 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8162 bool isConcept = D.getDeclSpec().isConceptSpecified();
8163 isFriend = D.getDeclSpec().isFriendSpecified();
8164 if (isFriend && !isInline && D.isFunctionDefinition()) {
8165 // C++ [class.friend]p5
8166 // A function can be defined in a friend declaration of a
8167 // class . . . . Such a function is implicitly inline.
8168 NewFD->setImplicitlyInline();
8171 // If this is a method defined in an __interface, and is not a constructor
8172 // or an overloaded operator, then set the pure flag (isVirtual will already
8174 if (const CXXRecordDecl *Parent =
8175 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8176 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8177 NewFD->setPure(true);
8179 // C++ [class.union]p2
8180 // A union can have member functions, but not virtual functions.
8181 if (isVirtual && Parent->isUnion())
8182 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8185 SetNestedNameSpecifier(NewFD, D);
8186 isMemberSpecialization = false;
8187 isFunctionTemplateSpecialization = false;
8188 if (D.isInvalidType())
8189 NewFD->setInvalidDecl();
8191 // Match up the template parameter lists with the scope specifier, then
8192 // determine whether we have a template or a template specialization.
8193 bool Invalid = false;
8194 if (TemplateParameterList *TemplateParams =
8195 MatchTemplateParametersToScopeSpecifier(
8196 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8197 D.getCXXScopeSpec(),
8198 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8199 ? D.getName().TemplateId
8201 TemplateParamLists, isFriend, isMemberSpecialization,
8203 if (TemplateParams->size() > 0) {
8204 // This is a function template
8206 // Check that we can declare a template here.
8207 if (CheckTemplateDeclScope(S, TemplateParams))
8208 NewFD->setInvalidDecl();
8210 // A destructor cannot be a template.
8211 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8212 Diag(NewFD->getLocation(), diag::err_destructor_template);
8213 NewFD->setInvalidDecl();
8216 // If we're adding a template to a dependent context, we may need to
8217 // rebuilding some of the types used within the template parameter list,
8218 // now that we know what the current instantiation is.
8219 if (DC->isDependentContext()) {
8220 ContextRAII SavedContext(*this, DC);
8221 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8225 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8226 NewFD->getLocation(),
8227 Name, TemplateParams,
8229 FunctionTemplate->setLexicalDeclContext(CurContext);
8230 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8232 // For source fidelity, store the other template param lists.
8233 if (TemplateParamLists.size() > 1) {
8234 NewFD->setTemplateParameterListsInfo(Context,
8235 TemplateParamLists.drop_back(1));
8238 // This is a function template specialization.
8239 isFunctionTemplateSpecialization = true;
8240 // For source fidelity, store all the template param lists.
8241 if (TemplateParamLists.size() > 0)
8242 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8244 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8246 // We want to remove the "template<>", found here.
8247 SourceRange RemoveRange = TemplateParams->getSourceRange();
8249 // If we remove the template<> and the name is not a
8250 // template-id, we're actually silently creating a problem:
8251 // the friend declaration will refer to an untemplated decl,
8252 // and clearly the user wants a template specialization. So
8253 // we need to insert '<>' after the name.
8254 SourceLocation InsertLoc;
8255 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8256 InsertLoc = D.getName().getSourceRange().getEnd();
8257 InsertLoc = getLocForEndOfToken(InsertLoc);
8260 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8261 << Name << RemoveRange
8262 << FixItHint::CreateRemoval(RemoveRange)
8263 << FixItHint::CreateInsertion(InsertLoc, "<>");
8268 // All template param lists were matched against the scope specifier:
8269 // this is NOT (an explicit specialization of) a template.
8270 if (TemplateParamLists.size() > 0)
8271 // For source fidelity, store all the template param lists.
8272 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8276 NewFD->setInvalidDecl();
8277 if (FunctionTemplate)
8278 FunctionTemplate->setInvalidDecl();
8281 // C++ [dcl.fct.spec]p5:
8282 // The virtual specifier shall only be used in declarations of
8283 // nonstatic class member functions that appear within a
8284 // member-specification of a class declaration; see 10.3.
8286 if (isVirtual && !NewFD->isInvalidDecl()) {
8287 if (!isVirtualOkay) {
8288 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8289 diag::err_virtual_non_function);
8290 } else if (!CurContext->isRecord()) {
8291 // 'virtual' was specified outside of the class.
8292 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8293 diag::err_virtual_out_of_class)
8294 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8295 } else if (NewFD->getDescribedFunctionTemplate()) {
8296 // C++ [temp.mem]p3:
8297 // A member function template shall not be virtual.
8298 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8299 diag::err_virtual_member_function_template)
8300 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8302 // Okay: Add virtual to the method.
8303 NewFD->setVirtualAsWritten(true);
8306 if (getLangOpts().CPlusPlus14 &&
8307 NewFD->getReturnType()->isUndeducedType())
8308 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8311 if (getLangOpts().CPlusPlus14 &&
8312 (NewFD->isDependentContext() ||
8313 (isFriend && CurContext->isDependentContext())) &&
8314 NewFD->getReturnType()->isUndeducedType()) {
8315 // If the function template is referenced directly (for instance, as a
8316 // member of the current instantiation), pretend it has a dependent type.
8317 // This is not really justified by the standard, but is the only sane
8319 // FIXME: For a friend function, we have not marked the function as being
8320 // a friend yet, so 'isDependentContext' on the FD doesn't work.
8321 const FunctionProtoType *FPT =
8322 NewFD->getType()->castAs<FunctionProtoType>();
8324 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8325 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8326 FPT->getExtProtoInfo()));
8329 // C++ [dcl.fct.spec]p3:
8330 // The inline specifier shall not appear on a block scope function
8332 if (isInline && !NewFD->isInvalidDecl()) {
8333 if (CurContext->isFunctionOrMethod()) {
8334 // 'inline' is not allowed on block scope function declaration.
8335 Diag(D.getDeclSpec().getInlineSpecLoc(),
8336 diag::err_inline_declaration_block_scope) << Name
8337 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8341 // C++ [dcl.fct.spec]p6:
8342 // The explicit specifier shall be used only in the declaration of a
8343 // constructor or conversion function within its class definition;
8344 // see 12.3.1 and 12.3.2.
8345 if (isExplicit && !NewFD->isInvalidDecl() &&
8346 !isa<CXXDeductionGuideDecl>(NewFD)) {
8347 if (!CurContext->isRecord()) {
8348 // 'explicit' was specified outside of the class.
8349 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8350 diag::err_explicit_out_of_class)
8351 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8352 } else if (!isa<CXXConstructorDecl>(NewFD) &&
8353 !isa<CXXConversionDecl>(NewFD)) {
8354 // 'explicit' was specified on a function that wasn't a constructor
8355 // or conversion function.
8356 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8357 diag::err_explicit_non_ctor_or_conv_function)
8358 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8363 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8364 // are implicitly inline.
8365 NewFD->setImplicitlyInline();
8367 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8368 // be either constructors or to return a literal type. Therefore,
8369 // destructors cannot be declared constexpr.
8370 if (isa<CXXDestructorDecl>(NewFD))
8371 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8375 // This is a function concept.
8376 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8379 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8380 // applied only to the definition of a function template [...]
8381 if (!D.isFunctionDefinition()) {
8382 Diag(D.getDeclSpec().getConceptSpecLoc(),
8383 diag::err_function_concept_not_defined);
8384 NewFD->setInvalidDecl();
8387 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8388 // have no exception-specification and is treated as if it were specified
8389 // with noexcept(true) (15.4). [...]
8390 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8391 if (FPT->hasExceptionSpec()) {
8393 if (D.isFunctionDeclarator())
8394 Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8395 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8396 << FixItHint::CreateRemoval(Range);
8397 NewFD->setInvalidDecl();
8399 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8402 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8403 // following restrictions:
8404 // - The declared return type shall have the type bool.
8405 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8406 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8407 NewFD->setInvalidDecl();
8410 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8411 // following restrictions:
8412 // - The declaration's parameter list shall be equivalent to an empty
8414 if (FPT->getNumParams() > 0 || FPT->isVariadic())
8415 Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8418 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8419 // implicity defined to be a constexpr declaration (implicitly inline)
8420 NewFD->setImplicitlyInline();
8422 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8423 // be declared with the thread_local, inline, friend, or constexpr
8424 // specifiers, [...]
8426 Diag(D.getDeclSpec().getInlineSpecLoc(),
8427 diag::err_concept_decl_invalid_specifiers)
8429 NewFD->setInvalidDecl(true);
8433 Diag(D.getDeclSpec().getFriendSpecLoc(),
8434 diag::err_concept_decl_invalid_specifiers)
8436 NewFD->setInvalidDecl(true);
8440 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8441 diag::err_concept_decl_invalid_specifiers)
8443 NewFD->setInvalidDecl(true);
8446 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8447 // applied only to the definition of a function template or variable
8448 // template, declared in namespace scope.
8449 if (isFunctionTemplateSpecialization) {
8450 Diag(D.getDeclSpec().getConceptSpecLoc(),
8451 diag::err_concept_specified_specialization) << 1;
8452 NewFD->setInvalidDecl(true);
8457 // If __module_private__ was specified, mark the function accordingly.
8458 if (D.getDeclSpec().isModulePrivateSpecified()) {
8459 if (isFunctionTemplateSpecialization) {
8460 SourceLocation ModulePrivateLoc
8461 = D.getDeclSpec().getModulePrivateSpecLoc();
8462 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8464 << FixItHint::CreateRemoval(ModulePrivateLoc);
8466 NewFD->setModulePrivate();
8467 if (FunctionTemplate)
8468 FunctionTemplate->setModulePrivate();
8473 if (FunctionTemplate) {
8474 FunctionTemplate->setObjectOfFriendDecl();
8475 FunctionTemplate->setAccess(AS_public);
8477 NewFD->setObjectOfFriendDecl();
8478 NewFD->setAccess(AS_public);
8481 // If a function is defined as defaulted or deleted, mark it as such now.
8482 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8483 // definition kind to FDK_Definition.
8484 switch (D.getFunctionDefinitionKind()) {
8485 case FDK_Declaration:
8486 case FDK_Definition:
8490 NewFD->setDefaulted();
8494 NewFD->setDeletedAsWritten();
8498 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8499 D.isFunctionDefinition()) {
8500 // C++ [class.mfct]p2:
8501 // A member function may be defined (8.4) in its class definition, in
8502 // which case it is an inline member function (7.1.2)
8503 NewFD->setImplicitlyInline();
8506 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8507 !CurContext->isRecord()) {
8508 // C++ [class.static]p1:
8509 // A data or function member of a class may be declared static
8510 // in a class definition, in which case it is a static member of
8513 // Complain about the 'static' specifier if it's on an out-of-line
8514 // member function definition.
8515 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8516 diag::err_static_out_of_line)
8517 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8520 // C++11 [except.spec]p15:
8521 // A deallocation function with no exception-specification is treated
8522 // as if it were specified with noexcept(true).
8523 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8524 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8525 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8526 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8527 NewFD->setType(Context.getFunctionType(
8528 FPT->getReturnType(), FPT->getParamTypes(),
8529 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8532 // Filter out previous declarations that don't match the scope.
8533 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8534 D.getCXXScopeSpec().isNotEmpty() ||
8535 isMemberSpecialization ||
8536 isFunctionTemplateSpecialization);
8538 // Handle GNU asm-label extension (encoded as an attribute).
8539 if (Expr *E = (Expr*) D.getAsmLabel()) {
8540 // The parser guarantees this is a string.
8541 StringLiteral *SE = cast<StringLiteral>(E);
8542 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8543 SE->getString(), 0));
8544 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8545 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8546 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8547 if (I != ExtnameUndeclaredIdentifiers.end()) {
8548 if (isDeclExternC(NewFD)) {
8549 NewFD->addAttr(I->second);
8550 ExtnameUndeclaredIdentifiers.erase(I);
8552 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8553 << /*Variable*/0 << NewFD;
8557 // Copy the parameter declarations from the declarator D to the function
8558 // declaration NewFD, if they are available. First scavenge them into Params.
8559 SmallVector<ParmVarDecl*, 16> Params;
8561 if (D.isFunctionDeclarator(FTIIdx)) {
8562 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8564 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8565 // function that takes no arguments, not a function that takes a
8566 // single void argument.
8567 // We let through "const void" here because Sema::GetTypeForDeclarator
8568 // already checks for that case.
8569 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8570 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8571 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8572 assert(Param->getDeclContext() != NewFD && "Was set before ?");
8573 Param->setDeclContext(NewFD);
8574 Params.push_back(Param);
8576 if (Param->isInvalidDecl())
8577 NewFD->setInvalidDecl();
8581 if (!getLangOpts().CPlusPlus) {
8582 // In C, find all the tag declarations from the prototype and move them
8583 // into the function DeclContext. Remove them from the surrounding tag
8584 // injection context of the function, which is typically but not always
8586 DeclContext *PrototypeTagContext =
8587 getTagInjectionContext(NewFD->getLexicalDeclContext());
8588 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8589 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8591 // We don't want to reparent enumerators. Look at their parent enum
8594 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8595 TD = cast<EnumDecl>(ECD->getDeclContext());
8599 DeclContext *TagDC = TD->getLexicalDeclContext();
8600 if (!TagDC->containsDecl(TD))
8602 TagDC->removeDecl(TD);
8603 TD->setDeclContext(NewFD);
8606 // Preserve the lexical DeclContext if it is not the surrounding tag
8607 // injection context of the FD. In this example, the semantic context of
8608 // E will be f and the lexical context will be S, while both the
8609 // semantic and lexical contexts of S will be f:
8610 // void f(struct S { enum E { a } f; } s);
8611 if (TagDC != PrototypeTagContext)
8612 TD->setLexicalDeclContext(TagDC);
8615 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8616 // When we're declaring a function with a typedef, typeof, etc as in the
8617 // following example, we'll need to synthesize (unnamed)
8618 // parameters for use in the declaration.
8621 // typedef void fn(int);
8625 // Synthesize a parameter for each argument type.
8626 for (const auto &AI : FT->param_types()) {
8627 ParmVarDecl *Param =
8628 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8629 Param->setScopeInfo(0, Params.size());
8630 Params.push_back(Param);
8633 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8634 "Should not need args for typedef of non-prototype fn");
8637 // Finally, we know we have the right number of parameters, install them.
8638 NewFD->setParams(Params);
8640 if (D.getDeclSpec().isNoreturnSpecified())
8642 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8645 // Functions returning a variably modified type violate C99 6.7.5.2p2
8646 // because all functions have linkage.
8647 if (!NewFD->isInvalidDecl() &&
8648 NewFD->getReturnType()->isVariablyModifiedType()) {
8649 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8650 NewFD->setInvalidDecl();
8653 // Apply an implicit SectionAttr if #pragma code_seg is active.
8654 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8655 !NewFD->hasAttr<SectionAttr>()) {
8657 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8658 CodeSegStack.CurrentValue->getString(),
8659 CodeSegStack.CurrentPragmaLocation));
8660 if (UnifySection(CodeSegStack.CurrentValue->getString(),
8661 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8662 ASTContext::PSF_Read,
8664 NewFD->dropAttr<SectionAttr>();
8667 // Handle attributes.
8668 ProcessDeclAttributes(S, NewFD, D);
8670 if (getLangOpts().OpenCL) {
8671 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8672 // type declaration will generate a compilation error.
8673 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8674 if (AddressSpace == LangAS::opencl_local ||
8675 AddressSpace == LangAS::opencl_global ||
8676 AddressSpace == LangAS::opencl_constant) {
8677 Diag(NewFD->getLocation(),
8678 diag::err_opencl_return_value_with_address_space);
8679 NewFD->setInvalidDecl();
8683 if (!getLangOpts().CPlusPlus) {
8684 // Perform semantic checking on the function declaration.
8685 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8686 CheckMain(NewFD, D.getDeclSpec());
8688 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8689 CheckMSVCRTEntryPoint(NewFD);
8691 if (!NewFD->isInvalidDecl())
8692 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8693 isMemberSpecialization));
8694 else if (!Previous.empty())
8695 // Recover gracefully from an invalid redeclaration.
8696 D.setRedeclaration(true);
8697 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8698 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8699 "previous declaration set still overloaded");
8701 // Diagnose no-prototype function declarations with calling conventions that
8702 // don't support variadic calls. Only do this in C and do it after merging
8703 // possibly prototyped redeclarations.
8704 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8705 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8706 CallingConv CC = FT->getExtInfo().getCC();
8707 if (!supportsVariadicCall(CC)) {
8708 // Windows system headers sometimes accidentally use stdcall without
8709 // (void) parameters, so we relax this to a warning.
8711 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8712 Diag(NewFD->getLocation(), DiagID)
8713 << FunctionType::getNameForCallConv(CC);
8717 // C++11 [replacement.functions]p3:
8718 // The program's definitions shall not be specified as inline.
8720 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8722 // Suppress the diagnostic if the function is __attribute__((used)), since
8723 // that forces an external definition to be emitted.
8724 if (D.getDeclSpec().isInlineSpecified() &&
8725 NewFD->isReplaceableGlobalAllocationFunction() &&
8726 !NewFD->hasAttr<UsedAttr>())
8727 Diag(D.getDeclSpec().getInlineSpecLoc(),
8728 diag::ext_operator_new_delete_declared_inline)
8729 << NewFD->getDeclName();
8731 // If the declarator is a template-id, translate the parser's template
8732 // argument list into our AST format.
8733 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8734 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8735 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8736 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8737 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8738 TemplateId->NumArgs);
8739 translateTemplateArguments(TemplateArgsPtr,
8742 HasExplicitTemplateArgs = true;
8744 if (NewFD->isInvalidDecl()) {
8745 HasExplicitTemplateArgs = false;
8746 } else if (FunctionTemplate) {
8747 // Function template with explicit template arguments.
8748 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8749 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8751 HasExplicitTemplateArgs = false;
8753 assert((isFunctionTemplateSpecialization ||
8754 D.getDeclSpec().isFriendSpecified()) &&
8755 "should have a 'template<>' for this decl");
8756 // "friend void foo<>(int);" is an implicit specialization decl.
8757 isFunctionTemplateSpecialization = true;
8759 } else if (isFriend && isFunctionTemplateSpecialization) {
8760 // This combination is only possible in a recovery case; the user
8761 // wrote something like:
8762 // template <> friend void foo(int);
8763 // which we're recovering from as if the user had written:
8764 // friend void foo<>(int);
8765 // Go ahead and fake up a template id.
8766 HasExplicitTemplateArgs = true;
8767 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8768 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8771 // We do not add HD attributes to specializations here because
8772 // they may have different constexpr-ness compared to their
8773 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8774 // may end up with different effective targets. Instead, a
8775 // specialization inherits its target attributes from its template
8776 // in the CheckFunctionTemplateSpecialization() call below.
8777 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8778 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8780 // If it's a friend (and only if it's a friend), it's possible
8781 // that either the specialized function type or the specialized
8782 // template is dependent, and therefore matching will fail. In
8783 // this case, don't check the specialization yet.
8784 bool InstantiationDependent = false;
8785 if (isFunctionTemplateSpecialization && isFriend &&
8786 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8787 TemplateSpecializationType::anyDependentTemplateArguments(
8789 InstantiationDependent))) {
8790 assert(HasExplicitTemplateArgs &&
8791 "friend function specialization without template args");
8792 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8794 NewFD->setInvalidDecl();
8795 } else if (isFunctionTemplateSpecialization) {
8796 if (CurContext->isDependentContext() && CurContext->isRecord()
8798 isDependentClassScopeExplicitSpecialization = true;
8799 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8800 diag::ext_function_specialization_in_class :
8801 diag::err_function_specialization_in_class)
8802 << NewFD->getDeclName();
8803 } else if (CheckFunctionTemplateSpecialization(NewFD,
8804 (HasExplicitTemplateArgs ? &TemplateArgs
8807 NewFD->setInvalidDecl();
8810 // A storage-class-specifier shall not be specified in an explicit
8811 // specialization (14.7.3)
8812 FunctionTemplateSpecializationInfo *Info =
8813 NewFD->getTemplateSpecializationInfo();
8814 if (Info && SC != SC_None) {
8815 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8816 Diag(NewFD->getLocation(),
8817 diag::err_explicit_specialization_inconsistent_storage_class)
8819 << FixItHint::CreateRemoval(
8820 D.getDeclSpec().getStorageClassSpecLoc());
8823 Diag(NewFD->getLocation(),
8824 diag::ext_explicit_specialization_storage_class)
8825 << FixItHint::CreateRemoval(
8826 D.getDeclSpec().getStorageClassSpecLoc());
8828 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8829 if (CheckMemberSpecialization(NewFD, Previous))
8830 NewFD->setInvalidDecl();
8833 // Perform semantic checking on the function declaration.
8834 if (!isDependentClassScopeExplicitSpecialization) {
8835 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8836 CheckMain(NewFD, D.getDeclSpec());
8838 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8839 CheckMSVCRTEntryPoint(NewFD);
8841 if (!NewFD->isInvalidDecl())
8842 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8843 isMemberSpecialization));
8844 else if (!Previous.empty())
8845 // Recover gracefully from an invalid redeclaration.
8846 D.setRedeclaration(true);
8849 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8850 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8851 "previous declaration set still overloaded");
8853 NamedDecl *PrincipalDecl = (FunctionTemplate
8854 ? cast<NamedDecl>(FunctionTemplate)
8857 if (isFriend && NewFD->getPreviousDecl()) {
8858 AccessSpecifier Access = AS_public;
8859 if (!NewFD->isInvalidDecl())
8860 Access = NewFD->getPreviousDecl()->getAccess();
8862 NewFD->setAccess(Access);
8863 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8866 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8867 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8868 PrincipalDecl->setNonMemberOperator();
8870 // If we have a function template, check the template parameter
8871 // list. This will check and merge default template arguments.
8872 if (FunctionTemplate) {
8873 FunctionTemplateDecl *PrevTemplate =
8874 FunctionTemplate->getPreviousDecl();
8875 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8876 PrevTemplate ? PrevTemplate->getTemplateParameters()
8878 D.getDeclSpec().isFriendSpecified()
8879 ? (D.isFunctionDefinition()
8880 ? TPC_FriendFunctionTemplateDefinition
8881 : TPC_FriendFunctionTemplate)
8882 : (D.getCXXScopeSpec().isSet() &&
8883 DC && DC->isRecord() &&
8884 DC->isDependentContext())
8885 ? TPC_ClassTemplateMember
8886 : TPC_FunctionTemplate);
8889 if (NewFD->isInvalidDecl()) {
8890 // Ignore all the rest of this.
8891 } else if (!D.isRedeclaration()) {
8892 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8894 // Fake up an access specifier if it's supposed to be a class member.
8895 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8896 NewFD->setAccess(AS_public);
8898 // Qualified decls generally require a previous declaration.
8899 if (D.getCXXScopeSpec().isSet()) {
8900 // ...with the major exception of templated-scope or
8901 // dependent-scope friend declarations.
8903 // TODO: we currently also suppress this check in dependent
8904 // contexts because (1) the parameter depth will be off when
8905 // matching friend templates and (2) we might actually be
8906 // selecting a friend based on a dependent factor. But there
8907 // are situations where these conditions don't apply and we
8908 // can actually do this check immediately.
8910 (TemplateParamLists.size() ||
8911 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8912 CurContext->isDependentContext())) {
8915 // The user tried to provide an out-of-line definition for a
8916 // function that is a member of a class or namespace, but there
8917 // was no such member function declared (C++ [class.mfct]p2,
8918 // C++ [namespace.memdef]p2). For example:
8924 // void X::f() { } // ill-formed
8926 // Complain about this problem, and attempt to suggest close
8927 // matches (e.g., those that differ only in cv-qualifiers and
8928 // whether the parameter types are references).
8930 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8931 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8932 AddToScope = ExtraArgs.AddToScope;
8937 // Unqualified local friend declarations are required to resolve
8939 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8940 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8941 *this, Previous, NewFD, ExtraArgs, true, S)) {
8942 AddToScope = ExtraArgs.AddToScope;
8946 } else if (!D.isFunctionDefinition() &&
8947 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8948 !isFriend && !isFunctionTemplateSpecialization &&
8949 !isMemberSpecialization) {
8950 // An out-of-line member function declaration must also be a
8951 // definition (C++ [class.mfct]p2).
8952 // Note that this is not the case for explicit specializations of
8953 // function templates or member functions of class templates, per
8954 // C++ [temp.expl.spec]p2. We also allow these declarations as an
8955 // extension for compatibility with old SWIG code which likes to
8957 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8958 << D.getCXXScopeSpec().getRange();
8962 ProcessPragmaWeak(S, NewFD);
8963 checkAttributesAfterMerging(*this, *NewFD);
8965 AddKnownFunctionAttributes(NewFD);
8967 if (NewFD->hasAttr<OverloadableAttr>() &&
8968 !NewFD->getType()->getAs<FunctionProtoType>()) {
8969 Diag(NewFD->getLocation(),
8970 diag::err_attribute_overloadable_no_prototype)
8973 // Turn this into a variadic function with no parameters.
8974 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8975 FunctionProtoType::ExtProtoInfo EPI(
8976 Context.getDefaultCallingConvention(true, false));
8977 EPI.Variadic = true;
8978 EPI.ExtInfo = FT->getExtInfo();
8980 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8984 // If there's a #pragma GCC visibility in scope, and this isn't a class
8985 // member, set the visibility of this function.
8986 if (!DC->isRecord() && NewFD->isExternallyVisible())
8987 AddPushedVisibilityAttribute(NewFD);
8989 // If there's a #pragma clang arc_cf_code_audited in scope, consider
8990 // marking the function.
8991 AddCFAuditedAttribute(NewFD);
8993 // If this is a function definition, check if we have to apply optnone due to
8995 if(D.isFunctionDefinition())
8996 AddRangeBasedOptnone(NewFD);
8998 // If this is the first declaration of an extern C variable, update
8999 // the map of such variables.
9000 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9001 isIncompleteDeclExternC(*this, NewFD))
9002 RegisterLocallyScopedExternCDecl(NewFD, S);
9004 // Set this FunctionDecl's range up to the right paren.
9005 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9007 if (D.isRedeclaration() && !Previous.empty()) {
9008 checkDLLAttributeRedeclaration(
9009 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9010 isMemberSpecialization || isFunctionTemplateSpecialization,
9011 D.isFunctionDefinition());
9014 if (getLangOpts().CUDA) {
9015 IdentifierInfo *II = NewFD->getIdentifier();
9016 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9017 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9018 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9019 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9021 Context.setcudaConfigureCallDecl(NewFD);
9024 // Variadic functions, other than a *declaration* of printf, are not allowed
9025 // in device-side CUDA code, unless someone passed
9026 // -fcuda-allow-variadic-functions.
9027 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9028 (NewFD->hasAttr<CUDADeviceAttr>() ||
9029 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9030 !(II && II->isStr("printf") && NewFD->isExternC() &&
9031 !D.isFunctionDefinition())) {
9032 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9036 MarkUnusedFileScopedDecl(NewFD);
9038 if (getLangOpts().CPlusPlus) {
9039 if (FunctionTemplate) {
9040 if (NewFD->isInvalidDecl())
9041 FunctionTemplate->setInvalidDecl();
9042 return FunctionTemplate;
9045 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9046 CompleteMemberSpecialization(NewFD, Previous);
9049 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9050 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9051 if ((getLangOpts().OpenCLVersion >= 120)
9052 && (SC == SC_Static)) {
9053 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9057 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9058 if (!NewFD->getReturnType()->isVoidType()) {
9059 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9060 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9061 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9066 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9067 for (auto Param : NewFD->parameters())
9068 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9070 for (const ParmVarDecl *Param : NewFD->parameters()) {
9071 QualType PT = Param->getType();
9073 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9075 if (getLangOpts().OpenCLVersion >= 200) {
9076 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9077 QualType ElemTy = PipeTy->getElementType();
9078 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9079 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9086 // Here we have an function template explicit specialization at class scope.
9087 // The actually specialization will be postponed to template instatiation
9088 // time via the ClassScopeFunctionSpecializationDecl node.
9089 if (isDependentClassScopeExplicitSpecialization) {
9090 ClassScopeFunctionSpecializationDecl *NewSpec =
9091 ClassScopeFunctionSpecializationDecl::Create(
9092 Context, CurContext, SourceLocation(),
9093 cast<CXXMethodDecl>(NewFD),
9094 HasExplicitTemplateArgs, TemplateArgs);
9095 CurContext->addDecl(NewSpec);
9102 /// \brief Checks if the new declaration declared in dependent context must be
9103 /// put in the same redeclaration chain as the specified declaration.
9105 /// \param D Declaration that is checked.
9106 /// \param PrevDecl Previous declaration found with proper lookup method for the
9107 /// same declaration name.
9108 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9111 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9112 // Any declarations should be put into redeclaration chains except for
9113 // friend declaration in a dependent context that names a function in
9116 // This allows to compile code like:
9119 // template<typename T> class C1 { friend void func() { } };
9120 // template<typename T> class C2 { friend void func() { } };
9122 // This code snippet is a valid code unless both templates are instantiated.
9123 return !(D->getLexicalDeclContext()->isDependentContext() &&
9124 D->getDeclContext()->isFileContext() &&
9125 D->getFriendObjectKind() != Decl::FOK_None);
9128 /// \brief Perform semantic checking of a new function declaration.
9130 /// Performs semantic analysis of the new function declaration
9131 /// NewFD. This routine performs all semantic checking that does not
9132 /// require the actual declarator involved in the declaration, and is
9133 /// used both for the declaration of functions as they are parsed
9134 /// (called via ActOnDeclarator) and for the declaration of functions
9135 /// that have been instantiated via C++ template instantiation (called
9136 /// via InstantiateDecl).
9138 /// \param IsMemberSpecialization whether this new function declaration is
9139 /// a member specialization (that replaces any definition provided by the
9140 /// previous declaration).
9142 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9144 /// \returns true if the function declaration is a redeclaration.
9145 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9146 LookupResult &Previous,
9147 bool IsMemberSpecialization) {
9148 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9149 "Variably modified return types are not handled here");
9151 // Determine whether the type of this function should be merged with
9152 // a previous visible declaration. This never happens for functions in C++,
9153 // and always happens in C if the previous declaration was visible.
9154 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9155 !Previous.isShadowed();
9157 bool Redeclaration = false;
9158 NamedDecl *OldDecl = nullptr;
9160 // Merge or overload the declaration with an existing declaration of
9161 // the same name, if appropriate.
9162 if (!Previous.empty()) {
9163 // Determine whether NewFD is an overload of PrevDecl or
9164 // a declaration that requires merging. If it's an overload,
9165 // there's no more work to do here; we'll just add the new
9166 // function to the scope.
9167 if (!AllowOverloadingOfFunction(Previous, Context)) {
9168 NamedDecl *Candidate = Previous.getRepresentativeDecl();
9169 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9170 Redeclaration = true;
9171 OldDecl = Candidate;
9174 switch (CheckOverload(S, NewFD, Previous, OldDecl,
9175 /*NewIsUsingDecl*/ false)) {
9177 Redeclaration = true;
9180 case Ovl_NonFunction:
9181 Redeclaration = true;
9185 Redeclaration = false;
9189 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9190 // If a function name is overloadable in C, then every function
9191 // with that name must be marked "overloadable".
9192 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9193 << Redeclaration << NewFD;
9194 NamedDecl *OverloadedDecl =
9195 Redeclaration ? OldDecl : Previous.getRepresentativeDecl();
9196 Diag(OverloadedDecl->getLocation(),
9197 diag::note_attribute_overloadable_prev_overload);
9198 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9203 // Check for a previous extern "C" declaration with this name.
9204 if (!Redeclaration &&
9205 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9206 if (!Previous.empty()) {
9207 // This is an extern "C" declaration with the same name as a previous
9208 // declaration, and thus redeclares that entity...
9209 Redeclaration = true;
9210 OldDecl = Previous.getFoundDecl();
9211 MergeTypeWithPrevious = false;
9213 // ... except in the presence of __attribute__((overloadable)).
9214 if (OldDecl->hasAttr<OverloadableAttr>()) {
9215 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
9216 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
9217 << Redeclaration << NewFD;
9218 Diag(Previous.getFoundDecl()->getLocation(),
9219 diag::note_attribute_overloadable_prev_overload);
9220 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9222 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9223 Redeclaration = false;
9230 // C++11 [dcl.constexpr]p8:
9231 // A constexpr specifier for a non-static member function that is not
9232 // a constructor declares that member function to be const.
9234 // This needs to be delayed until we know whether this is an out-of-line
9235 // definition of a static member function.
9237 // This rule is not present in C++1y, so we produce a backwards
9238 // compatibility warning whenever it happens in C++11.
9239 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9240 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9241 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9242 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9243 CXXMethodDecl *OldMD = nullptr;
9245 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9246 if (!OldMD || !OldMD->isStatic()) {
9247 const FunctionProtoType *FPT =
9248 MD->getType()->castAs<FunctionProtoType>();
9249 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9250 EPI.TypeQuals |= Qualifiers::Const;
9251 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9252 FPT->getParamTypes(), EPI));
9254 // Warn that we did this, if we're not performing template instantiation.
9255 // In that case, we'll have warned already when the template was defined.
9256 if (!inTemplateInstantiation()) {
9257 SourceLocation AddConstLoc;
9258 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9259 .IgnoreParens().getAs<FunctionTypeLoc>())
9260 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9262 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9263 << FixItHint::CreateInsertion(AddConstLoc, " const");
9268 if (Redeclaration) {
9269 // NewFD and OldDecl represent declarations that need to be
9271 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9272 NewFD->setInvalidDecl();
9273 return Redeclaration;
9277 Previous.addDecl(OldDecl);
9279 if (FunctionTemplateDecl *OldTemplateDecl
9280 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9281 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9282 FunctionTemplateDecl *NewTemplateDecl
9283 = NewFD->getDescribedFunctionTemplate();
9284 assert(NewTemplateDecl && "Template/non-template mismatch");
9285 if (CXXMethodDecl *Method
9286 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9287 Method->setAccess(OldTemplateDecl->getAccess());
9288 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9291 // If this is an explicit specialization of a member that is a function
9292 // template, mark it as a member specialization.
9293 if (IsMemberSpecialization &&
9294 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9295 NewTemplateDecl->setMemberSpecialization();
9296 assert(OldTemplateDecl->isMemberSpecialization());
9297 // Explicit specializations of a member template do not inherit deleted
9298 // status from the parent member template that they are specializing.
9299 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9300 FunctionDecl *const OldTemplatedDecl =
9301 OldTemplateDecl->getTemplatedDecl();
9302 // FIXME: This assert will not hold in the presence of modules.
9303 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9304 // FIXME: We need an update record for this AST mutation.
9305 OldTemplatedDecl->setDeletedAsWritten(false);
9310 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9311 // This needs to happen first so that 'inline' propagates.
9312 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9313 if (isa<CXXMethodDecl>(NewFD))
9314 NewFD->setAccess(OldDecl->getAccess());
9319 // Semantic checking for this function declaration (in isolation).
9321 if (getLangOpts().CPlusPlus) {
9322 // C++-specific checks.
9323 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9324 CheckConstructor(Constructor);
9325 } else if (CXXDestructorDecl *Destructor =
9326 dyn_cast<CXXDestructorDecl>(NewFD)) {
9327 CXXRecordDecl *Record = Destructor->getParent();
9328 QualType ClassType = Context.getTypeDeclType(Record);
9330 // FIXME: Shouldn't we be able to perform this check even when the class
9331 // type is dependent? Both gcc and edg can handle that.
9332 if (!ClassType->isDependentType()) {
9333 DeclarationName Name
9334 = Context.DeclarationNames.getCXXDestructorName(
9335 Context.getCanonicalType(ClassType));
9336 if (NewFD->getDeclName() != Name) {
9337 Diag(NewFD->getLocation(), diag::err_destructor_name);
9338 NewFD->setInvalidDecl();
9339 return Redeclaration;
9342 } else if (CXXConversionDecl *Conversion
9343 = dyn_cast<CXXConversionDecl>(NewFD)) {
9344 ActOnConversionDeclarator(Conversion);
9345 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9346 if (auto *TD = Guide->getDescribedFunctionTemplate())
9347 CheckDeductionGuideTemplate(TD);
9349 // A deduction guide is not on the list of entities that can be
9350 // explicitly specialized.
9351 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9352 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9353 << /*explicit specialization*/ 1;
9356 // Find any virtual functions that this function overrides.
9357 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9358 if (!Method->isFunctionTemplateSpecialization() &&
9359 !Method->getDescribedFunctionTemplate() &&
9360 Method->isCanonicalDecl()) {
9361 if (AddOverriddenMethods(Method->getParent(), Method)) {
9362 // If the function was marked as "static", we have a problem.
9363 if (NewFD->getStorageClass() == SC_Static) {
9364 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9369 if (Method->isStatic())
9370 checkThisInStaticMemberFunctionType(Method);
9373 // Extra checking for C++ overloaded operators (C++ [over.oper]).
9374 if (NewFD->isOverloadedOperator() &&
9375 CheckOverloadedOperatorDeclaration(NewFD)) {
9376 NewFD->setInvalidDecl();
9377 return Redeclaration;
9380 // Extra checking for C++0x literal operators (C++0x [over.literal]).
9381 if (NewFD->getLiteralIdentifier() &&
9382 CheckLiteralOperatorDeclaration(NewFD)) {
9383 NewFD->setInvalidDecl();
9384 return Redeclaration;
9387 // In C++, check default arguments now that we have merged decls. Unless
9388 // the lexical context is the class, because in this case this is done
9389 // during delayed parsing anyway.
9390 if (!CurContext->isRecord())
9391 CheckCXXDefaultArguments(NewFD);
9393 // If this function declares a builtin function, check the type of this
9394 // declaration against the expected type for the builtin.
9395 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9396 ASTContext::GetBuiltinTypeError Error;
9397 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9398 QualType T = Context.GetBuiltinType(BuiltinID, Error);
9399 // If the type of the builtin differs only in its exception
9400 // specification, that's OK.
9401 // FIXME: If the types do differ in this way, it would be better to
9402 // retain the 'noexcept' form of the type.
9404 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9406 // The type of this function differs from the type of the builtin,
9407 // so forget about the builtin entirely.
9408 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9411 // If this function is declared as being extern "C", then check to see if
9412 // the function returns a UDT (class, struct, or union type) that is not C
9413 // compatible, and if it does, warn the user.
9414 // But, issue any diagnostic on the first declaration only.
9415 if (Previous.empty() && NewFD->isExternC()) {
9416 QualType R = NewFD->getReturnType();
9417 if (R->isIncompleteType() && !R->isVoidType())
9418 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9420 else if (!R.isPODType(Context) && !R->isVoidType() &&
9421 !R->isObjCObjectPointerType())
9422 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9425 // C++1z [dcl.fct]p6:
9426 // [...] whether the function has a non-throwing exception-specification
9427 // [is] part of the function type
9429 // This results in an ABI break between C++14 and C++17 for functions whose
9430 // declared type includes an exception-specification in a parameter or
9431 // return type. (Exception specifications on the function itself are OK in
9432 // most cases, and exception specifications are not permitted in most other
9433 // contexts where they could make it into a mangling.)
9434 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9435 auto HasNoexcept = [&](QualType T) -> bool {
9436 // Strip off declarator chunks that could be between us and a function
9437 // type. We don't need to look far, exception specifications are very
9438 // restricted prior to C++17.
9439 if (auto *RT = T->getAs<ReferenceType>())
9440 T = RT->getPointeeType();
9441 else if (T->isAnyPointerType())
9442 T = T->getPointeeType();
9443 else if (auto *MPT = T->getAs<MemberPointerType>())
9444 T = MPT->getPointeeType();
9445 if (auto *FPT = T->getAs<FunctionProtoType>())
9446 if (FPT->isNothrow(Context))
9451 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9452 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9453 for (QualType T : FPT->param_types())
9454 AnyNoexcept |= HasNoexcept(T);
9456 Diag(NewFD->getLocation(),
9457 diag::warn_cxx1z_compat_exception_spec_in_signature)
9461 if (!Redeclaration && LangOpts.CUDA)
9462 checkCUDATargetOverload(NewFD, Previous);
9464 return Redeclaration;
9467 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9468 // C++11 [basic.start.main]p3:
9469 // A program that [...] declares main to be inline, static or
9470 // constexpr is ill-formed.
9471 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
9472 // appear in a declaration of main.
9473 // static main is not an error under C99, but we should warn about it.
9474 // We accept _Noreturn main as an extension.
9475 if (FD->getStorageClass() == SC_Static)
9476 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9477 ? diag::err_static_main : diag::warn_static_main)
9478 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9479 if (FD->isInlineSpecified())
9480 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9481 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9482 if (DS.isNoreturnSpecified()) {
9483 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9484 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9485 Diag(NoreturnLoc, diag::ext_noreturn_main);
9486 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9487 << FixItHint::CreateRemoval(NoreturnRange);
9489 if (FD->isConstexpr()) {
9490 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9491 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9492 FD->setConstexpr(false);
9495 if (getLangOpts().OpenCL) {
9496 Diag(FD->getLocation(), diag::err_opencl_no_main)
9497 << FD->hasAttr<OpenCLKernelAttr>();
9498 FD->setInvalidDecl();
9502 QualType T = FD->getType();
9503 assert(T->isFunctionType() && "function decl is not of function type");
9504 const FunctionType* FT = T->castAs<FunctionType>();
9506 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9507 // In C with GNU extensions we allow main() to have non-integer return
9508 // type, but we should warn about the extension, and we disable the
9509 // implicit-return-zero rule.
9511 // GCC in C mode accepts qualified 'int'.
9512 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9513 FD->setHasImplicitReturnZero(true);
9515 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9516 SourceRange RTRange = FD->getReturnTypeSourceRange();
9517 if (RTRange.isValid())
9518 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9519 << FixItHint::CreateReplacement(RTRange, "int");
9522 // In C and C++, main magically returns 0 if you fall off the end;
9523 // set the flag which tells us that.
9524 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9526 // All the standards say that main() should return 'int'.
9527 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9528 FD->setHasImplicitReturnZero(true);
9530 // Otherwise, this is just a flat-out error.
9531 SourceRange RTRange = FD->getReturnTypeSourceRange();
9532 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9533 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9535 FD->setInvalidDecl(true);
9539 // Treat protoless main() as nullary.
9540 if (isa<FunctionNoProtoType>(FT)) return;
9542 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9543 unsigned nparams = FTP->getNumParams();
9544 assert(FD->getNumParams() == nparams);
9546 bool HasExtraParameters = (nparams > 3);
9548 if (FTP->isVariadic()) {
9549 Diag(FD->getLocation(), diag::ext_variadic_main);
9550 // FIXME: if we had information about the location of the ellipsis, we
9551 // could add a FixIt hint to remove it as a parameter.
9554 // Darwin passes an undocumented fourth argument of type char**. If
9555 // other platforms start sprouting these, the logic below will start
9557 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9558 HasExtraParameters = false;
9560 if (HasExtraParameters) {
9561 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9562 FD->setInvalidDecl(true);
9566 // FIXME: a lot of the following diagnostics would be improved
9567 // if we had some location information about types.
9570 Context.getPointerType(Context.getPointerType(Context.CharTy));
9571 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9573 for (unsigned i = 0; i < nparams; ++i) {
9574 QualType AT = FTP->getParamType(i);
9576 bool mismatch = true;
9578 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9580 else if (Expected[i] == CharPP) {
9581 // As an extension, the following forms are okay:
9583 // char const * const *
9586 QualifierCollector qs;
9587 const PointerType* PT;
9588 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9589 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9590 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9593 mismatch = !qs.empty();
9598 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9599 // TODO: suggest replacing given type with expected type
9600 FD->setInvalidDecl(true);
9604 if (nparams == 1 && !FD->isInvalidDecl()) {
9605 Diag(FD->getLocation(), diag::warn_main_one_arg);
9608 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9609 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9610 FD->setInvalidDecl();
9614 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9615 QualType T = FD->getType();
9616 assert(T->isFunctionType() && "function decl is not of function type");
9617 const FunctionType *FT = T->castAs<FunctionType>();
9619 // Set an implicit return of 'zero' if the function can return some integral,
9620 // enumeration, pointer or nullptr type.
9621 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9622 FT->getReturnType()->isAnyPointerType() ||
9623 FT->getReturnType()->isNullPtrType())
9624 // DllMain is exempt because a return value of zero means it failed.
9625 if (FD->getName() != "DllMain")
9626 FD->setHasImplicitReturnZero(true);
9628 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9629 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9630 FD->setInvalidDecl();
9634 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9635 // FIXME: Need strict checking. In C89, we need to check for
9636 // any assignment, increment, decrement, function-calls, or
9637 // commas outside of a sizeof. In C99, it's the same list,
9638 // except that the aforementioned are allowed in unevaluated
9639 // expressions. Everything else falls under the
9640 // "may accept other forms of constant expressions" exception.
9641 // (We never end up here for C++, so the constant expression
9642 // rules there don't matter.)
9643 const Expr *Culprit;
9644 if (Init->isConstantInitializer(Context, false, &Culprit))
9646 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9647 << Culprit->getSourceRange();
9652 // Visits an initialization expression to see if OrigDecl is evaluated in
9653 // its own initialization and throws a warning if it does.
9654 class SelfReferenceChecker
9655 : public EvaluatedExprVisitor<SelfReferenceChecker> {
9660 bool isReferenceType;
9663 llvm::SmallVector<unsigned, 4> InitFieldIndex;
9666 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9668 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9669 S(S), OrigDecl(OrigDecl) {
9671 isRecordType = false;
9672 isReferenceType = false;
9674 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9675 isPODType = VD->getType().isPODType(S.Context);
9676 isRecordType = VD->getType()->isRecordType();
9677 isReferenceType = VD->getType()->isReferenceType();
9681 // For most expressions, just call the visitor. For initializer lists,
9682 // track the index of the field being initialized since fields are
9683 // initialized in order allowing use of previously initialized fields.
9684 void CheckExpr(Expr *E) {
9685 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9691 // Track and increment the index here.
9693 InitFieldIndex.push_back(0);
9694 for (auto Child : InitList->children()) {
9695 CheckExpr(cast<Expr>(Child));
9696 ++InitFieldIndex.back();
9698 InitFieldIndex.pop_back();
9701 // Returns true if MemberExpr is checked and no further checking is needed.
9702 // Returns false if additional checking is required.
9703 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9704 llvm::SmallVector<FieldDecl*, 4> Fields;
9706 bool ReferenceField = false;
9708 // Get the field memebers used.
9709 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9710 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9713 Fields.push_back(FD);
9714 if (FD->getType()->isReferenceType())
9715 ReferenceField = true;
9716 Base = ME->getBase()->IgnoreParenImpCasts();
9719 // Keep checking only if the base Decl is the same.
9720 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9721 if (!DRE || DRE->getDecl() != OrigDecl)
9724 // A reference field can be bound to an unininitialized field.
9725 if (CheckReference && !ReferenceField)
9728 // Convert FieldDecls to their index number.
9729 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9730 for (const FieldDecl *I : llvm::reverse(Fields))
9731 UsedFieldIndex.push_back(I->getFieldIndex());
9733 // See if a warning is needed by checking the first difference in index
9734 // numbers. If field being used has index less than the field being
9735 // initialized, then the use is safe.
9736 for (auto UsedIter = UsedFieldIndex.begin(),
9737 UsedEnd = UsedFieldIndex.end(),
9738 OrigIter = InitFieldIndex.begin(),
9739 OrigEnd = InitFieldIndex.end();
9740 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9741 if (*UsedIter < *OrigIter)
9743 if (*UsedIter > *OrigIter)
9747 // TODO: Add a different warning which will print the field names.
9748 HandleDeclRefExpr(DRE);
9752 // For most expressions, the cast is directly above the DeclRefExpr.
9753 // For conditional operators, the cast can be outside the conditional
9754 // operator if both expressions are DeclRefExpr's.
9755 void HandleValue(Expr *E) {
9756 E = E->IgnoreParens();
9757 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9758 HandleDeclRefExpr(DRE);
9762 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9763 Visit(CO->getCond());
9764 HandleValue(CO->getTrueExpr());
9765 HandleValue(CO->getFalseExpr());
9769 if (BinaryConditionalOperator *BCO =
9770 dyn_cast<BinaryConditionalOperator>(E)) {
9771 Visit(BCO->getCond());
9772 HandleValue(BCO->getFalseExpr());
9776 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9777 HandleValue(OVE->getSourceExpr());
9781 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9782 if (BO->getOpcode() == BO_Comma) {
9783 Visit(BO->getLHS());
9784 HandleValue(BO->getRHS());
9789 if (isa<MemberExpr>(E)) {
9791 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9792 false /*CheckReference*/))
9796 Expr *Base = E->IgnoreParenImpCasts();
9797 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9798 // Check for static member variables and don't warn on them.
9799 if (!isa<FieldDecl>(ME->getMemberDecl()))
9801 Base = ME->getBase()->IgnoreParenImpCasts();
9803 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9804 HandleDeclRefExpr(DRE);
9811 // Reference types not handled in HandleValue are handled here since all
9812 // uses of references are bad, not just r-value uses.
9813 void VisitDeclRefExpr(DeclRefExpr *E) {
9814 if (isReferenceType)
9815 HandleDeclRefExpr(E);
9818 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9819 if (E->getCastKind() == CK_LValueToRValue) {
9820 HandleValue(E->getSubExpr());
9824 Inherited::VisitImplicitCastExpr(E);
9827 void VisitMemberExpr(MemberExpr *E) {
9829 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9833 // Don't warn on arrays since they can be treated as pointers.
9834 if (E->getType()->canDecayToPointerType()) return;
9836 // Warn when a non-static method call is followed by non-static member
9837 // field accesses, which is followed by a DeclRefExpr.
9838 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9839 bool Warn = (MD && !MD->isStatic());
9840 Expr *Base = E->getBase()->IgnoreParenImpCasts();
9841 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9842 if (!isa<FieldDecl>(ME->getMemberDecl()))
9844 Base = ME->getBase()->IgnoreParenImpCasts();
9847 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9849 HandleDeclRefExpr(DRE);
9853 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9854 // Visit that expression.
9858 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9859 Expr *Callee = E->getCallee();
9861 if (isa<UnresolvedLookupExpr>(Callee))
9862 return Inherited::VisitCXXOperatorCallExpr(E);
9865 for (auto Arg: E->arguments())
9866 HandleValue(Arg->IgnoreParenImpCasts());
9869 void VisitUnaryOperator(UnaryOperator *E) {
9870 // For POD record types, addresses of its own members are well-defined.
9871 if (E->getOpcode() == UO_AddrOf && isRecordType &&
9872 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9874 HandleValue(E->getSubExpr());
9878 if (E->isIncrementDecrementOp()) {
9879 HandleValue(E->getSubExpr());
9883 Inherited::VisitUnaryOperator(E);
9886 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9888 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9889 if (E->getConstructor()->isCopyConstructor()) {
9890 Expr *ArgExpr = E->getArg(0);
9891 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9892 if (ILE->getNumInits() == 1)
9893 ArgExpr = ILE->getInit(0);
9894 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9895 if (ICE->getCastKind() == CK_NoOp)
9896 ArgExpr = ICE->getSubExpr();
9897 HandleValue(ArgExpr);
9900 Inherited::VisitCXXConstructExpr(E);
9903 void VisitCallExpr(CallExpr *E) {
9904 // Treat std::move as a use.
9905 if (E->getNumArgs() == 1) {
9906 if (FunctionDecl *FD = E->getDirectCallee()) {
9907 if (FD->isInStdNamespace() && FD->getIdentifier() &&
9908 FD->getIdentifier()->isStr("move")) {
9909 HandleValue(E->getArg(0));
9915 Inherited::VisitCallExpr(E);
9918 void VisitBinaryOperator(BinaryOperator *E) {
9919 if (E->isCompoundAssignmentOp()) {
9920 HandleValue(E->getLHS());
9925 Inherited::VisitBinaryOperator(E);
9928 // A custom visitor for BinaryConditionalOperator is needed because the
9929 // regular visitor would check the condition and true expression separately
9930 // but both point to the same place giving duplicate diagnostics.
9931 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9932 Visit(E->getCond());
9933 Visit(E->getFalseExpr());
9936 void HandleDeclRefExpr(DeclRefExpr *DRE) {
9937 Decl* ReferenceDecl = DRE->getDecl();
9938 if (OrigDecl != ReferenceDecl) return;
9940 if (isReferenceType) {
9941 diag = diag::warn_uninit_self_reference_in_reference_init;
9942 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9943 diag = diag::warn_static_self_reference_in_init;
9944 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9945 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9946 DRE->getDecl()->getType()->isRecordType()) {
9947 diag = diag::warn_uninit_self_reference_in_init;
9949 // Local variables will be handled by the CFG analysis.
9953 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9955 << DRE->getNameInfo().getName()
9956 << OrigDecl->getLocation()
9957 << DRE->getSourceRange());
9961 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9962 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9964 // Parameters arguments are occassionially constructed with itself,
9965 // for instance, in recursive functions. Skip them.
9966 if (isa<ParmVarDecl>(OrigDecl))
9969 E = E->IgnoreParens();
9971 // Skip checking T a = a where T is not a record or reference type.
9972 // Doing so is a way to silence uninitialized warnings.
9973 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9974 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9975 if (ICE->getCastKind() == CK_LValueToRValue)
9976 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9977 if (DRE->getDecl() == OrigDecl)
9980 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9982 } // end anonymous namespace
9985 // Simple wrapper to add the name of a variable or (if no variable is
9986 // available) a DeclarationName into a diagnostic.
9987 struct VarDeclOrName {
9989 DeclarationName Name;
9991 friend const Sema::SemaDiagnosticBuilder &
9992 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9993 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9996 } // end anonymous namespace
9998 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9999 DeclarationName Name, QualType Type,
10000 TypeSourceInfo *TSI,
10001 SourceRange Range, bool DirectInit,
10003 bool IsInitCapture = !VDecl;
10004 assert((!VDecl || !VDecl->isInitCapture()) &&
10005 "init captures are expected to be deduced prior to initialization");
10007 VarDeclOrName VN{VDecl, Name};
10009 DeducedType *Deduced = Type->getContainedDeducedType();
10010 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10012 // C++11 [dcl.spec.auto]p3
10014 assert(VDecl && "no init for init capture deduction?");
10015 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10016 << VDecl->getDeclName() << Type;
10020 ArrayRef<Expr*> DeduceInits = Init;
10022 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10023 DeduceInits = PL->exprs();
10026 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10027 assert(VDecl && "non-auto type for init capture deduction?");
10028 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10029 InitializationKind Kind = InitializationKind::CreateForInit(
10030 VDecl->getLocation(), DirectInit, Init);
10031 // FIXME: Initialization should not be taking a mutable list of inits.
10032 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10033 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10038 if (auto *IL = dyn_cast<InitListExpr>(Init))
10039 DeduceInits = IL->inits();
10042 // Deduction only works if we have exactly one source expression.
10043 if (DeduceInits.empty()) {
10044 // It isn't possible to write this directly, but it is possible to
10045 // end up in this situation with "auto x(some_pack...);"
10046 Diag(Init->getLocStart(), IsInitCapture
10047 ? diag::err_init_capture_no_expression
10048 : diag::err_auto_var_init_no_expression)
10049 << VN << Type << Range;
10053 if (DeduceInits.size() > 1) {
10054 Diag(DeduceInits[1]->getLocStart(),
10055 IsInitCapture ? diag::err_init_capture_multiple_expressions
10056 : diag::err_auto_var_init_multiple_expressions)
10057 << VN << Type << Range;
10061 Expr *DeduceInit = DeduceInits[0];
10062 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10063 Diag(Init->getLocStart(), IsInitCapture
10064 ? diag::err_init_capture_paren_braces
10065 : diag::err_auto_var_init_paren_braces)
10066 << isa<InitListExpr>(Init) << VN << Type << Range;
10070 // Expressions default to 'id' when we're in a debugger.
10071 bool DefaultedAnyToId = false;
10072 if (getLangOpts().DebuggerCastResultToId &&
10073 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10074 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10075 if (Result.isInvalid()) {
10078 Init = Result.get();
10079 DefaultedAnyToId = true;
10082 // C++ [dcl.decomp]p1:
10083 // If the assignment-expression [...] has array type A and no ref-qualifier
10084 // is present, e has type cv A
10085 if (VDecl && isa<DecompositionDecl>(VDecl) &&
10086 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10087 DeduceInit->getType()->isConstantArrayType())
10088 return Context.getQualifiedType(DeduceInit->getType(),
10089 Type.getQualifiers());
10091 QualType DeducedType;
10092 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10093 if (!IsInitCapture)
10094 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10095 else if (isa<InitListExpr>(Init))
10096 Diag(Range.getBegin(),
10097 diag::err_init_capture_deduction_failure_from_init_list)
10099 << (DeduceInit->getType().isNull() ? TSI->getType()
10100 : DeduceInit->getType())
10101 << DeduceInit->getSourceRange();
10103 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10104 << VN << TSI->getType()
10105 << (DeduceInit->getType().isNull() ? TSI->getType()
10106 : DeduceInit->getType())
10107 << DeduceInit->getSourceRange();
10110 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10111 // 'id' instead of a specific object type prevents most of our usual
10113 // We only want to warn outside of template instantiations, though:
10114 // inside a template, the 'id' could have come from a parameter.
10115 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10116 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10117 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10118 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10121 return DeducedType;
10124 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10126 QualType DeducedType = deduceVarTypeFromInitializer(
10127 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10128 VDecl->getSourceRange(), DirectInit, Init);
10129 if (DeducedType.isNull()) {
10130 VDecl->setInvalidDecl();
10134 VDecl->setType(DeducedType);
10135 assert(VDecl->isLinkageValid());
10137 // In ARC, infer lifetime.
10138 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10139 VDecl->setInvalidDecl();
10141 // If this is a redeclaration, check that the type we just deduced matches
10142 // the previously declared type.
10143 if (VarDecl *Old = VDecl->getPreviousDecl()) {
10144 // We never need to merge the type, because we cannot form an incomplete
10145 // array of auto, nor deduce such a type.
10146 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10149 // Check the deduced type is valid for a variable declaration.
10150 CheckVariableDeclarationType(VDecl);
10151 return VDecl->isInvalidDecl();
10154 /// AddInitializerToDecl - Adds the initializer Init to the
10155 /// declaration dcl. If DirectInit is true, this is C++ direct
10156 /// initialization rather than copy initialization.
10157 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10158 // If there is no declaration, there was an error parsing it. Just ignore
10159 // the initializer.
10160 if (!RealDecl || RealDecl->isInvalidDecl()) {
10161 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10165 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10166 // Pure-specifiers are handled in ActOnPureSpecifier.
10167 Diag(Method->getLocation(), diag::err_member_function_initialization)
10168 << Method->getDeclName() << Init->getSourceRange();
10169 Method->setInvalidDecl();
10173 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10175 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10176 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10177 RealDecl->setInvalidDecl();
10181 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10182 if (VDecl->getType()->isUndeducedType()) {
10183 // Attempt typo correction early so that the type of the init expression can
10184 // be deduced based on the chosen correction if the original init contains a
10186 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10187 if (!Res.isUsable()) {
10188 RealDecl->setInvalidDecl();
10193 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10197 // dllimport cannot be used on variable definitions.
10198 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10199 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10200 VDecl->setInvalidDecl();
10204 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10205 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10206 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10207 VDecl->setInvalidDecl();
10211 if (!VDecl->getType()->isDependentType()) {
10212 // A definition must end up with a complete type, which means it must be
10213 // complete with the restriction that an array type might be completed by
10214 // the initializer; note that later code assumes this restriction.
10215 QualType BaseDeclType = VDecl->getType();
10216 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10217 BaseDeclType = Array->getElementType();
10218 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10219 diag::err_typecheck_decl_incomplete_type)) {
10220 RealDecl->setInvalidDecl();
10224 // The variable can not have an abstract class type.
10225 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10226 diag::err_abstract_type_in_decl,
10227 AbstractVariableType))
10228 VDecl->setInvalidDecl();
10231 // If adding the initializer will turn this declaration into a definition,
10232 // and we already have a definition for this variable, diagnose or otherwise
10233 // handle the situation.
10235 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10236 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10237 !VDecl->isThisDeclarationADemotedDefinition() &&
10238 checkVarDeclRedefinition(Def, VDecl))
10241 if (getLangOpts().CPlusPlus) {
10242 // C++ [class.static.data]p4
10243 // If a static data member is of const integral or const
10244 // enumeration type, its declaration in the class definition can
10245 // specify a constant-initializer which shall be an integral
10246 // constant expression (5.19). In that case, the member can appear
10247 // in integral constant expressions. The member shall still be
10248 // defined in a namespace scope if it is used in the program and the
10249 // namespace scope definition shall not contain an initializer.
10251 // We already performed a redefinition check above, but for static
10252 // data members we also need to check whether there was an in-class
10253 // declaration with an initializer.
10254 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10255 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10256 << VDecl->getDeclName();
10257 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10258 diag::note_previous_initializer)
10263 if (VDecl->hasLocalStorage())
10264 getCurFunction()->setHasBranchProtectedScope();
10266 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10267 VDecl->setInvalidDecl();
10272 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10273 // a kernel function cannot be initialized."
10274 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10275 Diag(VDecl->getLocation(), diag::err_local_cant_init);
10276 VDecl->setInvalidDecl();
10280 // Get the decls type and save a reference for later, since
10281 // CheckInitializerTypes may change it.
10282 QualType DclT = VDecl->getType(), SavT = DclT;
10284 // Expressions default to 'id' when we're in a debugger
10285 // and we are assigning it to a variable of Objective-C pointer type.
10286 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10287 Init->getType() == Context.UnknownAnyTy) {
10288 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10289 if (Result.isInvalid()) {
10290 VDecl->setInvalidDecl();
10293 Init = Result.get();
10296 // Perform the initialization.
10297 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10298 if (!VDecl->isInvalidDecl()) {
10299 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10300 InitializationKind Kind = InitializationKind::CreateForInit(
10301 VDecl->getLocation(), DirectInit, Init);
10303 MultiExprArg Args = Init;
10305 Args = MultiExprArg(CXXDirectInit->getExprs(),
10306 CXXDirectInit->getNumExprs());
10308 // Try to correct any TypoExprs in the initialization arguments.
10309 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10310 ExprResult Res = CorrectDelayedTyposInExpr(
10311 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10312 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10313 return Init.Failed() ? ExprError() : E;
10315 if (Res.isInvalid()) {
10316 VDecl->setInvalidDecl();
10317 } else if (Res.get() != Args[Idx]) {
10318 Args[Idx] = Res.get();
10321 if (VDecl->isInvalidDecl())
10324 InitializationSequence InitSeq(*this, Entity, Kind, Args,
10325 /*TopLevelOfInitList=*/false,
10326 /*TreatUnavailableAsInvalid=*/false);
10327 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10328 if (Result.isInvalid()) {
10329 VDecl->setInvalidDecl();
10333 Init = Result.getAs<Expr>();
10336 // Check for self-references within variable initializers.
10337 // Variables declared within a function/method body (except for references)
10338 // are handled by a dataflow analysis.
10339 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10340 VDecl->getType()->isReferenceType()) {
10341 CheckSelfReference(*this, RealDecl, Init, DirectInit);
10344 // If the type changed, it means we had an incomplete type that was
10345 // completed by the initializer. For example:
10346 // int ary[] = { 1, 3, 5 };
10347 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10348 if (!VDecl->isInvalidDecl() && (DclT != SavT))
10349 VDecl->setType(DclT);
10351 if (!VDecl->isInvalidDecl()) {
10352 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10354 if (VDecl->hasAttr<BlocksAttr>())
10355 checkRetainCycles(VDecl, Init);
10357 // It is safe to assign a weak reference into a strong variable.
10358 // Although this code can still have problems:
10359 // id x = self.weakProp;
10360 // id y = self.weakProp;
10361 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10362 // paths through the function. This should be revisited if
10363 // -Wrepeated-use-of-weak is made flow-sensitive.
10364 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10365 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10366 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10367 Init->getLocStart()))
10368 getCurFunction()->markSafeWeakUse(Init);
10371 // The initialization is usually a full-expression.
10373 // FIXME: If this is a braced initialization of an aggregate, it is not
10374 // an expression, and each individual field initializer is a separate
10375 // full-expression. For instance, in:
10377 // struct Temp { ~Temp(); };
10378 // struct S { S(Temp); };
10379 // struct T { S a, b; } t = { Temp(), Temp() }
10381 // we should destroy the first Temp before constructing the second.
10382 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10384 VDecl->isConstexpr());
10385 if (Result.isInvalid()) {
10386 VDecl->setInvalidDecl();
10389 Init = Result.get();
10391 // Attach the initializer to the decl.
10392 VDecl->setInit(Init);
10394 if (VDecl->isLocalVarDecl()) {
10395 // Don't check the initializer if the declaration is malformed.
10396 if (VDecl->isInvalidDecl()) {
10399 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10400 // This is true even in OpenCL C++.
10401 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10402 CheckForConstantInitializer(Init, DclT);
10404 // Otherwise, C++ does not restrict the initializer.
10405 } else if (getLangOpts().CPlusPlus) {
10408 // C99 6.7.8p4: All the expressions in an initializer for an object that has
10409 // static storage duration shall be constant expressions or string literals.
10410 } else if (VDecl->getStorageClass() == SC_Static) {
10411 CheckForConstantInitializer(Init, DclT);
10413 // C89 is stricter than C99 for aggregate initializers.
10414 // C89 6.5.7p3: All the expressions [...] in an initializer list
10415 // for an object that has aggregate or union type shall be
10416 // constant expressions.
10417 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10418 isa<InitListExpr>(Init)) {
10419 const Expr *Culprit;
10420 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10421 Diag(Culprit->getExprLoc(),
10422 diag::ext_aggregate_init_not_constant)
10423 << Culprit->getSourceRange();
10426 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10427 VDecl->getLexicalDeclContext()->isRecord()) {
10428 // This is an in-class initialization for a static data member, e.g.,
10431 // static const int value = 17;
10434 // C++ [class.mem]p4:
10435 // A member-declarator can contain a constant-initializer only
10436 // if it declares a static member (9.4) of const integral or
10437 // const enumeration type, see 9.4.2.
10439 // C++11 [class.static.data]p3:
10440 // If a non-volatile non-inline const static data member is of integral
10441 // or enumeration type, its declaration in the class definition can
10442 // specify a brace-or-equal-initializer in which every initializer-clause
10443 // that is an assignment-expression is a constant expression. A static
10444 // data member of literal type can be declared in the class definition
10445 // with the constexpr specifier; if so, its declaration shall specify a
10446 // brace-or-equal-initializer in which every initializer-clause that is
10447 // an assignment-expression is a constant expression.
10449 // Do nothing on dependent types.
10450 if (DclT->isDependentType()) {
10452 // Allow any 'static constexpr' members, whether or not they are of literal
10453 // type. We separately check that every constexpr variable is of literal
10455 } else if (VDecl->isConstexpr()) {
10457 // Require constness.
10458 } else if (!DclT.isConstQualified()) {
10459 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10460 << Init->getSourceRange();
10461 VDecl->setInvalidDecl();
10463 // We allow integer constant expressions in all cases.
10464 } else if (DclT->isIntegralOrEnumerationType()) {
10465 // Check whether the expression is a constant expression.
10466 SourceLocation Loc;
10467 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10468 // In C++11, a non-constexpr const static data member with an
10469 // in-class initializer cannot be volatile.
10470 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10471 else if (Init->isValueDependent())
10472 ; // Nothing to check.
10473 else if (Init->isIntegerConstantExpr(Context, &Loc))
10474 ; // Ok, it's an ICE!
10475 else if (Init->isEvaluatable(Context)) {
10476 // If we can constant fold the initializer through heroics, accept it,
10477 // but report this as a use of an extension for -pedantic.
10478 Diag(Loc, diag::ext_in_class_initializer_non_constant)
10479 << Init->getSourceRange();
10481 // Otherwise, this is some crazy unknown case. Report the issue at the
10482 // location provided by the isIntegerConstantExpr failed check.
10483 Diag(Loc, diag::err_in_class_initializer_non_constant)
10484 << Init->getSourceRange();
10485 VDecl->setInvalidDecl();
10488 // We allow foldable floating-point constants as an extension.
10489 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10490 // In C++98, this is a GNU extension. In C++11, it is not, but we support
10491 // it anyway and provide a fixit to add the 'constexpr'.
10492 if (getLangOpts().CPlusPlus11) {
10493 Diag(VDecl->getLocation(),
10494 diag::ext_in_class_initializer_float_type_cxx11)
10495 << DclT << Init->getSourceRange();
10496 Diag(VDecl->getLocStart(),
10497 diag::note_in_class_initializer_float_type_cxx11)
10498 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10500 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10501 << DclT << Init->getSourceRange();
10503 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10504 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10505 << Init->getSourceRange();
10506 VDecl->setInvalidDecl();
10510 // Suggest adding 'constexpr' in C++11 for literal types.
10511 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10512 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10513 << DclT << Init->getSourceRange()
10514 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10515 VDecl->setConstexpr(true);
10518 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10519 << DclT << Init->getSourceRange();
10520 VDecl->setInvalidDecl();
10522 } else if (VDecl->isFileVarDecl()) {
10523 // In C, extern is typically used to avoid tentative definitions when
10524 // declaring variables in headers, but adding an intializer makes it a
10525 // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10526 // In C++, extern is often used to give implictly static const variables
10527 // external linkage, so don't warn in that case. If selectany is present,
10528 // this might be header code intended for C and C++ inclusion, so apply the
10530 if (VDecl->getStorageClass() == SC_Extern &&
10531 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10532 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10533 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10534 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10535 Diag(VDecl->getLocation(), diag::warn_extern_init);
10537 // C99 6.7.8p4. All file scoped initializers need to be constant.
10538 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10539 CheckForConstantInitializer(Init, DclT);
10542 // We will represent direct-initialization similarly to copy-initialization:
10543 // int x(1); -as-> int x = 1;
10544 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10546 // Clients that want to distinguish between the two forms, can check for
10547 // direct initializer using VarDecl::getInitStyle().
10548 // A major benefit is that clients that don't particularly care about which
10549 // exactly form was it (like the CodeGen) can handle both cases without
10550 // special case code.
10553 // The form of initialization (using parentheses or '=') is generally
10554 // insignificant, but does matter when the entity being initialized has a
10556 if (CXXDirectInit) {
10557 assert(DirectInit && "Call-style initializer must be direct init.");
10558 VDecl->setInitStyle(VarDecl::CallInit);
10559 } else if (DirectInit) {
10560 // This must be list-initialization. No other way is direct-initialization.
10561 VDecl->setInitStyle(VarDecl::ListInit);
10564 CheckCompleteVariableDeclaration(VDecl);
10567 /// ActOnInitializerError - Given that there was an error parsing an
10568 /// initializer for the given declaration, try to return to some form
10570 void Sema::ActOnInitializerError(Decl *D) {
10571 // Our main concern here is re-establishing invariants like "a
10572 // variable's type is either dependent or complete".
10573 if (!D || D->isInvalidDecl()) return;
10575 VarDecl *VD = dyn_cast<VarDecl>(D);
10578 // Bindings are not usable if we can't make sense of the initializer.
10579 if (auto *DD = dyn_cast<DecompositionDecl>(D))
10580 for (auto *BD : DD->bindings())
10581 BD->setInvalidDecl();
10583 // Auto types are meaningless if we can't make sense of the initializer.
10584 if (ParsingInitForAutoVars.count(D)) {
10585 D->setInvalidDecl();
10589 QualType Ty = VD->getType();
10590 if (Ty->isDependentType()) return;
10592 // Require a complete type.
10593 if (RequireCompleteType(VD->getLocation(),
10594 Context.getBaseElementType(Ty),
10595 diag::err_typecheck_decl_incomplete_type)) {
10596 VD->setInvalidDecl();
10600 // Require a non-abstract type.
10601 if (RequireNonAbstractType(VD->getLocation(), Ty,
10602 diag::err_abstract_type_in_decl,
10603 AbstractVariableType)) {
10604 VD->setInvalidDecl();
10608 // Don't bother complaining about constructors or destructors,
10612 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10613 // If there is no declaration, there was an error parsing it. Just ignore it.
10617 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10618 QualType Type = Var->getType();
10620 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10621 if (isa<DecompositionDecl>(RealDecl)) {
10622 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10623 Var->setInvalidDecl();
10627 if (Type->isUndeducedType() &&
10628 DeduceVariableDeclarationType(Var, false, nullptr))
10631 // C++11 [class.static.data]p3: A static data member can be declared with
10632 // the constexpr specifier; if so, its declaration shall specify
10633 // a brace-or-equal-initializer.
10634 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10635 // the definition of a variable [...] or the declaration of a static data
10637 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10638 !Var->isThisDeclarationADemotedDefinition()) {
10639 if (Var->isStaticDataMember()) {
10640 // C++1z removes the relevant rule; the in-class declaration is always
10641 // a definition there.
10642 if (!getLangOpts().CPlusPlus1z) {
10643 Diag(Var->getLocation(),
10644 diag::err_constexpr_static_mem_var_requires_init)
10645 << Var->getDeclName();
10646 Var->setInvalidDecl();
10650 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10651 Var->setInvalidDecl();
10656 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
10657 // definition having the concept specifier is called a variable concept. A
10658 // concept definition refers to [...] a variable concept and its initializer.
10659 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10660 if (VTD->isConcept()) {
10661 Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10662 Var->setInvalidDecl();
10667 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10669 if (!Var->isInvalidDecl() &&
10670 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10671 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10672 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10673 Var->setInvalidDecl();
10677 switch (Var->isThisDeclarationADefinition()) {
10678 case VarDecl::Definition:
10679 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10682 // We have an out-of-line definition of a static data member
10683 // that has an in-class initializer, so we type-check this like
10688 case VarDecl::DeclarationOnly:
10689 // It's only a declaration.
10691 // Block scope. C99 6.7p7: If an identifier for an object is
10692 // declared with no linkage (C99 6.2.2p6), the type for the
10693 // object shall be complete.
10694 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10695 !Var->hasLinkage() && !Var->isInvalidDecl() &&
10696 RequireCompleteType(Var->getLocation(), Type,
10697 diag::err_typecheck_decl_incomplete_type))
10698 Var->setInvalidDecl();
10700 // Make sure that the type is not abstract.
10701 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10702 RequireNonAbstractType(Var->getLocation(), Type,
10703 diag::err_abstract_type_in_decl,
10704 AbstractVariableType))
10705 Var->setInvalidDecl();
10706 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10707 Var->getStorageClass() == SC_PrivateExtern) {
10708 Diag(Var->getLocation(), diag::warn_private_extern);
10709 Diag(Var->getLocation(), diag::note_private_extern);
10714 case VarDecl::TentativeDefinition:
10715 // File scope. C99 6.9.2p2: A declaration of an identifier for an
10716 // object that has file scope without an initializer, and without a
10717 // storage-class specifier or with the storage-class specifier "static",
10718 // constitutes a tentative definition. Note: A tentative definition with
10719 // external linkage is valid (C99 6.2.2p5).
10720 if (!Var->isInvalidDecl()) {
10721 if (const IncompleteArrayType *ArrayT
10722 = Context.getAsIncompleteArrayType(Type)) {
10723 if (RequireCompleteType(Var->getLocation(),
10724 ArrayT->getElementType(),
10725 diag::err_illegal_decl_array_incomplete_type))
10726 Var->setInvalidDecl();
10727 } else if (Var->getStorageClass() == SC_Static) {
10728 // C99 6.9.2p3: If the declaration of an identifier for an object is
10729 // a tentative definition and has internal linkage (C99 6.2.2p3), the
10730 // declared type shall not be an incomplete type.
10731 // NOTE: code such as the following
10732 // static struct s;
10733 // struct s { int a; };
10734 // is accepted by gcc. Hence here we issue a warning instead of
10735 // an error and we do not invalidate the static declaration.
10736 // NOTE: to avoid multiple warnings, only check the first declaration.
10737 if (Var->isFirstDecl())
10738 RequireCompleteType(Var->getLocation(), Type,
10739 diag::ext_typecheck_decl_incomplete_type);
10743 // Record the tentative definition; we're done.
10744 if (!Var->isInvalidDecl())
10745 TentativeDefinitions.push_back(Var);
10749 // Provide a specific diagnostic for uninitialized variable
10750 // definitions with incomplete array type.
10751 if (Type->isIncompleteArrayType()) {
10752 Diag(Var->getLocation(),
10753 diag::err_typecheck_incomplete_array_needs_initializer);
10754 Var->setInvalidDecl();
10758 // Provide a specific diagnostic for uninitialized variable
10759 // definitions with reference type.
10760 if (Type->isReferenceType()) {
10761 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10762 << Var->getDeclName()
10763 << SourceRange(Var->getLocation(), Var->getLocation());
10764 Var->setInvalidDecl();
10768 // Do not attempt to type-check the default initializer for a
10769 // variable with dependent type.
10770 if (Type->isDependentType())
10773 if (Var->isInvalidDecl())
10776 if (!Var->hasAttr<AliasAttr>()) {
10777 if (RequireCompleteType(Var->getLocation(),
10778 Context.getBaseElementType(Type),
10779 diag::err_typecheck_decl_incomplete_type)) {
10780 Var->setInvalidDecl();
10787 // The variable can not have an abstract class type.
10788 if (RequireNonAbstractType(Var->getLocation(), Type,
10789 diag::err_abstract_type_in_decl,
10790 AbstractVariableType)) {
10791 Var->setInvalidDecl();
10795 // Check for jumps past the implicit initializer. C++0x
10796 // clarifies that this applies to a "variable with automatic
10797 // storage duration", not a "local variable".
10798 // C++11 [stmt.dcl]p3
10799 // A program that jumps from a point where a variable with automatic
10800 // storage duration is not in scope to a point where it is in scope is
10801 // ill-formed unless the variable has scalar type, class type with a
10802 // trivial default constructor and a trivial destructor, a cv-qualified
10803 // version of one of these types, or an array of one of the preceding
10804 // types and is declared without an initializer.
10805 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10806 if (const RecordType *Record
10807 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10808 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10809 // Mark the function for further checking even if the looser rules of
10810 // C++11 do not require such checks, so that we can diagnose
10811 // incompatibilities with C++98.
10812 if (!CXXRecord->isPOD())
10813 getCurFunction()->setHasBranchProtectedScope();
10817 // C++03 [dcl.init]p9:
10818 // If no initializer is specified for an object, and the
10819 // object is of (possibly cv-qualified) non-POD class type (or
10820 // array thereof), the object shall be default-initialized; if
10821 // the object is of const-qualified type, the underlying class
10822 // type shall have a user-declared default
10823 // constructor. Otherwise, if no initializer is specified for
10824 // a non- static object, the object and its subobjects, if
10825 // any, have an indeterminate initial value); if the object
10826 // or any of its subobjects are of const-qualified type, the
10827 // program is ill-formed.
10828 // C++0x [dcl.init]p11:
10829 // If no initializer is specified for an object, the object is
10830 // default-initialized; [...].
10831 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10832 InitializationKind Kind
10833 = InitializationKind::CreateDefault(Var->getLocation());
10835 InitializationSequence InitSeq(*this, Entity, Kind, None);
10836 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10837 if (Init.isInvalid())
10838 Var->setInvalidDecl();
10839 else if (Init.get()) {
10840 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10841 // This is important for template substitution.
10842 Var->setInitStyle(VarDecl::CallInit);
10845 CheckCompleteVariableDeclaration(Var);
10849 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10850 // If there is no declaration, there was an error parsing it. Ignore it.
10854 VarDecl *VD = dyn_cast<VarDecl>(D);
10856 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10857 D->setInvalidDecl();
10861 VD->setCXXForRangeDecl(true);
10863 // for-range-declaration cannot be given a storage class specifier.
10865 switch (VD->getStorageClass()) {
10874 case SC_PrivateExtern:
10885 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10886 << VD->getDeclName() << Error;
10887 D->setInvalidDecl();
10892 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10893 IdentifierInfo *Ident,
10894 ParsedAttributes &Attrs,
10895 SourceLocation AttrEnd) {
10896 // C++1y [stmt.iter]p1:
10897 // A range-based for statement of the form
10898 // for ( for-range-identifier : for-range-initializer ) statement
10899 // is equivalent to
10900 // for ( auto&& for-range-identifier : for-range-initializer ) statement
10901 DeclSpec DS(Attrs.getPool().getFactory());
10903 const char *PrevSpec;
10905 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10906 getPrintingPolicy());
10908 Declarator D(DS, Declarator::ForContext);
10909 D.SetIdentifier(Ident, IdentLoc);
10910 D.takeAttributes(Attrs, AttrEnd);
10912 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10913 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10914 EmptyAttrs, IdentLoc);
10915 Decl *Var = ActOnDeclarator(S, D);
10916 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10917 FinalizeDeclaration(Var);
10918 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10919 AttrEnd.isValid() ? AttrEnd : IdentLoc);
10922 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10923 if (var->isInvalidDecl()) return;
10925 if (getLangOpts().OpenCL) {
10926 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10928 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10930 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10932 var->setInvalidDecl();
10937 // In Objective-C, don't allow jumps past the implicit initialization of a
10938 // local retaining variable.
10939 if (getLangOpts().ObjC1 &&
10940 var->hasLocalStorage()) {
10941 switch (var->getType().getObjCLifetime()) {
10942 case Qualifiers::OCL_None:
10943 case Qualifiers::OCL_ExplicitNone:
10944 case Qualifiers::OCL_Autoreleasing:
10947 case Qualifiers::OCL_Weak:
10948 case Qualifiers::OCL_Strong:
10949 getCurFunction()->setHasBranchProtectedScope();
10954 // Warn about externally-visible variables being defined without a
10955 // prior declaration. We only want to do this for global
10956 // declarations, but we also specifically need to avoid doing it for
10957 // class members because the linkage of an anonymous class can
10958 // change if it's later given a typedef name.
10959 if (var->isThisDeclarationADefinition() &&
10960 var->getDeclContext()->getRedeclContext()->isFileContext() &&
10961 var->isExternallyVisible() && var->hasLinkage() &&
10962 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10963 var->getLocation())) {
10964 // Find a previous declaration that's not a definition.
10965 VarDecl *prev = var->getPreviousDecl();
10966 while (prev && prev->isThisDeclarationADefinition())
10967 prev = prev->getPreviousDecl();
10970 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10973 // Cache the result of checking for constant initialization.
10974 Optional<bool> CacheHasConstInit;
10975 const Expr *CacheCulprit;
10976 auto checkConstInit = [&]() mutable {
10977 if (!CacheHasConstInit)
10978 CacheHasConstInit = var->getInit()->isConstantInitializer(
10979 Context, var->getType()->isReferenceType(), &CacheCulprit);
10980 return *CacheHasConstInit;
10983 if (var->getTLSKind() == VarDecl::TLS_Static) {
10984 if (var->getType().isDestructedType()) {
10985 // GNU C++98 edits for __thread, [basic.start.term]p3:
10986 // The type of an object with thread storage duration shall not
10987 // have a non-trivial destructor.
10988 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10989 if (getLangOpts().CPlusPlus11)
10990 Diag(var->getLocation(), diag::note_use_thread_local);
10991 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10992 if (!checkConstInit()) {
10993 // GNU C++98 edits for __thread, [basic.start.init]p4:
10994 // An object of thread storage duration shall not require dynamic
10996 // FIXME: Need strict checking here.
10997 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10998 << CacheCulprit->getSourceRange();
10999 if (getLangOpts().CPlusPlus11)
11000 Diag(var->getLocation(), diag::note_use_thread_local);
11005 // Apply section attributes and pragmas to global variables.
11006 bool GlobalStorage = var->hasGlobalStorage();
11007 if (GlobalStorage && var->isThisDeclarationADefinition() &&
11008 !inTemplateInstantiation()) {
11009 PragmaStack<StringLiteral *> *Stack = nullptr;
11010 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11011 if (var->getType().isConstQualified())
11012 Stack = &ConstSegStack;
11013 else if (!var->getInit()) {
11014 Stack = &BSSSegStack;
11015 SectionFlags |= ASTContext::PSF_Write;
11017 Stack = &DataSegStack;
11018 SectionFlags |= ASTContext::PSF_Write;
11020 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11021 var->addAttr(SectionAttr::CreateImplicit(
11022 Context, SectionAttr::Declspec_allocate,
11023 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11025 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11026 if (UnifySection(SA->getName(), SectionFlags, var))
11027 var->dropAttr<SectionAttr>();
11029 // Apply the init_seg attribute if this has an initializer. If the
11030 // initializer turns out to not be dynamic, we'll end up ignoring this
11032 if (CurInitSeg && var->getInit())
11033 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11037 // All the following checks are C++ only.
11038 if (!getLangOpts().CPlusPlus) {
11039 // If this variable must be emitted, add it as an initializer for the
11041 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11042 Context.addModuleInitializer(ModuleScopes.back().Module, var);
11046 if (auto *DD = dyn_cast<DecompositionDecl>(var))
11047 CheckCompleteDecompositionDeclaration(DD);
11049 QualType type = var->getType();
11050 if (type->isDependentType()) return;
11052 // __block variables might require us to capture a copy-initializer.
11053 if (var->hasAttr<BlocksAttr>()) {
11054 // It's currently invalid to ever have a __block variable with an
11055 // array type; should we diagnose that here?
11057 // Regardless, we don't want to ignore array nesting when
11058 // constructing this copy.
11059 if (type->isStructureOrClassType()) {
11060 EnterExpressionEvaluationContext scope(
11061 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11062 SourceLocation poi = var->getLocation();
11063 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11065 = PerformMoveOrCopyInitialization(
11066 InitializedEntity::InitializeBlock(poi, type, false),
11067 var, var->getType(), varRef, /*AllowNRVO=*/true);
11068 if (!result.isInvalid()) {
11069 result = MaybeCreateExprWithCleanups(result);
11070 Expr *init = result.getAs<Expr>();
11071 Context.setBlockVarCopyInits(var, init);
11076 Expr *Init = var->getInit();
11077 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11078 QualType baseType = Context.getBaseElementType(type);
11080 if (!var->getDeclContext()->isDependentContext() &&
11081 Init && !Init->isValueDependent()) {
11083 if (var->isConstexpr()) {
11084 SmallVector<PartialDiagnosticAt, 8> Notes;
11085 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11086 SourceLocation DiagLoc = var->getLocation();
11087 // If the note doesn't add any useful information other than a source
11088 // location, fold it into the primary diagnostic.
11089 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11090 diag::note_invalid_subexpr_in_const_expr) {
11091 DiagLoc = Notes[0].first;
11094 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11095 << var << Init->getSourceRange();
11096 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11097 Diag(Notes[I].first, Notes[I].second);
11099 } else if (var->isUsableInConstantExpressions(Context)) {
11100 // Check whether the initializer of a const variable of integral or
11101 // enumeration type is an ICE now, since we can't tell whether it was
11102 // initialized by a constant expression if we check later.
11103 var->checkInitIsICE();
11106 // Don't emit further diagnostics about constexpr globals since they
11107 // were just diagnosed.
11108 if (!var->isConstexpr() && GlobalStorage &&
11109 var->hasAttr<RequireConstantInitAttr>()) {
11110 // FIXME: Need strict checking in C++03 here.
11111 bool DiagErr = getLangOpts().CPlusPlus11
11112 ? !var->checkInitIsICE() : !checkConstInit();
11114 auto attr = var->getAttr<RequireConstantInitAttr>();
11115 Diag(var->getLocation(), diag::err_require_constant_init_failed)
11116 << Init->getSourceRange();
11117 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11118 << attr->getRange();
11121 else if (!var->isConstexpr() && IsGlobal &&
11122 !getDiagnostics().isIgnored(diag::warn_global_constructor,
11123 var->getLocation())) {
11124 // Warn about globals which don't have a constant initializer. Don't
11125 // warn about globals with a non-trivial destructor because we already
11126 // warned about them.
11127 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11128 if (!(RD && !RD->hasTrivialDestructor())) {
11129 if (!checkConstInit())
11130 Diag(var->getLocation(), diag::warn_global_constructor)
11131 << Init->getSourceRange();
11136 // Require the destructor.
11137 if (const RecordType *recordType = baseType->getAs<RecordType>())
11138 FinalizeVarWithDestructor(var, recordType);
11140 // If this variable must be emitted, add it as an initializer for the current
11142 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11143 Context.addModuleInitializer(ModuleScopes.back().Module, var);
11146 /// \brief Determines if a variable's alignment is dependent.
11147 static bool hasDependentAlignment(VarDecl *VD) {
11148 if (VD->getType()->isDependentType())
11150 for (auto *I : VD->specific_attrs<AlignedAttr>())
11151 if (I->isAlignmentDependent())
11156 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11157 /// any semantic actions necessary after any initializer has been attached.
11158 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11159 // Note that we are no longer parsing the initializer for this declaration.
11160 ParsingInitForAutoVars.erase(ThisDecl);
11162 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11166 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11167 for (auto *BD : DD->bindings()) {
11168 FinalizeDeclaration(BD);
11172 checkAttributesAfterMerging(*this, *VD);
11174 // Perform TLS alignment check here after attributes attached to the variable
11175 // which may affect the alignment have been processed. Only perform the check
11176 // if the target has a maximum TLS alignment (zero means no constraints).
11177 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11178 // Protect the check so that it's not performed on dependent types and
11179 // dependent alignments (we can't determine the alignment in that case).
11180 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11181 !VD->isInvalidDecl()) {
11182 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11183 if (Context.getDeclAlign(VD) > MaxAlignChars) {
11184 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11185 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11186 << (unsigned)MaxAlignChars.getQuantity();
11191 if (VD->isStaticLocal()) {
11192 if (FunctionDecl *FD =
11193 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11194 // Static locals inherit dll attributes from their function.
11195 if (Attr *A = getDLLAttr(FD)) {
11196 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11197 NewAttr->setInherited(true);
11198 VD->addAttr(NewAttr);
11200 // CUDA E.2.9.4: Within the body of a __device__ or __global__
11201 // function, only __shared__ variables may be declared with
11202 // static storage class.
11203 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11204 CUDADiagIfDeviceCode(VD->getLocation(),
11205 diag::err_device_static_local_var)
11206 << CurrentCUDATarget())
11207 VD->setInvalidDecl();
11211 // Perform check for initializers of device-side global variables.
11212 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11213 // 7.5). We must also apply the same checks to all __shared__
11214 // variables whether they are local or not. CUDA also allows
11215 // constant initializers for __constant__ and __device__ variables.
11216 if (getLangOpts().CUDA) {
11217 const Expr *Init = VD->getInit();
11218 if (Init && VD->hasGlobalStorage()) {
11219 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11220 VD->hasAttr<CUDASharedAttr>()) {
11221 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11222 bool AllowedInit = false;
11223 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11225 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11226 // We'll allow constant initializers even if it's a non-empty
11227 // constructor according to CUDA rules. This deviates from NVCC,
11228 // but allows us to handle things like constexpr constructors.
11229 if (!AllowedInit &&
11230 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11231 AllowedInit = VD->getInit()->isConstantInitializer(
11232 Context, VD->getType()->isReferenceType());
11234 // Also make sure that destructor, if there is one, is empty.
11236 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11238 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11240 if (!AllowedInit) {
11241 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11242 ? diag::err_shared_var_init
11243 : diag::err_dynamic_var_init)
11244 << Init->getSourceRange();
11245 VD->setInvalidDecl();
11248 // This is a host-side global variable. Check that the initializer is
11249 // callable from the host side.
11250 const FunctionDecl *InitFn = nullptr;
11251 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11252 InitFn = CE->getConstructor();
11253 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11254 InitFn = CE->getDirectCallee();
11257 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11258 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11259 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11260 << InitFnTarget << InitFn;
11261 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11262 VD->setInvalidDecl();
11269 // Grab the dllimport or dllexport attribute off of the VarDecl.
11270 const InheritableAttr *DLLAttr = getDLLAttr(VD);
11272 // Imported static data members cannot be defined out-of-line.
11273 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11274 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11275 VD->isThisDeclarationADefinition()) {
11276 // We allow definitions of dllimport class template static data members
11278 CXXRecordDecl *Context =
11279 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11280 bool IsClassTemplateMember =
11281 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11282 Context->getDescribedClassTemplate();
11284 Diag(VD->getLocation(),
11285 IsClassTemplateMember
11286 ? diag::warn_attribute_dllimport_static_field_definition
11287 : diag::err_attribute_dllimport_static_field_definition);
11288 Diag(IA->getLocation(), diag::note_attribute);
11289 if (!IsClassTemplateMember)
11290 VD->setInvalidDecl();
11294 // dllimport/dllexport variables cannot be thread local, their TLS index
11295 // isn't exported with the variable.
11296 if (DLLAttr && VD->getTLSKind()) {
11297 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11298 if (F && getDLLAttr(F)) {
11299 assert(VD->isStaticLocal());
11300 // But if this is a static local in a dlimport/dllexport function, the
11301 // function will never be inlined, which means the var would never be
11302 // imported, so having it marked import/export is safe.
11304 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11306 VD->setInvalidDecl();
11310 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11311 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11312 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11313 VD->dropAttr<UsedAttr>();
11317 const DeclContext *DC = VD->getDeclContext();
11318 // If there's a #pragma GCC visibility in scope, and this isn't a class
11319 // member, set the visibility of this variable.
11320 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11321 AddPushedVisibilityAttribute(VD);
11323 // FIXME: Warn on unused var template partial specializations.
11324 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11325 MarkUnusedFileScopedDecl(VD);
11327 // Now we have parsed the initializer and can update the table of magic
11329 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11330 !VD->getType()->isIntegralOrEnumerationType())
11333 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11334 const Expr *MagicValueExpr = VD->getInit();
11335 if (!MagicValueExpr) {
11338 llvm::APSInt MagicValueInt;
11339 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11340 Diag(I->getRange().getBegin(),
11341 diag::err_type_tag_for_datatype_not_ice)
11342 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11345 if (MagicValueInt.getActiveBits() > 64) {
11346 Diag(I->getRange().getBegin(),
11347 diag::err_type_tag_for_datatype_too_large)
11348 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11351 uint64_t MagicValue = MagicValueInt.getZExtValue();
11352 RegisterTypeTagForDatatype(I->getArgumentKind(),
11354 I->getMatchingCType(),
11355 I->getLayoutCompatible(),
11356 I->getMustBeNull());
11360 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11361 auto *VD = dyn_cast<VarDecl>(DD);
11362 return VD && !VD->getType()->hasAutoForTrailingReturnType();
11365 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11366 ArrayRef<Decl *> Group) {
11367 SmallVector<Decl*, 8> Decls;
11369 if (DS.isTypeSpecOwned())
11370 Decls.push_back(DS.getRepAsDecl());
11372 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11373 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11374 bool DiagnosedMultipleDecomps = false;
11375 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11376 bool DiagnosedNonDeducedAuto = false;
11378 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11379 if (Decl *D = Group[i]) {
11380 // For declarators, there are some additional syntactic-ish checks we need
11382 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11383 if (!FirstDeclaratorInGroup)
11384 FirstDeclaratorInGroup = DD;
11385 if (!FirstDecompDeclaratorInGroup)
11386 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11387 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11388 !hasDeducedAuto(DD))
11389 FirstNonDeducedAutoInGroup = DD;
11391 if (FirstDeclaratorInGroup != DD) {
11392 // A decomposition declaration cannot be combined with any other
11393 // declaration in the same group.
11394 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11395 Diag(FirstDecompDeclaratorInGroup->getLocation(),
11396 diag::err_decomp_decl_not_alone)
11397 << FirstDeclaratorInGroup->getSourceRange()
11398 << DD->getSourceRange();
11399 DiagnosedMultipleDecomps = true;
11402 // A declarator that uses 'auto' in any way other than to declare a
11403 // variable with a deduced type cannot be combined with any other
11404 // declarator in the same group.
11405 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11406 Diag(FirstNonDeducedAutoInGroup->getLocation(),
11407 diag::err_auto_non_deduced_not_alone)
11408 << FirstNonDeducedAutoInGroup->getType()
11409 ->hasAutoForTrailingReturnType()
11410 << FirstDeclaratorInGroup->getSourceRange()
11411 << DD->getSourceRange();
11412 DiagnosedNonDeducedAuto = true;
11417 Decls.push_back(D);
11421 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11422 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11423 handleTagNumbering(Tag, S);
11424 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11425 getLangOpts().CPlusPlus)
11426 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11430 return BuildDeclaratorGroup(Decls);
11433 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11434 /// group, performing any necessary semantic checking.
11435 Sema::DeclGroupPtrTy
11436 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11437 // C++14 [dcl.spec.auto]p7: (DR1347)
11438 // If the type that replaces the placeholder type is not the same in each
11439 // deduction, the program is ill-formed.
11440 if (Group.size() > 1) {
11442 VarDecl *DeducedDecl = nullptr;
11443 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11444 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11445 if (!D || D->isInvalidDecl())
11447 DeducedType *DT = D->getType()->getContainedDeducedType();
11448 if (!DT || DT->getDeducedType().isNull())
11450 if (Deduced.isNull()) {
11451 Deduced = DT->getDeducedType();
11453 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11454 auto *AT = dyn_cast<AutoType>(DT);
11455 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11456 diag::err_auto_different_deductions)
11457 << (AT ? (unsigned)AT->getKeyword() : 3)
11458 << Deduced << DeducedDecl->getDeclName()
11459 << DT->getDeducedType() << D->getDeclName()
11460 << DeducedDecl->getInit()->getSourceRange()
11461 << D->getInit()->getSourceRange();
11462 D->setInvalidDecl();
11468 ActOnDocumentableDecls(Group);
11470 return DeclGroupPtrTy::make(
11471 DeclGroupRef::Create(Context, Group.data(), Group.size()));
11474 void Sema::ActOnDocumentableDecl(Decl *D) {
11475 ActOnDocumentableDecls(D);
11478 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11479 // Don't parse the comment if Doxygen diagnostics are ignored.
11480 if (Group.empty() || !Group[0])
11483 if (Diags.isIgnored(diag::warn_doc_param_not_found,
11484 Group[0]->getLocation()) &&
11485 Diags.isIgnored(diag::warn_unknown_comment_command_name,
11486 Group[0]->getLocation()))
11489 if (Group.size() >= 2) {
11490 // This is a decl group. Normally it will contain only declarations
11491 // produced from declarator list. But in case we have any definitions or
11492 // additional declaration references:
11493 // 'typedef struct S {} S;'
11494 // 'typedef struct S *S;'
11496 // FinalizeDeclaratorGroup adds these as separate declarations.
11497 Decl *MaybeTagDecl = Group[0];
11498 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11499 Group = Group.slice(1);
11503 // See if there are any new comments that are not attached to a decl.
11504 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11505 if (!Comments.empty() &&
11506 !Comments.back()->isAttached()) {
11507 // There is at least one comment that not attached to a decl.
11508 // Maybe it should be attached to one of these decls?
11510 // Note that this way we pick up not only comments that precede the
11511 // declaration, but also comments that *follow* the declaration -- thanks to
11512 // the lookahead in the lexer: we've consumed the semicolon and looked
11513 // ahead through comments.
11514 for (unsigned i = 0, e = Group.size(); i != e; ++i)
11515 Context.getCommentForDecl(Group[i], &PP);
11519 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11520 /// to introduce parameters into function prototype scope.
11521 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11522 const DeclSpec &DS = D.getDeclSpec();
11524 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11526 // C++03 [dcl.stc]p2 also permits 'auto'.
11527 StorageClass SC = SC_None;
11528 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11530 } else if (getLangOpts().CPlusPlus &&
11531 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11533 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11534 Diag(DS.getStorageClassSpecLoc(),
11535 diag::err_invalid_storage_class_in_func_decl);
11536 D.getMutableDeclSpec().ClearStorageClassSpecs();
11539 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11540 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11541 << DeclSpec::getSpecifierName(TSCS);
11542 if (DS.isInlineSpecified())
11543 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11544 << getLangOpts().CPlusPlus1z;
11545 if (DS.isConstexprSpecified())
11546 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11548 if (DS.isConceptSpecified())
11549 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11551 DiagnoseFunctionSpecifiers(DS);
11553 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11554 QualType parmDeclType = TInfo->getType();
11556 if (getLangOpts().CPlusPlus) {
11557 // Check that there are no default arguments inside the type of this
11559 CheckExtraCXXDefaultArguments(D);
11561 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11562 if (D.getCXXScopeSpec().isSet()) {
11563 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11564 << D.getCXXScopeSpec().getRange();
11565 D.getCXXScopeSpec().clear();
11569 // Ensure we have a valid name
11570 IdentifierInfo *II = nullptr;
11572 II = D.getIdentifier();
11574 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11575 << GetNameForDeclarator(D).getName();
11576 D.setInvalidType(true);
11580 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11582 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11585 if (R.isSingleResult()) {
11586 NamedDecl *PrevDecl = R.getFoundDecl();
11587 if (PrevDecl->isTemplateParameter()) {
11588 // Maybe we will complain about the shadowed template parameter.
11589 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11590 // Just pretend that we didn't see the previous declaration.
11591 PrevDecl = nullptr;
11592 } else if (S->isDeclScope(PrevDecl)) {
11593 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11594 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11596 // Recover by removing the name
11598 D.SetIdentifier(nullptr, D.getIdentifierLoc());
11599 D.setInvalidType(true);
11604 // Temporarily put parameter variables in the translation unit, not
11605 // the enclosing context. This prevents them from accidentally
11606 // looking like class members in C++.
11607 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11609 D.getIdentifierLoc(), II,
11610 parmDeclType, TInfo,
11613 if (D.isInvalidType())
11614 New->setInvalidDecl();
11616 assert(S->isFunctionPrototypeScope());
11617 assert(S->getFunctionPrototypeDepth() >= 1);
11618 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11619 S->getNextFunctionPrototypeIndex());
11621 // Add the parameter declaration into this scope.
11624 IdResolver.AddDecl(New);
11626 ProcessDeclAttributes(S, New, D);
11628 if (D.getDeclSpec().isModulePrivateSpecified())
11629 Diag(New->getLocation(), diag::err_module_private_local)
11630 << 1 << New->getDeclName()
11631 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11632 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11634 if (New->hasAttr<BlocksAttr>()) {
11635 Diag(New->getLocation(), diag::err_block_on_nonlocal);
11640 /// \brief Synthesizes a variable for a parameter arising from a
11642 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11643 SourceLocation Loc,
11645 /* FIXME: setting StartLoc == Loc.
11646 Would it be worth to modify callers so as to provide proper source
11647 location for the unnamed parameters, embedding the parameter's type? */
11648 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11649 T, Context.getTrivialTypeSourceInfo(T, Loc),
11651 Param->setImplicit();
11655 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11656 // Don't diagnose unused-parameter errors in template instantiations; we
11657 // will already have done so in the template itself.
11658 if (inTemplateInstantiation())
11661 for (const ParmVarDecl *Parameter : Parameters) {
11662 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11663 !Parameter->hasAttr<UnusedAttr>()) {
11664 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11665 << Parameter->getDeclName();
11670 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11671 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11672 if (LangOpts.NumLargeByValueCopy == 0) // No check.
11675 // Warn if the return value is pass-by-value and larger than the specified
11677 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11678 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11679 if (Size > LangOpts.NumLargeByValueCopy)
11680 Diag(D->getLocation(), diag::warn_return_value_size)
11681 << D->getDeclName() << Size;
11684 // Warn if any parameter is pass-by-value and larger than the specified
11686 for (const ParmVarDecl *Parameter : Parameters) {
11687 QualType T = Parameter->getType();
11688 if (T->isDependentType() || !T.isPODType(Context))
11690 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11691 if (Size > LangOpts.NumLargeByValueCopy)
11692 Diag(Parameter->getLocation(), diag::warn_parameter_size)
11693 << Parameter->getDeclName() << Size;
11697 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11698 SourceLocation NameLoc, IdentifierInfo *Name,
11699 QualType T, TypeSourceInfo *TSInfo,
11701 // In ARC, infer a lifetime qualifier for appropriate parameter types.
11702 if (getLangOpts().ObjCAutoRefCount &&
11703 T.getObjCLifetime() == Qualifiers::OCL_None &&
11704 T->isObjCLifetimeType()) {
11706 Qualifiers::ObjCLifetime lifetime;
11708 // Special cases for arrays:
11709 // - if it's const, use __unsafe_unretained
11710 // - otherwise, it's an error
11711 if (T->isArrayType()) {
11712 if (!T.isConstQualified()) {
11713 DelayedDiagnostics.add(
11714 sema::DelayedDiagnostic::makeForbiddenType(
11715 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11717 lifetime = Qualifiers::OCL_ExplicitNone;
11719 lifetime = T->getObjCARCImplicitLifetime();
11721 T = Context.getLifetimeQualifiedType(T, lifetime);
11724 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11725 Context.getAdjustedParameterType(T),
11726 TSInfo, SC, nullptr);
11728 // Parameters can not be abstract class types.
11729 // For record types, this is done by the AbstractClassUsageDiagnoser once
11730 // the class has been completely parsed.
11731 if (!CurContext->isRecord() &&
11732 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11733 AbstractParamType))
11734 New->setInvalidDecl();
11736 // Parameter declarators cannot be interface types. All ObjC objects are
11737 // passed by reference.
11738 if (T->isObjCObjectType()) {
11739 SourceLocation TypeEndLoc =
11740 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11742 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11743 << FixItHint::CreateInsertion(TypeEndLoc, "*");
11744 T = Context.getObjCObjectPointerType(T);
11748 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11749 // duration shall not be qualified by an address-space qualifier."
11750 // Since all parameters have automatic store duration, they can not have
11751 // an address space.
11752 if (T.getAddressSpace() != 0) {
11753 // OpenCL allows function arguments declared to be an array of a type
11754 // to be qualified with an address space.
11755 if (!(getLangOpts().OpenCL && T->isArrayType())) {
11756 Diag(NameLoc, diag::err_arg_with_address_space);
11757 New->setInvalidDecl();
11764 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11765 SourceLocation LocAfterDecls) {
11766 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11768 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11769 // for a K&R function.
11770 if (!FTI.hasPrototype) {
11771 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11773 if (FTI.Params[i].Param == nullptr) {
11774 SmallString<256> Code;
11775 llvm::raw_svector_ostream(Code)
11776 << " int " << FTI.Params[i].Ident->getName() << ";\n";
11777 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11778 << FTI.Params[i].Ident
11779 << FixItHint::CreateInsertion(LocAfterDecls, Code);
11781 // Implicitly declare the argument as type 'int' for lack of a better
11783 AttributeFactory attrs;
11784 DeclSpec DS(attrs);
11785 const char* PrevSpec; // unused
11786 unsigned DiagID; // unused
11787 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11788 DiagID, Context.getPrintingPolicy());
11789 // Use the identifier location for the type source range.
11790 DS.SetRangeStart(FTI.Params[i].IdentLoc);
11791 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11792 Declarator ParamD(DS, Declarator::KNRTypeListContext);
11793 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11794 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11801 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11802 MultiTemplateParamsArg TemplateParameterLists,
11803 SkipBodyInfo *SkipBody) {
11804 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11805 assert(D.isFunctionDeclarator() && "Not a function declarator!");
11806 Scope *ParentScope = FnBodyScope->getParent();
11808 D.setFunctionDefinitionKind(FDK_Definition);
11809 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11810 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11813 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11814 Consumer.HandleInlineFunctionDefinition(D);
11817 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11818 const FunctionDecl*& PossibleZeroParamPrototype) {
11819 // Don't warn about invalid declarations.
11820 if (FD->isInvalidDecl())
11823 // Or declarations that aren't global.
11824 if (!FD->isGlobal())
11827 // Don't warn about C++ member functions.
11828 if (isa<CXXMethodDecl>(FD))
11831 // Don't warn about 'main'.
11835 // Don't warn about inline functions.
11836 if (FD->isInlined())
11839 // Don't warn about function templates.
11840 if (FD->getDescribedFunctionTemplate())
11843 // Don't warn about function template specializations.
11844 if (FD->isFunctionTemplateSpecialization())
11847 // Don't warn for OpenCL kernels.
11848 if (FD->hasAttr<OpenCLKernelAttr>())
11851 // Don't warn on explicitly deleted functions.
11852 if (FD->isDeleted())
11855 bool MissingPrototype = true;
11856 for (const FunctionDecl *Prev = FD->getPreviousDecl();
11857 Prev; Prev = Prev->getPreviousDecl()) {
11858 // Ignore any declarations that occur in function or method
11859 // scope, because they aren't visible from the header.
11860 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11863 MissingPrototype = !Prev->getType()->isFunctionProtoType();
11864 if (FD->getNumParams() == 0)
11865 PossibleZeroParamPrototype = Prev;
11869 return MissingPrototype;
11873 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11874 const FunctionDecl *EffectiveDefinition,
11875 SkipBodyInfo *SkipBody) {
11876 const FunctionDecl *Definition = EffectiveDefinition;
11878 if (!FD->isDefined(Definition))
11881 if (canRedefineFunction(Definition, getLangOpts()))
11884 // Don't emit an error when this is redifinition of a typo-corrected
11886 if (TypoCorrectedFunctionDefinitions.count(Definition))
11889 // If we don't have a visible definition of the function, and it's inline or
11890 // a template, skip the new definition.
11891 if (SkipBody && !hasVisibleDefinition(Definition) &&
11892 (Definition->getFormalLinkage() == InternalLinkage ||
11893 Definition->isInlined() ||
11894 Definition->getDescribedFunctionTemplate() ||
11895 Definition->getNumTemplateParameterLists())) {
11896 SkipBody->ShouldSkip = true;
11897 if (auto *TD = Definition->getDescribedFunctionTemplate())
11898 makeMergedDefinitionVisible(TD);
11899 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
11903 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11904 Definition->getStorageClass() == SC_Extern)
11905 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11906 << FD->getDeclName() << getLangOpts().CPlusPlus;
11908 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11910 Diag(Definition->getLocation(), diag::note_previous_definition);
11911 FD->setInvalidDecl();
11914 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11916 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11918 LambdaScopeInfo *LSI = S.PushLambdaScope();
11919 LSI->CallOperator = CallOperator;
11920 LSI->Lambda = LambdaClass;
11921 LSI->ReturnType = CallOperator->getReturnType();
11922 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11924 if (LCD == LCD_None)
11925 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11926 else if (LCD == LCD_ByCopy)
11927 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11928 else if (LCD == LCD_ByRef)
11929 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11930 DeclarationNameInfo DNI = CallOperator->getNameInfo();
11932 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11933 LSI->Mutable = !CallOperator->isConst();
11935 // Add the captures to the LSI so they can be noted as already
11936 // captured within tryCaptureVar.
11937 auto I = LambdaClass->field_begin();
11938 for (const auto &C : LambdaClass->captures()) {
11939 if (C.capturesVariable()) {
11940 VarDecl *VD = C.getCapturedVar();
11941 if (VD->isInitCapture())
11942 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11943 QualType CaptureType = VD->getType();
11944 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11945 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11946 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11947 /*EllipsisLoc*/C.isPackExpansion()
11948 ? C.getEllipsisLoc() : SourceLocation(),
11949 CaptureType, /*Expr*/ nullptr);
11951 } else if (C.capturesThis()) {
11952 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11954 C.getCaptureKind() == LCK_StarThis);
11956 LSI->addVLATypeCapture(C.getLocation(), I->getType());
11962 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11963 SkipBodyInfo *SkipBody) {
11966 FunctionDecl *FD = nullptr;
11968 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11969 FD = FunTmpl->getTemplatedDecl();
11971 FD = cast<FunctionDecl>(D);
11973 // Check for defining attributes before the check for redefinition.
11974 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
11975 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
11976 FD->dropAttr<AliasAttr>();
11977 FD->setInvalidDecl();
11979 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
11980 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
11981 FD->dropAttr<IFuncAttr>();
11982 FD->setInvalidDecl();
11985 // See if this is a redefinition.
11986 if (!FD->isLateTemplateParsed()) {
11987 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11989 // If we're skipping the body, we're done. Don't enter the scope.
11990 if (SkipBody && SkipBody->ShouldSkip)
11994 // Mark this function as "will have a body eventually". This lets users to
11995 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11997 FD->setWillHaveBody();
11999 // If we are instantiating a generic lambda call operator, push
12000 // a LambdaScopeInfo onto the function stack. But use the information
12001 // that's already been calculated (ActOnLambdaExpr) to prime the current
12002 // LambdaScopeInfo.
12003 // When the template operator is being specialized, the LambdaScopeInfo,
12004 // has to be properly restored so that tryCaptureVariable doesn't try
12005 // and capture any new variables. In addition when calculating potential
12006 // captures during transformation of nested lambdas, it is necessary to
12007 // have the LSI properly restored.
12008 if (isGenericLambdaCallOperatorSpecialization(FD)) {
12009 assert(inTemplateInstantiation() &&
12010 "There should be an active template instantiation on the stack "
12011 "when instantiating a generic lambda!");
12012 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12014 // Enter a new function scope
12015 PushFunctionScope();
12018 // Builtin functions cannot be defined.
12019 if (unsigned BuiltinID = FD->getBuiltinID()) {
12020 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12021 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12022 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12023 FD->setInvalidDecl();
12027 // The return type of a function definition must be complete
12028 // (C99 6.9.1p3, C++ [dcl.fct]p6).
12029 QualType ResultType = FD->getReturnType();
12030 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12031 !FD->isInvalidDecl() &&
12032 RequireCompleteType(FD->getLocation(), ResultType,
12033 diag::err_func_def_incomplete_result))
12034 FD->setInvalidDecl();
12037 PushDeclContext(FnBodyScope, FD);
12039 // Check the validity of our function parameters
12040 CheckParmsForFunctionDef(FD->parameters(),
12041 /*CheckParameterNames=*/true);
12043 // Add non-parameter declarations already in the function to the current
12046 for (Decl *NPD : FD->decls()) {
12047 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12050 assert(!isa<ParmVarDecl>(NonParmDecl) &&
12051 "parameters should not be in newly created FD yet");
12053 // If the decl has a name, make it accessible in the current scope.
12054 if (NonParmDecl->getDeclName())
12055 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12057 // Similarly, dive into enums and fish their constants out, making them
12058 // accessible in this scope.
12059 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12060 for (auto *EI : ED->enumerators())
12061 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12066 // Introduce our parameters into the function scope
12067 for (auto Param : FD->parameters()) {
12068 Param->setOwningFunction(FD);
12070 // If this has an identifier, add it to the scope stack.
12071 if (Param->getIdentifier() && FnBodyScope) {
12072 CheckShadow(FnBodyScope, Param);
12074 PushOnScopeChains(Param, FnBodyScope);
12078 // Ensure that the function's exception specification is instantiated.
12079 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12080 ResolveExceptionSpec(D->getLocation(), FPT);
12082 // dllimport cannot be applied to non-inline function definitions.
12083 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12084 !FD->isTemplateInstantiation()) {
12085 assert(!FD->hasAttr<DLLExportAttr>());
12086 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12087 FD->setInvalidDecl();
12090 // We want to attach documentation to original Decl (which might be
12091 // a function template).
12092 ActOnDocumentableDecl(D);
12093 if (getCurLexicalContext()->isObjCContainer() &&
12094 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12095 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12096 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12101 /// \brief Given the set of return statements within a function body,
12102 /// compute the variables that are subject to the named return value
12105 /// Each of the variables that is subject to the named return value
12106 /// optimization will be marked as NRVO variables in the AST, and any
12107 /// return statement that has a marked NRVO variable as its NRVO candidate can
12108 /// use the named return value optimization.
12110 /// This function applies a very simplistic algorithm for NRVO: if every return
12111 /// statement in the scope of a variable has the same NRVO candidate, that
12112 /// candidate is an NRVO variable.
12113 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12114 ReturnStmt **Returns = Scope->Returns.data();
12116 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12117 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12118 if (!NRVOCandidate->isNRVOVariable())
12119 Returns[I]->setNRVOCandidate(nullptr);
12124 bool Sema::canDelayFunctionBody(const Declarator &D) {
12125 // We can't delay parsing the body of a constexpr function template (yet).
12126 if (D.getDeclSpec().isConstexprSpecified())
12129 // We can't delay parsing the body of a function template with a deduced
12130 // return type (yet).
12131 if (D.getDeclSpec().hasAutoTypeSpec()) {
12132 // If the placeholder introduces a non-deduced trailing return type,
12133 // we can still delay parsing it.
12134 if (D.getNumTypeObjects()) {
12135 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12136 if (Outer.Kind == DeclaratorChunk::Function &&
12137 Outer.Fun.hasTrailingReturnType()) {
12138 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12139 return Ty.isNull() || !Ty->isUndeducedType();
12148 bool Sema::canSkipFunctionBody(Decl *D) {
12149 // We cannot skip the body of a function (or function template) which is
12150 // constexpr, since we may need to evaluate its body in order to parse the
12151 // rest of the file.
12152 // We cannot skip the body of a function with an undeduced return type,
12153 // because any callers of that function need to know the type.
12154 if (const FunctionDecl *FD = D->getAsFunction())
12155 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12157 return Consumer.shouldSkipFunctionBody(D);
12160 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12161 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12162 FD->setHasSkippedBody();
12163 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12164 MD->setHasSkippedBody();
12168 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12169 return ActOnFinishFunctionBody(D, BodyArg, false);
12172 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12173 bool IsInstantiation) {
12174 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12176 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12177 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12179 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12180 CheckCompletedCoroutineBody(FD, Body);
12185 if (getLangOpts().CPlusPlus14) {
12186 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12187 FD->getReturnType()->isUndeducedType()) {
12188 // If the function has a deduced result type but contains no 'return'
12189 // statements, the result type as written must be exactly 'auto', and
12190 // the deduced result type is 'void'.
12191 if (!FD->getReturnType()->getAs<AutoType>()) {
12192 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12193 << FD->getReturnType();
12194 FD->setInvalidDecl();
12196 // Substitute 'void' for the 'auto' in the type.
12197 TypeLoc ResultType = getReturnTypeLoc(FD);
12198 Context.adjustDeducedFunctionResultType(
12199 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12202 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12203 // In C++11, we don't use 'auto' deduction rules for lambda call
12204 // operators because we don't support return type deduction.
12205 auto *LSI = getCurLambda();
12206 if (LSI->HasImplicitReturnType) {
12207 deduceClosureReturnType(*LSI);
12209 // C++11 [expr.prim.lambda]p4:
12210 // [...] if there are no return statements in the compound-statement
12211 // [the deduced type is] the type void
12213 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12215 // Update the return type to the deduced type.
12216 const FunctionProtoType *Proto =
12217 FD->getType()->getAs<FunctionProtoType>();
12218 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12219 Proto->getExtProtoInfo()));
12223 // The only way to be included in UndefinedButUsed is if there is an
12224 // ODR use before the definition. Avoid the expensive map lookup if this
12225 // is the first declaration.
12226 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
12227 if (!FD->isExternallyVisible())
12228 UndefinedButUsed.erase(FD);
12229 else if (FD->isInlined() &&
12230 !LangOpts.GNUInline &&
12231 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
12232 UndefinedButUsed.erase(FD);
12235 // If the function implicitly returns zero (like 'main') or is naked,
12236 // don't complain about missing return statements.
12237 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12238 WP.disableCheckFallThrough();
12240 // MSVC permits the use of pure specifier (=0) on function definition,
12241 // defined at class scope, warn about this non-standard construct.
12242 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12243 Diag(FD->getLocation(), diag::ext_pure_function_definition);
12245 if (!FD->isInvalidDecl()) {
12246 // Don't diagnose unused parameters of defaulted or deleted functions.
12247 if (!FD->isDeleted() && !FD->isDefaulted())
12248 DiagnoseUnusedParameters(FD->parameters());
12249 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12250 FD->getReturnType(), FD);
12252 // If this is a structor, we need a vtable.
12253 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12254 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12255 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12256 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12258 // Try to apply the named return value optimization. We have to check
12259 // if we can do this here because lambdas keep return statements around
12260 // to deduce an implicit return type.
12261 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12262 !FD->isDependentContext())
12263 computeNRVO(Body, getCurFunction());
12266 // GNU warning -Wmissing-prototypes:
12267 // Warn if a global function is defined without a previous
12268 // prototype declaration. This warning is issued even if the
12269 // definition itself provides a prototype. The aim is to detect
12270 // global functions that fail to be declared in header files.
12271 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12272 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12273 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12275 if (PossibleZeroParamPrototype) {
12276 // We found a declaration that is not a prototype,
12277 // but that could be a zero-parameter prototype
12278 if (TypeSourceInfo *TI =
12279 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12280 TypeLoc TL = TI->getTypeLoc();
12281 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12282 Diag(PossibleZeroParamPrototype->getLocation(),
12283 diag::note_declaration_not_a_prototype)
12284 << PossibleZeroParamPrototype
12285 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12289 // GNU warning -Wstrict-prototypes
12290 // Warn if K&R function is defined without a previous declaration.
12291 // This warning is issued only if the definition itself does not provide
12292 // a prototype. Only K&R definitions do not provide a prototype.
12293 // An empty list in a function declarator that is part of a definition
12294 // of that function specifies that the function has no parameters
12295 // (C99 6.7.5.3p14)
12296 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12297 !LangOpts.CPlusPlus) {
12298 TypeSourceInfo *TI = FD->getTypeSourceInfo();
12299 TypeLoc TL = TI->getTypeLoc();
12300 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12301 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
12305 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12306 const CXXMethodDecl *KeyFunction;
12307 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12309 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12310 MD == KeyFunction->getCanonicalDecl()) {
12311 // Update the key-function state if necessary for this ABI.
12312 if (FD->isInlined() &&
12313 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12314 Context.setNonKeyFunction(MD);
12316 // If the newly-chosen key function is already defined, then we
12317 // need to mark the vtable as used retroactively.
12318 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12319 const FunctionDecl *Definition;
12320 if (KeyFunction && KeyFunction->isDefined(Definition))
12321 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12323 // We just defined they key function; mark the vtable as used.
12324 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12329 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12330 "Function parsing confused");
12331 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12332 assert(MD == getCurMethodDecl() && "Method parsing confused");
12334 if (!MD->isInvalidDecl()) {
12335 DiagnoseUnusedParameters(MD->parameters());
12336 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12337 MD->getReturnType(), MD);
12340 computeNRVO(Body, getCurFunction());
12342 if (getCurFunction()->ObjCShouldCallSuper) {
12343 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12344 << MD->getSelector().getAsString();
12345 getCurFunction()->ObjCShouldCallSuper = false;
12347 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12348 const ObjCMethodDecl *InitMethod = nullptr;
12349 bool isDesignated =
12350 MD->isDesignatedInitializerForTheInterface(&InitMethod);
12351 assert(isDesignated && InitMethod);
12352 (void)isDesignated;
12354 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12355 auto IFace = MD->getClassInterface();
12358 auto SuperD = IFace->getSuperClass();
12361 return SuperD->getIdentifier() ==
12362 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12364 // Don't issue this warning for unavailable inits or direct subclasses
12366 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12367 Diag(MD->getLocation(),
12368 diag::warn_objc_designated_init_missing_super_call);
12369 Diag(InitMethod->getLocation(),
12370 diag::note_objc_designated_init_marked_here);
12372 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12374 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12375 // Don't issue this warning for unavaialable inits.
12376 if (!MD->isUnavailable())
12377 Diag(MD->getLocation(),
12378 diag::warn_objc_secondary_init_missing_init_call);
12379 getCurFunction()->ObjCWarnForNoInitDelegation = false;
12385 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12386 DiagnoseUnguardedAvailabilityViolations(dcl);
12388 assert(!getCurFunction()->ObjCShouldCallSuper &&
12389 "This should only be set for ObjC methods, which should have been "
12390 "handled in the block above.");
12392 // Verify and clean out per-function state.
12393 if (Body && (!FD || !FD->isDefaulted())) {
12394 // C++ constructors that have function-try-blocks can't have return
12395 // statements in the handlers of that block. (C++ [except.handle]p14)
12397 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12398 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12400 // Verify that gotos and switch cases don't jump into scopes illegally.
12401 if (getCurFunction()->NeedsScopeChecking() &&
12402 !PP.isCodeCompletionEnabled())
12403 DiagnoseInvalidJumps(Body);
12405 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12406 if (!Destructor->getParent()->isDependentType())
12407 CheckDestructor(Destructor);
12409 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12410 Destructor->getParent());
12413 // If any errors have occurred, clear out any temporaries that may have
12414 // been leftover. This ensures that these temporaries won't be picked up for
12415 // deletion in some later function.
12416 if (getDiagnostics().hasErrorOccurred() ||
12417 getDiagnostics().getSuppressAllDiagnostics()) {
12418 DiscardCleanupsInEvaluationContext();
12420 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12421 !isa<FunctionTemplateDecl>(dcl)) {
12422 // Since the body is valid, issue any analysis-based warnings that are
12424 ActivePolicy = &WP;
12427 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12428 (!CheckConstexprFunctionDecl(FD) ||
12429 !CheckConstexprFunctionBody(FD, Body)))
12430 FD->setInvalidDecl();
12432 if (FD && FD->hasAttr<NakedAttr>()) {
12433 for (const Stmt *S : Body->children()) {
12434 // Allow local register variables without initializer as they don't
12435 // require prologue.
12436 bool RegisterVariables = false;
12437 if (auto *DS = dyn_cast<DeclStmt>(S)) {
12438 for (const auto *Decl : DS->decls()) {
12439 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12440 RegisterVariables =
12441 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12442 if (!RegisterVariables)
12447 if (RegisterVariables)
12449 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12450 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12451 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12452 FD->setInvalidDecl();
12458 assert(ExprCleanupObjects.size() ==
12459 ExprEvalContexts.back().NumCleanupObjects &&
12460 "Leftover temporaries in function");
12461 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12462 assert(MaybeODRUseExprs.empty() &&
12463 "Leftover expressions for odr-use checking");
12466 if (!IsInstantiation)
12469 PopFunctionScopeInfo(ActivePolicy, dcl);
12470 // If any errors have occurred, clear out any temporaries that may have
12471 // been leftover. This ensures that these temporaries won't be picked up for
12472 // deletion in some later function.
12473 if (getDiagnostics().hasErrorOccurred()) {
12474 DiscardCleanupsInEvaluationContext();
12480 /// When we finish delayed parsing of an attribute, we must attach it to the
12482 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12483 ParsedAttributes &Attrs) {
12484 // Always attach attributes to the underlying decl.
12485 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12486 D = TD->getTemplatedDecl();
12487 ProcessDeclAttributeList(S, D, Attrs.getList());
12489 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12490 if (Method->isStatic())
12491 checkThisInStaticMemberFunctionAttributes(Method);
12494 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12495 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12496 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12497 IdentifierInfo &II, Scope *S) {
12498 // Before we produce a declaration for an implicitly defined
12499 // function, see whether there was a locally-scoped declaration of
12500 // this name as a function or variable. If so, use that
12501 // (non-visible) declaration, and complain about it.
12502 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12503 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12504 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12505 return ExternCPrev;
12508 // Extension in C99. Legal in C90, but warn about it.
12510 if (II.getName().startswith("__builtin_"))
12511 diag_id = diag::warn_builtin_unknown;
12512 else if (getLangOpts().C99)
12513 diag_id = diag::ext_implicit_function_decl;
12515 diag_id = diag::warn_implicit_function_decl;
12516 Diag(Loc, diag_id) << &II;
12518 // Because typo correction is expensive, only do it if the implicit
12519 // function declaration is going to be treated as an error.
12520 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12521 TypoCorrection Corrected;
12523 (Corrected = CorrectTypo(
12524 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12525 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12526 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12527 /*ErrorRecovery*/false);
12530 // Set a Declarator for the implicit definition: int foo();
12532 AttributeFactory attrFactory;
12533 DeclSpec DS(attrFactory);
12535 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12536 Context.getPrintingPolicy());
12537 (void)Error; // Silence warning.
12538 assert(!Error && "Error setting up implicit decl!");
12539 SourceLocation NoLoc;
12540 Declarator D(DS, Declarator::BlockContext);
12541 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12542 /*IsAmbiguous=*/false,
12543 /*LParenLoc=*/NoLoc,
12544 /*Params=*/nullptr,
12546 /*EllipsisLoc=*/NoLoc,
12547 /*RParenLoc=*/NoLoc,
12549 /*RefQualifierIsLvalueRef=*/true,
12550 /*RefQualifierLoc=*/NoLoc,
12551 /*ConstQualifierLoc=*/NoLoc,
12552 /*VolatileQualifierLoc=*/NoLoc,
12553 /*RestrictQualifierLoc=*/NoLoc,
12554 /*MutableLoc=*/NoLoc,
12556 /*ESpecRange=*/SourceRange(),
12557 /*Exceptions=*/nullptr,
12558 /*ExceptionRanges=*/nullptr,
12559 /*NumExceptions=*/0,
12560 /*NoexceptExpr=*/nullptr,
12561 /*ExceptionSpecTokens=*/nullptr,
12562 /*DeclsInPrototype=*/None,
12564 DS.getAttributes(),
12566 D.SetIdentifier(&II, Loc);
12568 // Insert this function into translation-unit scope.
12570 DeclContext *PrevDC = CurContext;
12571 CurContext = Context.getTranslationUnitDecl();
12573 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12576 CurContext = PrevDC;
12578 AddKnownFunctionAttributes(FD);
12583 /// \brief Adds any function attributes that we know a priori based on
12584 /// the declaration of this function.
12586 /// These attributes can apply both to implicitly-declared builtins
12587 /// (like __builtin___printf_chk) or to library-declared functions
12588 /// like NSLog or printf.
12590 /// We need to check for duplicate attributes both here and where user-written
12591 /// attributes are applied to declarations.
12592 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12593 if (FD->isInvalidDecl())
12596 // If this is a built-in function, map its builtin attributes to
12597 // actual attributes.
12598 if (unsigned BuiltinID = FD->getBuiltinID()) {
12599 // Handle printf-formatting attributes.
12600 unsigned FormatIdx;
12602 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12603 if (!FD->hasAttr<FormatAttr>()) {
12604 const char *fmt = "printf";
12605 unsigned int NumParams = FD->getNumParams();
12606 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12607 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12609 FD->addAttr(FormatAttr::CreateImplicit(Context,
12610 &Context.Idents.get(fmt),
12612 HasVAListArg ? 0 : FormatIdx+2,
12613 FD->getLocation()));
12616 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12618 if (!FD->hasAttr<FormatAttr>())
12619 FD->addAttr(FormatAttr::CreateImplicit(Context,
12620 &Context.Idents.get("scanf"),
12622 HasVAListArg ? 0 : FormatIdx+2,
12623 FD->getLocation()));
12626 // Mark const if we don't care about errno and that is the only
12627 // thing preventing the function from being const. This allows
12628 // IRgen to use LLVM intrinsics for such functions.
12629 if (!getLangOpts().MathErrno &&
12630 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12631 if (!FD->hasAttr<ConstAttr>())
12632 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12635 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12636 !FD->hasAttr<ReturnsTwiceAttr>())
12637 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12638 FD->getLocation()));
12639 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12640 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12641 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12642 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12643 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12644 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12645 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12646 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12647 // Add the appropriate attribute, depending on the CUDA compilation mode
12648 // and which target the builtin belongs to. For example, during host
12649 // compilation, aux builtins are __device__, while the rest are __host__.
12650 if (getLangOpts().CUDAIsDevice !=
12651 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12652 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12654 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12658 // If C++ exceptions are enabled but we are told extern "C" functions cannot
12659 // throw, add an implicit nothrow attribute to any extern "C" function we come
12661 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12662 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12663 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12664 if (!FPT || FPT->getExceptionSpecType() == EST_None)
12665 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12668 IdentifierInfo *Name = FD->getIdentifier();
12671 if ((!getLangOpts().CPlusPlus &&
12672 FD->getDeclContext()->isTranslationUnit()) ||
12673 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12674 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12675 LinkageSpecDecl::lang_c)) {
12676 // Okay: this could be a libc/libm/Objective-C function we know
12681 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12682 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12683 // target-specific builtins, perhaps?
12684 if (!FD->hasAttr<FormatAttr>())
12685 FD->addAttr(FormatAttr::CreateImplicit(Context,
12686 &Context.Idents.get("printf"), 2,
12687 Name->isStr("vasprintf") ? 0 : 3,
12688 FD->getLocation()));
12691 if (Name->isStr("__CFStringMakeConstantString")) {
12692 // We already have a __builtin___CFStringMakeConstantString,
12693 // but builds that use -fno-constant-cfstrings don't go through that.
12694 if (!FD->hasAttr<FormatArgAttr>())
12695 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12696 FD->getLocation()));
12700 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12701 TypeSourceInfo *TInfo) {
12702 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12703 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12706 assert(D.isInvalidType() && "no declarator info for valid type");
12707 TInfo = Context.getTrivialTypeSourceInfo(T);
12710 // Scope manipulation handled by caller.
12711 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12713 D.getIdentifierLoc(),
12717 // Bail out immediately if we have an invalid declaration.
12718 if (D.isInvalidType()) {
12719 NewTD->setInvalidDecl();
12723 if (D.getDeclSpec().isModulePrivateSpecified()) {
12724 if (CurContext->isFunctionOrMethod())
12725 Diag(NewTD->getLocation(), diag::err_module_private_local)
12726 << 2 << NewTD->getDeclName()
12727 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12728 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12730 NewTD->setModulePrivate();
12733 // C++ [dcl.typedef]p8:
12734 // If the typedef declaration defines an unnamed class (or
12735 // enum), the first typedef-name declared by the declaration
12736 // to be that class type (or enum type) is used to denote the
12737 // class type (or enum type) for linkage purposes only.
12738 // We need to check whether the type was declared in the declaration.
12739 switch (D.getDeclSpec().getTypeSpecType()) {
12742 case TST_interface:
12745 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12746 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12757 /// \brief Check that this is a valid underlying type for an enum declaration.
12758 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12759 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12760 QualType T = TI->getType();
12762 if (T->isDependentType())
12765 if (const BuiltinType *BT = T->getAs<BuiltinType>())
12766 if (BT->isInteger())
12769 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12773 /// Check whether this is a valid redeclaration of a previous enumeration.
12774 /// \return true if the redeclaration was invalid.
12775 bool Sema::CheckEnumRedeclaration(
12776 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12777 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12778 bool IsFixed = !EnumUnderlyingTy.isNull();
12780 if (IsScoped != Prev->isScoped()) {
12781 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12782 << Prev->isScoped();
12783 Diag(Prev->getLocation(), diag::note_previous_declaration);
12787 if (IsFixed && Prev->isFixed()) {
12788 if (!EnumUnderlyingTy->isDependentType() &&
12789 !Prev->getIntegerType()->isDependentType() &&
12790 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12791 Prev->getIntegerType())) {
12792 // TODO: Highlight the underlying type of the redeclaration.
12793 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12794 << EnumUnderlyingTy << Prev->getIntegerType();
12795 Diag(Prev->getLocation(), diag::note_previous_declaration)
12796 << Prev->getIntegerTypeRange();
12799 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12801 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12803 } else if (IsFixed != Prev->isFixed()) {
12804 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12805 << Prev->isFixed();
12806 Diag(Prev->getLocation(), diag::note_previous_declaration);
12813 /// \brief Get diagnostic %select index for tag kind for
12814 /// redeclaration diagnostic message.
12815 /// WARNING: Indexes apply to particular diagnostics only!
12817 /// \returns diagnostic %select index.
12818 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12820 case TTK_Struct: return 0;
12821 case TTK_Interface: return 1;
12822 case TTK_Class: return 2;
12823 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12827 /// \brief Determine if tag kind is a class-key compatible with
12828 /// class for redeclaration (class, struct, or __interface).
12830 /// \returns true iff the tag kind is compatible.
12831 static bool isClassCompatTagKind(TagTypeKind Tag)
12833 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12836 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12838 if (isa<TypedefDecl>(PrevDecl))
12839 return NTK_Typedef;
12840 else if (isa<TypeAliasDecl>(PrevDecl))
12841 return NTK_TypeAlias;
12842 else if (isa<ClassTemplateDecl>(PrevDecl))
12843 return NTK_Template;
12844 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12845 return NTK_TypeAliasTemplate;
12846 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12847 return NTK_TemplateTemplateArgument;
12850 case TTK_Interface:
12852 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12854 return NTK_NonUnion;
12856 return NTK_NonEnum;
12858 llvm_unreachable("invalid TTK");
12861 /// \brief Determine whether a tag with a given kind is acceptable
12862 /// as a redeclaration of the given tag declaration.
12864 /// \returns true if the new tag kind is acceptable, false otherwise.
12865 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12866 TagTypeKind NewTag, bool isDefinition,
12867 SourceLocation NewTagLoc,
12868 const IdentifierInfo *Name) {
12869 // C++ [dcl.type.elab]p3:
12870 // The class-key or enum keyword present in the
12871 // elaborated-type-specifier shall agree in kind with the
12872 // declaration to which the name in the elaborated-type-specifier
12873 // refers. This rule also applies to the form of
12874 // elaborated-type-specifier that declares a class-name or
12875 // friend class since it can be construed as referring to the
12876 // definition of the class. Thus, in any
12877 // elaborated-type-specifier, the enum keyword shall be used to
12878 // refer to an enumeration (7.2), the union class-key shall be
12879 // used to refer to a union (clause 9), and either the class or
12880 // struct class-key shall be used to refer to a class (clause 9)
12881 // declared using the class or struct class-key.
12882 TagTypeKind OldTag = Previous->getTagKind();
12883 if (!isDefinition || !isClassCompatTagKind(NewTag))
12884 if (OldTag == NewTag)
12887 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12888 // Warn about the struct/class tag mismatch.
12889 bool isTemplate = false;
12890 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12891 isTemplate = Record->getDescribedClassTemplate();
12893 if (inTemplateInstantiation()) {
12894 // In a template instantiation, do not offer fix-its for tag mismatches
12895 // since they usually mess up the template instead of fixing the problem.
12896 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12897 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12898 << getRedeclDiagFromTagKind(OldTag);
12902 if (isDefinition) {
12903 // On definitions, check previous tags and issue a fix-it for each
12904 // one that doesn't match the current tag.
12905 if (Previous->getDefinition()) {
12906 // Don't suggest fix-its for redefinitions.
12910 bool previousMismatch = false;
12911 for (auto I : Previous->redecls()) {
12912 if (I->getTagKind() != NewTag) {
12913 if (!previousMismatch) {
12914 previousMismatch = true;
12915 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12916 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12917 << getRedeclDiagFromTagKind(I->getTagKind());
12919 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12920 << getRedeclDiagFromTagKind(NewTag)
12921 << FixItHint::CreateReplacement(I->getInnerLocStart(),
12922 TypeWithKeyword::getTagTypeKindName(NewTag));
12928 // Check for a previous definition. If current tag and definition
12929 // are same type, do nothing. If no definition, but disagree with
12930 // with previous tag type, give a warning, but no fix-it.
12931 const TagDecl *Redecl = Previous->getDefinition() ?
12932 Previous->getDefinition() : Previous;
12933 if (Redecl->getTagKind() == NewTag) {
12937 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12938 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12939 << getRedeclDiagFromTagKind(OldTag);
12940 Diag(Redecl->getLocation(), diag::note_previous_use);
12942 // If there is a previous definition, suggest a fix-it.
12943 if (Previous->getDefinition()) {
12944 Diag(NewTagLoc, diag::note_struct_class_suggestion)
12945 << getRedeclDiagFromTagKind(Redecl->getTagKind())
12946 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12947 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12955 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12956 /// from an outer enclosing namespace or file scope inside a friend declaration.
12957 /// This should provide the commented out code in the following snippet:
12961 /// struct Y { friend struct /*N::*/ X; };
12964 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12965 SourceLocation NameLoc) {
12966 // While the decl is in a namespace, do repeated lookup of that name and see
12967 // if we get the same namespace back. If we do not, continue until
12968 // translation unit scope, at which point we have a fully qualified NNS.
12969 SmallVector<IdentifierInfo *, 4> Namespaces;
12970 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12971 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12972 // This tag should be declared in a namespace, which can only be enclosed by
12973 // other namespaces. Bail if there's an anonymous namespace in the chain.
12974 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12975 if (!Namespace || Namespace->isAnonymousNamespace())
12976 return FixItHint();
12977 IdentifierInfo *II = Namespace->getIdentifier();
12978 Namespaces.push_back(II);
12979 NamedDecl *Lookup = SemaRef.LookupSingleName(
12980 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12981 if (Lookup == Namespace)
12985 // Once we have all the namespaces, reverse them to go outermost first, and
12987 SmallString<64> Insertion;
12988 llvm::raw_svector_ostream OS(Insertion);
12989 if (DC->isTranslationUnit())
12991 std::reverse(Namespaces.begin(), Namespaces.end());
12992 for (auto *II : Namespaces)
12993 OS << II->getName() << "::";
12994 return FixItHint::CreateInsertion(NameLoc, Insertion);
12997 /// \brief Determine whether a tag originally declared in context \p OldDC can
12998 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12999 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13000 /// using-declaration).
13001 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13002 DeclContext *NewDC) {
13003 OldDC = OldDC->getRedeclContext();
13004 NewDC = NewDC->getRedeclContext();
13006 if (OldDC->Equals(NewDC))
13009 // In MSVC mode, we allow a redeclaration if the contexts are related (either
13010 // encloses the other).
13011 if (S.getLangOpts().MSVCCompat &&
13012 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13018 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
13019 /// former case, Name will be non-null. In the later case, Name will be null.
13020 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13021 /// reference/declaration/definition of a tag.
13023 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13024 /// trailing-type-specifier) other than one in an alias-declaration.
13026 /// \param SkipBody If non-null, will be set to indicate if the caller should
13027 /// skip the definition of this tag and treat it as if it were a declaration.
13028 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13029 SourceLocation KWLoc, CXXScopeSpec &SS,
13030 IdentifierInfo *Name, SourceLocation NameLoc,
13031 AttributeList *Attr, AccessSpecifier AS,
13032 SourceLocation ModulePrivateLoc,
13033 MultiTemplateParamsArg TemplateParameterLists,
13034 bool &OwnedDecl, bool &IsDependent,
13035 SourceLocation ScopedEnumKWLoc,
13036 bool ScopedEnumUsesClassTag,
13037 TypeResult UnderlyingType,
13038 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
13039 // If this is not a definition, it must have a name.
13040 IdentifierInfo *OrigName = Name;
13041 assert((Name != nullptr || TUK == TUK_Definition) &&
13042 "Nameless record must be a definition!");
13043 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13046 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13047 bool ScopedEnum = ScopedEnumKWLoc.isValid();
13049 // FIXME: Check member specializations more carefully.
13050 bool isMemberSpecialization = false;
13051 bool Invalid = false;
13053 // We only need to do this matching if we have template parameters
13054 // or a scope specifier, which also conveniently avoids this work
13055 // for non-C++ cases.
13056 if (TemplateParameterLists.size() > 0 ||
13057 (SS.isNotEmpty() && TUK != TUK_Reference)) {
13058 if (TemplateParameterList *TemplateParams =
13059 MatchTemplateParametersToScopeSpecifier(
13060 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13061 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13062 if (Kind == TTK_Enum) {
13063 Diag(KWLoc, diag::err_enum_template);
13067 if (TemplateParams->size() > 0) {
13068 // This is a declaration or definition of a class template (which may
13069 // be a member of another template).
13075 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13076 SS, Name, NameLoc, Attr,
13077 TemplateParams, AS,
13079 /*FriendLoc*/SourceLocation(),
13080 TemplateParameterLists.size()-1,
13081 TemplateParameterLists.data(),
13083 return Result.get();
13085 // The "template<>" header is extraneous.
13086 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13087 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13088 isMemberSpecialization = true;
13093 // Figure out the underlying type if this a enum declaration. We need to do
13094 // this early, because it's needed to detect if this is an incompatible
13096 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13097 bool EnumUnderlyingIsImplicit = false;
13099 if (Kind == TTK_Enum) {
13100 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13101 // No underlying type explicitly specified, or we failed to parse the
13102 // type, default to int.
13103 EnumUnderlying = Context.IntTy.getTypePtr();
13104 else if (UnderlyingType.get()) {
13105 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13106 // integral type; any cv-qualification is ignored.
13107 TypeSourceInfo *TI = nullptr;
13108 GetTypeFromParser(UnderlyingType.get(), &TI);
13109 EnumUnderlying = TI;
13111 if (CheckEnumUnderlyingType(TI))
13112 // Recover by falling back to int.
13113 EnumUnderlying = Context.IntTy.getTypePtr();
13115 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13116 UPPC_FixedUnderlyingType))
13117 EnumUnderlying = Context.IntTy.getTypePtr();
13119 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13120 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13121 // Microsoft enums are always of int type.
13122 EnumUnderlying = Context.IntTy.getTypePtr();
13123 EnumUnderlyingIsImplicit = true;
13128 DeclContext *SearchDC = CurContext;
13129 DeclContext *DC = CurContext;
13130 bool isStdBadAlloc = false;
13131 bool isStdAlignValT = false;
13133 RedeclarationKind Redecl = ForRedeclaration;
13134 if (TUK == TUK_Friend || TUK == TUK_Reference)
13135 Redecl = NotForRedeclaration;
13137 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13138 if (Name && SS.isNotEmpty()) {
13139 // We have a nested-name tag ('struct foo::bar').
13141 // Check for invalid 'foo::'.
13142 if (SS.isInvalid()) {
13144 goto CreateNewDecl;
13147 // If this is a friend or a reference to a class in a dependent
13148 // context, don't try to make a decl for it.
13149 if (TUK == TUK_Friend || TUK == TUK_Reference) {
13150 DC = computeDeclContext(SS, false);
13152 IsDependent = true;
13156 DC = computeDeclContext(SS, true);
13158 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13164 if (RequireCompleteDeclContext(SS, DC))
13168 // Look-up name inside 'foo::'.
13169 LookupQualifiedName(Previous, DC);
13171 if (Previous.isAmbiguous())
13174 if (Previous.empty()) {
13175 // Name lookup did not find anything. However, if the
13176 // nested-name-specifier refers to the current instantiation,
13177 // and that current instantiation has any dependent base
13178 // classes, we might find something at instantiation time: treat
13179 // this as a dependent elaborated-type-specifier.
13180 // But this only makes any sense for reference-like lookups.
13181 if (Previous.wasNotFoundInCurrentInstantiation() &&
13182 (TUK == TUK_Reference || TUK == TUK_Friend)) {
13183 IsDependent = true;
13187 // A tag 'foo::bar' must already exist.
13188 Diag(NameLoc, diag::err_not_tag_in_scope)
13189 << Kind << Name << DC << SS.getRange();
13192 goto CreateNewDecl;
13195 // C++14 [class.mem]p14:
13196 // If T is the name of a class, then each of the following shall have a
13197 // name different from T:
13198 // -- every member of class T that is itself a type
13199 if (TUK != TUK_Reference && TUK != TUK_Friend &&
13200 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13203 // If this is a named struct, check to see if there was a previous forward
13204 // declaration or definition.
13205 // FIXME: We're looking into outer scopes here, even when we
13206 // shouldn't be. Doing so can result in ambiguities that we
13207 // shouldn't be diagnosing.
13208 LookupName(Previous, S);
13210 // When declaring or defining a tag, ignore ambiguities introduced
13211 // by types using'ed into this scope.
13212 if (Previous.isAmbiguous() &&
13213 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13214 LookupResult::Filter F = Previous.makeFilter();
13215 while (F.hasNext()) {
13216 NamedDecl *ND = F.next();
13217 if (!ND->getDeclContext()->getRedeclContext()->Equals(
13218 SearchDC->getRedeclContext()))
13224 // C++11 [namespace.memdef]p3:
13225 // If the name in a friend declaration is neither qualified nor
13226 // a template-id and the declaration is a function or an
13227 // elaborated-type-specifier, the lookup to determine whether
13228 // the entity has been previously declared shall not consider
13229 // any scopes outside the innermost enclosing namespace.
13231 // MSVC doesn't implement the above rule for types, so a friend tag
13232 // declaration may be a redeclaration of a type declared in an enclosing
13233 // scope. They do implement this rule for friend functions.
13235 // Does it matter that this should be by scope instead of by
13236 // semantic context?
13237 if (!Previous.empty() && TUK == TUK_Friend) {
13238 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13239 LookupResult::Filter F = Previous.makeFilter();
13240 bool FriendSawTagOutsideEnclosingNamespace = false;
13241 while (F.hasNext()) {
13242 NamedDecl *ND = F.next();
13243 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13244 if (DC->isFileContext() &&
13245 !EnclosingNS->Encloses(ND->getDeclContext())) {
13246 if (getLangOpts().MSVCCompat)
13247 FriendSawTagOutsideEnclosingNamespace = true;
13254 // Diagnose this MSVC extension in the easy case where lookup would have
13255 // unambiguously found something outside the enclosing namespace.
13256 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13257 NamedDecl *ND = Previous.getFoundDecl();
13258 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13259 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13263 // Note: there used to be some attempt at recovery here.
13264 if (Previous.isAmbiguous())
13267 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13268 // FIXME: This makes sure that we ignore the contexts associated
13269 // with C structs, unions, and enums when looking for a matching
13270 // tag declaration or definition. See the similar lookup tweak
13271 // in Sema::LookupName; is there a better way to deal with this?
13272 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13273 SearchDC = SearchDC->getParent();
13277 if (Previous.isSingleResult() &&
13278 Previous.getFoundDecl()->isTemplateParameter()) {
13279 // Maybe we will complain about the shadowed template parameter.
13280 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13281 // Just pretend that we didn't see the previous declaration.
13285 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13286 DC->Equals(getStdNamespace())) {
13287 if (Name->isStr("bad_alloc")) {
13288 // This is a declaration of or a reference to "std::bad_alloc".
13289 isStdBadAlloc = true;
13291 // If std::bad_alloc has been implicitly declared (but made invisible to
13292 // name lookup), fill in this implicit declaration as the previous
13293 // declaration, so that the declarations get chained appropriately.
13294 if (Previous.empty() && StdBadAlloc)
13295 Previous.addDecl(getStdBadAlloc());
13296 } else if (Name->isStr("align_val_t")) {
13297 isStdAlignValT = true;
13298 if (Previous.empty() && StdAlignValT)
13299 Previous.addDecl(getStdAlignValT());
13303 // If we didn't find a previous declaration, and this is a reference
13304 // (or friend reference), move to the correct scope. In C++, we
13305 // also need to do a redeclaration lookup there, just in case
13306 // there's a shadow friend decl.
13307 if (Name && Previous.empty() &&
13308 (TUK == TUK_Reference || TUK == TUK_Friend)) {
13309 if (Invalid) goto CreateNewDecl;
13310 assert(SS.isEmpty());
13312 if (TUK == TUK_Reference) {
13313 // C++ [basic.scope.pdecl]p5:
13314 // -- for an elaborated-type-specifier of the form
13316 // class-key identifier
13318 // if the elaborated-type-specifier is used in the
13319 // decl-specifier-seq or parameter-declaration-clause of a
13320 // function defined in namespace scope, the identifier is
13321 // declared as a class-name in the namespace that contains
13322 // the declaration; otherwise, except as a friend
13323 // declaration, the identifier is declared in the smallest
13324 // non-class, non-function-prototype scope that contains the
13327 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13328 // C structs and unions.
13330 // It is an error in C++ to declare (rather than define) an enum
13331 // type, including via an elaborated type specifier. We'll
13332 // diagnose that later; for now, declare the enum in the same
13333 // scope as we would have picked for any other tag type.
13335 // GNU C also supports this behavior as part of its incomplete
13336 // enum types extension, while GNU C++ does not.
13338 // Find the context where we'll be declaring the tag.
13339 // FIXME: We would like to maintain the current DeclContext as the
13340 // lexical context,
13341 SearchDC = getTagInjectionContext(SearchDC);
13343 // Find the scope where we'll be declaring the tag.
13344 S = getTagInjectionScope(S, getLangOpts());
13346 assert(TUK == TUK_Friend);
13347 // C++ [namespace.memdef]p3:
13348 // If a friend declaration in a non-local class first declares a
13349 // class or function, the friend class or function is a member of
13350 // the innermost enclosing namespace.
13351 SearchDC = SearchDC->getEnclosingNamespaceContext();
13354 // In C++, we need to do a redeclaration lookup to properly
13355 // diagnose some problems.
13356 // FIXME: redeclaration lookup is also used (with and without C++) to find a
13357 // hidden declaration so that we don't get ambiguity errors when using a
13358 // type declared by an elaborated-type-specifier. In C that is not correct
13359 // and we should instead merge compatible types found by lookup.
13360 if (getLangOpts().CPlusPlus) {
13361 Previous.setRedeclarationKind(ForRedeclaration);
13362 LookupQualifiedName(Previous, SearchDC);
13364 Previous.setRedeclarationKind(ForRedeclaration);
13365 LookupName(Previous, S);
13369 // If we have a known previous declaration to use, then use it.
13370 if (Previous.empty() && SkipBody && SkipBody->Previous)
13371 Previous.addDecl(SkipBody->Previous);
13373 if (!Previous.empty()) {
13374 NamedDecl *PrevDecl = Previous.getFoundDecl();
13375 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13377 // It's okay to have a tag decl in the same scope as a typedef
13378 // which hides a tag decl in the same scope. Finding this
13379 // insanity with a redeclaration lookup can only actually happen
13382 // This is also okay for elaborated-type-specifiers, which is
13383 // technically forbidden by the current standard but which is
13384 // okay according to the likely resolution of an open issue;
13385 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13386 if (getLangOpts().CPlusPlus) {
13387 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13388 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13389 TagDecl *Tag = TT->getDecl();
13390 if (Tag->getDeclName() == Name &&
13391 Tag->getDeclContext()->getRedeclContext()
13392 ->Equals(TD->getDeclContext()->getRedeclContext())) {
13395 Previous.addDecl(Tag);
13396 Previous.resolveKind();
13402 // If this is a redeclaration of a using shadow declaration, it must
13403 // declare a tag in the same context. In MSVC mode, we allow a
13404 // redefinition if either context is within the other.
13405 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13406 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13407 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13408 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13409 !(OldTag && isAcceptableTagRedeclContext(
13410 *this, OldTag->getDeclContext(), SearchDC))) {
13411 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13412 Diag(Shadow->getTargetDecl()->getLocation(),
13413 diag::note_using_decl_target);
13414 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13416 // Recover by ignoring the old declaration.
13418 goto CreateNewDecl;
13422 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13423 // If this is a use of a previous tag, or if the tag is already declared
13424 // in the same scope (so that the definition/declaration completes or
13425 // rementions the tag), reuse the decl.
13426 if (TUK == TUK_Reference || TUK == TUK_Friend ||
13427 isDeclInScope(DirectPrevDecl, SearchDC, S,
13428 SS.isNotEmpty() || isMemberSpecialization)) {
13429 // Make sure that this wasn't declared as an enum and now used as a
13430 // struct or something similar.
13431 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13432 TUK == TUK_Definition, KWLoc,
13434 bool SafeToContinue
13435 = (PrevTagDecl->getTagKind() != TTK_Enum &&
13437 if (SafeToContinue)
13438 Diag(KWLoc, diag::err_use_with_wrong_tag)
13440 << FixItHint::CreateReplacement(SourceRange(KWLoc),
13441 PrevTagDecl->getKindName());
13443 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13444 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13446 if (SafeToContinue)
13447 Kind = PrevTagDecl->getTagKind();
13449 // Recover by making this an anonymous redefinition.
13456 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13457 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13459 // If this is an elaborated-type-specifier for a scoped enumeration,
13460 // the 'class' keyword is not necessary and not permitted.
13461 if (TUK == TUK_Reference || TUK == TUK_Friend) {
13463 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13464 << PrevEnum->isScoped()
13465 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13466 return PrevTagDecl;
13469 QualType EnumUnderlyingTy;
13470 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13471 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13472 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13473 EnumUnderlyingTy = QualType(T, 0);
13475 // All conflicts with previous declarations are recovered by
13476 // returning the previous declaration, unless this is a definition,
13477 // in which case we want the caller to bail out.
13478 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13479 ScopedEnum, EnumUnderlyingTy,
13480 EnumUnderlyingIsImplicit, PrevEnum))
13481 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13484 // C++11 [class.mem]p1:
13485 // A member shall not be declared twice in the member-specification,
13486 // except that a nested class or member class template can be declared
13487 // and then later defined.
13488 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13489 S->isDeclScope(PrevDecl)) {
13490 Diag(NameLoc, diag::ext_member_redeclared);
13491 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13495 // If this is a use, just return the declaration we found, unless
13496 // we have attributes.
13497 if (TUK == TUK_Reference || TUK == TUK_Friend) {
13499 // FIXME: Diagnose these attributes. For now, we create a new
13500 // declaration to hold them.
13501 } else if (TUK == TUK_Reference &&
13502 (PrevTagDecl->getFriendObjectKind() ==
13503 Decl::FOK_Undeclared ||
13504 PrevDecl->getOwningModule() != getCurrentModule()) &&
13506 // This declaration is a reference to an existing entity, but
13507 // has different visibility from that entity: it either makes
13508 // a friend visible or it makes a type visible in a new module.
13509 // In either case, create a new declaration. We only do this if
13510 // the declaration would have meant the same thing if no prior
13511 // declaration were found, that is, if it was found in the same
13512 // scope where we would have injected a declaration.
13513 if (!getTagInjectionContext(CurContext)->getRedeclContext()
13514 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13515 return PrevTagDecl;
13516 // This is in the injected scope, create a new declaration in
13518 S = getTagInjectionScope(S, getLangOpts());
13520 return PrevTagDecl;
13524 // Diagnose attempts to redefine a tag.
13525 if (TUK == TUK_Definition) {
13526 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13527 // If we're defining a specialization and the previous definition
13528 // is from an implicit instantiation, don't emit an error
13529 // here; we'll catch this in the general case below.
13530 bool IsExplicitSpecializationAfterInstantiation = false;
13531 if (isMemberSpecialization) {
13532 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13533 IsExplicitSpecializationAfterInstantiation =
13534 RD->getTemplateSpecializationKind() !=
13535 TSK_ExplicitSpecialization;
13536 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13537 IsExplicitSpecializationAfterInstantiation =
13538 ED->getTemplateSpecializationKind() !=
13539 TSK_ExplicitSpecialization;
13542 NamedDecl *Hidden = nullptr;
13543 if (SkipBody && getLangOpts().CPlusPlus &&
13544 !hasVisibleDefinition(Def, &Hidden)) {
13545 // There is a definition of this tag, but it is not visible. We
13546 // explicitly make use of C++'s one definition rule here, and
13547 // assume that this definition is identical to the hidden one
13548 // we already have. Make the existing definition visible and
13549 // use it in place of this one.
13550 SkipBody->ShouldSkip = true;
13551 makeMergedDefinitionVisible(Hidden);
13553 } else if (!IsExplicitSpecializationAfterInstantiation) {
13554 // A redeclaration in function prototype scope in C isn't
13555 // visible elsewhere, so merely issue a warning.
13556 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13557 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13559 Diag(NameLoc, diag::err_redefinition) << Name;
13560 notePreviousDefinition(Def,
13561 NameLoc.isValid() ? NameLoc : KWLoc);
13562 // If this is a redefinition, recover by making this
13563 // struct be anonymous, which will make any later
13564 // references get the previous definition.
13570 // If the type is currently being defined, complain
13571 // about a nested redefinition.
13572 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13573 if (TD->isBeingDefined()) {
13574 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13575 Diag(PrevTagDecl->getLocation(),
13576 diag::note_previous_definition);
13583 // Okay, this is definition of a previously declared or referenced
13584 // tag. We're going to create a new Decl for it.
13587 // Okay, we're going to make a redeclaration. If this is some kind
13588 // of reference, make sure we build the redeclaration in the same DC
13589 // as the original, and ignore the current access specifier.
13590 if (TUK == TUK_Friend || TUK == TUK_Reference) {
13591 SearchDC = PrevTagDecl->getDeclContext();
13595 // If we get here we have (another) forward declaration or we
13596 // have a definition. Just create a new decl.
13599 // If we get here, this is a definition of a new tag type in a nested
13600 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13601 // new decl/type. We set PrevDecl to NULL so that the entities
13602 // have distinct types.
13605 // If we get here, we're going to create a new Decl. If PrevDecl
13606 // is non-NULL, it's a definition of the tag declared by
13607 // PrevDecl. If it's NULL, we have a new definition.
13609 // Otherwise, PrevDecl is not a tag, but was found with tag
13610 // lookup. This is only actually possible in C++, where a few
13611 // things like templates still live in the tag namespace.
13613 // Use a better diagnostic if an elaborated-type-specifier
13614 // found the wrong kind of type on the first
13615 // (non-redeclaration) lookup.
13616 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13617 !Previous.isForRedeclaration()) {
13618 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13619 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13621 Diag(PrevDecl->getLocation(), diag::note_declared_at);
13624 // Otherwise, only diagnose if the declaration is in scope.
13625 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13626 SS.isNotEmpty() || isMemberSpecialization)) {
13629 // Diagnose implicit declarations introduced by elaborated types.
13630 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13631 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13632 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13633 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13636 // Otherwise it's a declaration. Call out a particularly common
13638 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13640 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13641 Diag(NameLoc, diag::err_tag_definition_of_typedef)
13642 << Name << Kind << TND->getUnderlyingType();
13643 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13646 // Otherwise, diagnose.
13648 // The tag name clashes with something else in the target scope,
13649 // issue an error and recover by making this tag be anonymous.
13650 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13651 notePreviousDefinition(PrevDecl, NameLoc);
13656 // The existing declaration isn't relevant to us; we're in a
13657 // new scope, so clear out the previous declaration.
13664 TagDecl *PrevDecl = nullptr;
13665 if (Previous.isSingleResult())
13666 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13668 // If there is an identifier, use the location of the identifier as the
13669 // location of the decl, otherwise use the location of the struct/union
13671 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13673 // Otherwise, create a new declaration. If there is a previous
13674 // declaration of the same entity, the two will be linked via
13678 bool IsForwardReference = false;
13679 if (Kind == TTK_Enum) {
13680 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13681 // enum X { A, B, C } D; D should chain to X.
13682 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13683 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13684 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13686 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13687 StdAlignValT = cast<EnumDecl>(New);
13689 // If this is an undefined enum, warn.
13690 if (TUK != TUK_Definition && !Invalid) {
13692 if (!EnumUnderlyingIsImplicit &&
13693 (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13694 cast<EnumDecl>(New)->isFixed()) {
13695 // C++0x: 7.2p2: opaque-enum-declaration.
13696 // Conflicts are diagnosed above. Do nothing.
13698 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13699 Diag(Loc, diag::ext_forward_ref_enum_def)
13701 Diag(Def->getLocation(), diag::note_previous_definition);
13703 unsigned DiagID = diag::ext_forward_ref_enum;
13704 if (getLangOpts().MSVCCompat)
13705 DiagID = diag::ext_ms_forward_ref_enum;
13706 else if (getLangOpts().CPlusPlus)
13707 DiagID = diag::err_forward_ref_enum;
13710 // If this is a forward-declared reference to an enumeration, make a
13711 // note of it; we won't actually be introducing the declaration into
13712 // the declaration context.
13713 if (TUK == TUK_Reference)
13714 IsForwardReference = true;
13718 if (EnumUnderlying) {
13719 EnumDecl *ED = cast<EnumDecl>(New);
13720 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13721 ED->setIntegerTypeSourceInfo(TI);
13723 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13724 ED->setPromotionType(ED->getIntegerType());
13727 // struct/union/class
13729 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13730 // struct X { int A; } D; D should chain to X.
13731 if (getLangOpts().CPlusPlus) {
13732 // FIXME: Look for a way to use RecordDecl for simple structs.
13733 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13734 cast_or_null<CXXRecordDecl>(PrevDecl));
13736 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13737 StdBadAlloc = cast<CXXRecordDecl>(New);
13739 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13740 cast_or_null<RecordDecl>(PrevDecl));
13743 // C++11 [dcl.type]p3:
13744 // A type-specifier-seq shall not define a class or enumeration [...].
13745 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13746 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13747 << Context.getTagDeclType(New);
13751 // Maybe add qualifier info.
13752 if (SS.isNotEmpty()) {
13754 // If this is either a declaration or a definition, check the
13755 // nested-name-specifier against the current context. We don't do this
13756 // for explicit specializations, because they have similar checking
13757 // (with more specific diagnostics) in the call to
13758 // CheckMemberSpecialization, below.
13759 if (!isMemberSpecialization &&
13760 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13761 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13764 New->setQualifierInfo(SS.getWithLocInContext(Context));
13765 if (TemplateParameterLists.size() > 0) {
13766 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13773 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13774 // Add alignment attributes if necessary; these attributes are checked when
13775 // the ASTContext lays out the structure.
13777 // It is important for implementing the correct semantics that this
13778 // happen here (in act on tag decl). The #pragma pack stack is
13779 // maintained as a result of parser callbacks which can occur at
13780 // many points during the parsing of a struct declaration (because
13781 // the #pragma tokens are effectively skipped over during the
13782 // parsing of the struct).
13783 if (TUK == TUK_Definition) {
13784 AddAlignmentAttributesForRecord(RD);
13785 AddMsStructLayoutForRecord(RD);
13789 if (ModulePrivateLoc.isValid()) {
13790 if (isMemberSpecialization)
13791 Diag(New->getLocation(), diag::err_module_private_specialization)
13793 << FixItHint::CreateRemoval(ModulePrivateLoc);
13794 // __module_private__ does not apply to local classes. However, we only
13795 // diagnose this as an error when the declaration specifiers are
13796 // freestanding. Here, we just ignore the __module_private__.
13797 else if (!SearchDC->isFunctionOrMethod())
13798 New->setModulePrivate();
13801 // If this is a specialization of a member class (of a class template),
13802 // check the specialization.
13803 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13806 // If we're declaring or defining a tag in function prototype scope in C,
13807 // note that this type can only be used within the function and add it to
13808 // the list of decls to inject into the function definition scope.
13809 if ((Name || Kind == TTK_Enum) &&
13810 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13811 if (getLangOpts().CPlusPlus) {
13812 // C++ [dcl.fct]p6:
13813 // Types shall not be defined in return or parameter types.
13814 if (TUK == TUK_Definition && !IsTypeSpecifier) {
13815 Diag(Loc, diag::err_type_defined_in_param_type)
13819 } else if (!PrevDecl) {
13820 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13825 New->setInvalidDecl();
13827 // Set the lexical context. If the tag has a C++ scope specifier, the
13828 // lexical context will be different from the semantic context.
13829 New->setLexicalDeclContext(CurContext);
13831 // Mark this as a friend decl if applicable.
13832 // In Microsoft mode, a friend declaration also acts as a forward
13833 // declaration so we always pass true to setObjectOfFriendDecl to make
13834 // the tag name visible.
13835 if (TUK == TUK_Friend)
13836 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13838 // Set the access specifier.
13839 if (!Invalid && SearchDC->isRecord())
13840 SetMemberAccessSpecifier(New, PrevDecl, AS);
13842 if (TUK == TUK_Definition)
13843 New->startDefinition();
13846 ProcessDeclAttributeList(S, New, Attr);
13847 AddPragmaAttributes(S, New);
13849 // If this has an identifier, add it to the scope stack.
13850 if (TUK == TUK_Friend) {
13851 // We might be replacing an existing declaration in the lookup tables;
13852 // if so, borrow its access specifier.
13854 New->setAccess(PrevDecl->getAccess());
13856 DeclContext *DC = New->getDeclContext()->getRedeclContext();
13857 DC->makeDeclVisibleInContext(New);
13858 if (Name) // can be null along some error paths
13859 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13860 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13862 S = getNonFieldDeclScope(S);
13863 PushOnScopeChains(New, S, !IsForwardReference);
13864 if (IsForwardReference)
13865 SearchDC->makeDeclVisibleInContext(New);
13867 CurContext->addDecl(New);
13870 // If this is the C FILE type, notify the AST context.
13871 if (IdentifierInfo *II = New->getIdentifier())
13872 if (!New->isInvalidDecl() &&
13873 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13875 Context.setFILEDecl(New);
13878 mergeDeclAttributes(New, PrevDecl);
13880 // If there's a #pragma GCC visibility in scope, set the visibility of this
13882 AddPushedVisibilityAttribute(New);
13884 if (isMemberSpecialization && !New->isInvalidDecl())
13885 CompleteMemberSpecialization(New, Previous);
13888 // In C++, don't return an invalid declaration. We can't recover well from
13889 // the cases where we make the type anonymous.
13890 if (Invalid && getLangOpts().CPlusPlus) {
13891 if (New->isBeingDefined())
13892 if (auto RD = dyn_cast<RecordDecl>(New))
13893 RD->completeDefinition();
13900 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13901 AdjustDeclIfTemplate(TagD);
13902 TagDecl *Tag = cast<TagDecl>(TagD);
13904 // Enter the tag context.
13905 PushDeclContext(S, Tag);
13907 ActOnDocumentableDecl(TagD);
13909 // If there's a #pragma GCC visibility in scope, set the visibility of this
13911 AddPushedVisibilityAttribute(Tag);
13914 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13915 assert(isa<ObjCContainerDecl>(IDecl) &&
13916 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13917 DeclContext *OCD = cast<DeclContext>(IDecl);
13918 assert(getContainingDC(OCD) == CurContext &&
13919 "The next DeclContext should be lexically contained in the current one.");
13924 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13925 SourceLocation FinalLoc,
13926 bool IsFinalSpelledSealed,
13927 SourceLocation LBraceLoc) {
13928 AdjustDeclIfTemplate(TagD);
13929 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13931 FieldCollector->StartClass();
13933 if (!Record->getIdentifier())
13936 if (FinalLoc.isValid())
13937 Record->addAttr(new (Context)
13938 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13941 // [...] The class-name is also inserted into the scope of the
13942 // class itself; this is known as the injected-class-name. For
13943 // purposes of access checking, the injected-class-name is treated
13944 // as if it were a public member name.
13945 CXXRecordDecl *InjectedClassName
13946 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13947 Record->getLocStart(), Record->getLocation(),
13948 Record->getIdentifier(),
13949 /*PrevDecl=*/nullptr,
13950 /*DelayTypeCreation=*/true);
13951 Context.getTypeDeclType(InjectedClassName, Record);
13952 InjectedClassName->setImplicit();
13953 InjectedClassName->setAccess(AS_public);
13954 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13955 InjectedClassName->setDescribedClassTemplate(Template);
13956 PushOnScopeChains(InjectedClassName, S);
13957 assert(InjectedClassName->isInjectedClassName() &&
13958 "Broken injected-class-name");
13961 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13962 SourceRange BraceRange) {
13963 AdjustDeclIfTemplate(TagD);
13964 TagDecl *Tag = cast<TagDecl>(TagD);
13965 Tag->setBraceRange(BraceRange);
13967 // Make sure we "complete" the definition even it is invalid.
13968 if (Tag->isBeingDefined()) {
13969 assert(Tag->isInvalidDecl() && "We should already have completed it");
13970 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13971 RD->completeDefinition();
13974 if (isa<CXXRecordDecl>(Tag)) {
13975 FieldCollector->FinishClass();
13978 // Exit this scope of this tag's definition.
13981 if (getCurLexicalContext()->isObjCContainer() &&
13982 Tag->getDeclContext()->isFileContext())
13983 Tag->setTopLevelDeclInObjCContainer();
13985 // Notify the consumer that we've defined a tag.
13986 if (!Tag->isInvalidDecl())
13987 Consumer.HandleTagDeclDefinition(Tag);
13990 void Sema::ActOnObjCContainerFinishDefinition() {
13991 // Exit this scope of this interface definition.
13995 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13996 assert(DC == CurContext && "Mismatch of container contexts");
13997 OriginalLexicalContext = DC;
13998 ActOnObjCContainerFinishDefinition();
14001 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14002 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14003 OriginalLexicalContext = nullptr;
14006 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14007 AdjustDeclIfTemplate(TagD);
14008 TagDecl *Tag = cast<TagDecl>(TagD);
14009 Tag->setInvalidDecl();
14011 // Make sure we "complete" the definition even it is invalid.
14012 if (Tag->isBeingDefined()) {
14013 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14014 RD->completeDefinition();
14017 // We're undoing ActOnTagStartDefinition here, not
14018 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14019 // the FieldCollector.
14024 // Note that FieldName may be null for anonymous bitfields.
14025 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14026 IdentifierInfo *FieldName,
14027 QualType FieldTy, bool IsMsStruct,
14028 Expr *BitWidth, bool *ZeroWidth) {
14029 // Default to true; that shouldn't confuse checks for emptiness
14033 // C99 6.7.2.1p4 - verify the field type.
14034 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14035 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14036 // Handle incomplete types with specific error.
14037 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14038 return ExprError();
14040 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14041 << FieldName << FieldTy << BitWidth->getSourceRange();
14042 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14043 << FieldTy << BitWidth->getSourceRange();
14044 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14045 UPPC_BitFieldWidth))
14046 return ExprError();
14048 // If the bit-width is type- or value-dependent, don't try to check
14050 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14053 llvm::APSInt Value;
14054 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14055 if (ICE.isInvalid())
14057 BitWidth = ICE.get();
14059 if (Value != 0 && ZeroWidth)
14060 *ZeroWidth = false;
14062 // Zero-width bitfield is ok for anonymous field.
14063 if (Value == 0 && FieldName)
14064 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14066 if (Value.isSigned() && Value.isNegative()) {
14068 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14069 << FieldName << Value.toString(10);
14070 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14071 << Value.toString(10);
14074 if (!FieldTy->isDependentType()) {
14075 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14076 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14077 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14079 // Over-wide bitfields are an error in C or when using the MSVC bitfield
14081 bool CStdConstraintViolation =
14082 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14083 bool MSBitfieldViolation =
14084 Value.ugt(TypeStorageSize) &&
14085 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14086 if (CStdConstraintViolation || MSBitfieldViolation) {
14087 unsigned DiagWidth =
14088 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14090 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14091 << FieldName << (unsigned)Value.getZExtValue()
14092 << !CStdConstraintViolation << DiagWidth;
14094 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14095 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14099 // Warn on types where the user might conceivably expect to get all
14100 // specified bits as value bits: that's all integral types other than
14102 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14104 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14105 << FieldName << (unsigned)Value.getZExtValue()
14106 << (unsigned)TypeWidth;
14108 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14109 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14116 /// ActOnField - Each field of a C struct/union is passed into this in order
14117 /// to create a FieldDecl object for it.
14118 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14119 Declarator &D, Expr *BitfieldWidth) {
14120 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14121 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14122 /*InitStyle=*/ICIS_NoInit, AS_public);
14126 /// HandleField - Analyze a field of a C struct or a C++ data member.
14128 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14129 SourceLocation DeclStart,
14130 Declarator &D, Expr *BitWidth,
14131 InClassInitStyle InitStyle,
14132 AccessSpecifier AS) {
14133 if (D.isDecompositionDeclarator()) {
14134 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14135 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14136 << Decomp.getSourceRange();
14140 IdentifierInfo *II = D.getIdentifier();
14141 SourceLocation Loc = DeclStart;
14142 if (II) Loc = D.getIdentifierLoc();
14144 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14145 QualType T = TInfo->getType();
14146 if (getLangOpts().CPlusPlus) {
14147 CheckExtraCXXDefaultArguments(D);
14149 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14150 UPPC_DataMemberType)) {
14151 D.setInvalidType();
14153 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14157 // TR 18037 does not allow fields to be declared with address spaces.
14158 if (T.getQualifiers().hasAddressSpace()) {
14159 Diag(Loc, diag::err_field_with_address_space);
14160 D.setInvalidType();
14163 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14164 // used as structure or union field: image, sampler, event or block types.
14165 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14166 T->isSamplerT() || T->isBlockPointerType())) {
14167 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14168 D.setInvalidType();
14171 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14173 if (D.getDeclSpec().isInlineSpecified())
14174 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14175 << getLangOpts().CPlusPlus1z;
14176 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14177 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14178 diag::err_invalid_thread)
14179 << DeclSpec::getSpecifierName(TSCS);
14181 // Check to see if this name was declared as a member previously
14182 NamedDecl *PrevDecl = nullptr;
14183 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14184 LookupName(Previous, S);
14185 switch (Previous.getResultKind()) {
14186 case LookupResult::Found:
14187 case LookupResult::FoundUnresolvedValue:
14188 PrevDecl = Previous.getAsSingle<NamedDecl>();
14191 case LookupResult::FoundOverloaded:
14192 PrevDecl = Previous.getRepresentativeDecl();
14195 case LookupResult::NotFound:
14196 case LookupResult::NotFoundInCurrentInstantiation:
14197 case LookupResult::Ambiguous:
14200 Previous.suppressDiagnostics();
14202 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14203 // Maybe we will complain about the shadowed template parameter.
14204 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14205 // Just pretend that we didn't see the previous declaration.
14206 PrevDecl = nullptr;
14209 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14210 PrevDecl = nullptr;
14213 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14214 SourceLocation TSSL = D.getLocStart();
14216 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14217 TSSL, AS, PrevDecl, &D);
14219 if (NewFD->isInvalidDecl())
14220 Record->setInvalidDecl();
14222 if (D.getDeclSpec().isModulePrivateSpecified())
14223 NewFD->setModulePrivate();
14225 if (NewFD->isInvalidDecl() && PrevDecl) {
14226 // Don't introduce NewFD into scope; there's already something
14227 // with the same name in the same scope.
14229 PushOnScopeChains(NewFD, S);
14231 Record->addDecl(NewFD);
14236 /// \brief Build a new FieldDecl and check its well-formedness.
14238 /// This routine builds a new FieldDecl given the fields name, type,
14239 /// record, etc. \p PrevDecl should refer to any previous declaration
14240 /// with the same name and in the same scope as the field to be
14243 /// \returns a new FieldDecl.
14245 /// \todo The Declarator argument is a hack. It will be removed once
14246 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14247 TypeSourceInfo *TInfo,
14248 RecordDecl *Record, SourceLocation Loc,
14249 bool Mutable, Expr *BitWidth,
14250 InClassInitStyle InitStyle,
14251 SourceLocation TSSL,
14252 AccessSpecifier AS, NamedDecl *PrevDecl,
14254 IdentifierInfo *II = Name.getAsIdentifierInfo();
14255 bool InvalidDecl = false;
14256 if (D) InvalidDecl = D->isInvalidType();
14258 // If we receive a broken type, recover by assuming 'int' and
14259 // marking this declaration as invalid.
14261 InvalidDecl = true;
14265 QualType EltTy = Context.getBaseElementType(T);
14266 if (!EltTy->isDependentType()) {
14267 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14268 // Fields of incomplete type force their record to be invalid.
14269 Record->setInvalidDecl();
14270 InvalidDecl = true;
14273 EltTy->isIncompleteType(&Def);
14274 if (Def && Def->isInvalidDecl()) {
14275 Record->setInvalidDecl();
14276 InvalidDecl = true;
14281 // OpenCL v1.2 s6.9.c: bitfields are not supported.
14282 if (BitWidth && getLangOpts().OpenCL) {
14283 Diag(Loc, diag::err_opencl_bitfields);
14284 InvalidDecl = true;
14287 // C99 6.7.2.1p8: A member of a structure or union may have any type other
14288 // than a variably modified type.
14289 if (!InvalidDecl && T->isVariablyModifiedType()) {
14290 bool SizeIsNegative;
14291 llvm::APSInt Oversized;
14293 TypeSourceInfo *FixedTInfo =
14294 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14298 Diag(Loc, diag::warn_illegal_constant_array_size);
14299 TInfo = FixedTInfo;
14300 T = FixedTInfo->getType();
14302 if (SizeIsNegative)
14303 Diag(Loc, diag::err_typecheck_negative_array_size);
14304 else if (Oversized.getBoolValue())
14305 Diag(Loc, diag::err_array_too_large)
14306 << Oversized.toString(10);
14308 Diag(Loc, diag::err_typecheck_field_variable_size);
14309 InvalidDecl = true;
14313 // Fields can not have abstract class types
14314 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14315 diag::err_abstract_type_in_decl,
14316 AbstractFieldType))
14317 InvalidDecl = true;
14319 bool ZeroWidth = false;
14321 BitWidth = nullptr;
14322 // If this is declared as a bit-field, check the bit-field.
14324 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14327 InvalidDecl = true;
14328 BitWidth = nullptr;
14333 // Check that 'mutable' is consistent with the type of the declaration.
14334 if (!InvalidDecl && Mutable) {
14335 unsigned DiagID = 0;
14336 if (T->isReferenceType())
14337 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14338 : diag::err_mutable_reference;
14339 else if (T.isConstQualified())
14340 DiagID = diag::err_mutable_const;
14343 SourceLocation ErrLoc = Loc;
14344 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14345 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14346 Diag(ErrLoc, DiagID);
14347 if (DiagID != diag::ext_mutable_reference) {
14349 InvalidDecl = true;
14354 // C++11 [class.union]p8 (DR1460):
14355 // At most one variant member of a union may have a
14356 // brace-or-equal-initializer.
14357 if (InitStyle != ICIS_NoInit)
14358 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14360 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14361 BitWidth, Mutable, InitStyle);
14363 NewFD->setInvalidDecl();
14365 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14366 Diag(Loc, diag::err_duplicate_member) << II;
14367 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14368 NewFD->setInvalidDecl();
14371 if (!InvalidDecl && getLangOpts().CPlusPlus) {
14372 if (Record->isUnion()) {
14373 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14374 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14375 if (RDecl->getDefinition()) {
14376 // C++ [class.union]p1: An object of a class with a non-trivial
14377 // constructor, a non-trivial copy constructor, a non-trivial
14378 // destructor, or a non-trivial copy assignment operator
14379 // cannot be a member of a union, nor can an array of such
14381 if (CheckNontrivialField(NewFD))
14382 NewFD->setInvalidDecl();
14386 // C++ [class.union]p1: If a union contains a member of reference type,
14387 // the program is ill-formed, except when compiling with MSVC extensions
14389 if (EltTy->isReferenceType()) {
14390 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14391 diag::ext_union_member_of_reference_type :
14392 diag::err_union_member_of_reference_type)
14393 << NewFD->getDeclName() << EltTy;
14394 if (!getLangOpts().MicrosoftExt)
14395 NewFD->setInvalidDecl();
14400 // FIXME: We need to pass in the attributes given an AST
14401 // representation, not a parser representation.
14403 // FIXME: The current scope is almost... but not entirely... correct here.
14404 ProcessDeclAttributes(getCurScope(), NewFD, *D);
14406 if (NewFD->hasAttrs())
14407 CheckAlignasUnderalignment(NewFD);
14410 // In auto-retain/release, infer strong retension for fields of
14411 // retainable type.
14412 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14413 NewFD->setInvalidDecl();
14415 if (T.isObjCGCWeak())
14416 Diag(Loc, diag::warn_attribute_weak_on_field);
14418 NewFD->setAccess(AS);
14422 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14424 assert(getLangOpts().CPlusPlus && "valid check only for C++");
14426 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14429 QualType EltTy = Context.getBaseElementType(FD->getType());
14430 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14431 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14432 if (RDecl->getDefinition()) {
14433 // We check for copy constructors before constructors
14434 // because otherwise we'll never get complaints about
14435 // copy constructors.
14437 CXXSpecialMember member = CXXInvalid;
14438 // We're required to check for any non-trivial constructors. Since the
14439 // implicit default constructor is suppressed if there are any
14440 // user-declared constructors, we just need to check that there is a
14441 // trivial default constructor and a trivial copy constructor. (We don't
14442 // worry about move constructors here, since this is a C++98 check.)
14443 if (RDecl->hasNonTrivialCopyConstructor())
14444 member = CXXCopyConstructor;
14445 else if (!RDecl->hasTrivialDefaultConstructor())
14446 member = CXXDefaultConstructor;
14447 else if (RDecl->hasNonTrivialCopyAssignment())
14448 member = CXXCopyAssignment;
14449 else if (RDecl->hasNonTrivialDestructor())
14450 member = CXXDestructor;
14452 if (member != CXXInvalid) {
14453 if (!getLangOpts().CPlusPlus11 &&
14454 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14455 // Objective-C++ ARC: it is an error to have a non-trivial field of
14456 // a union. However, system headers in Objective-C programs
14457 // occasionally have Objective-C lifetime objects within unions,
14458 // and rather than cause the program to fail, we make those
14459 // members unavailable.
14460 SourceLocation Loc = FD->getLocation();
14461 if (getSourceManager().isInSystemHeader(Loc)) {
14462 if (!FD->hasAttr<UnavailableAttr>())
14463 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14464 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14469 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14470 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14471 diag::err_illegal_union_or_anon_struct_member)
14472 << FD->getParent()->isUnion() << FD->getDeclName() << member;
14473 DiagnoseNontrivial(RDecl, member);
14474 return !getLangOpts().CPlusPlus11;
14482 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14483 /// AST enum value.
14484 static ObjCIvarDecl::AccessControl
14485 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14486 switch (ivarVisibility) {
14487 default: llvm_unreachable("Unknown visitibility kind");
14488 case tok::objc_private: return ObjCIvarDecl::Private;
14489 case tok::objc_public: return ObjCIvarDecl::Public;
14490 case tok::objc_protected: return ObjCIvarDecl::Protected;
14491 case tok::objc_package: return ObjCIvarDecl::Package;
14495 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14496 /// in order to create an IvarDecl object for it.
14497 Decl *Sema::ActOnIvar(Scope *S,
14498 SourceLocation DeclStart,
14499 Declarator &D, Expr *BitfieldWidth,
14500 tok::ObjCKeywordKind Visibility) {
14502 IdentifierInfo *II = D.getIdentifier();
14503 Expr *BitWidth = (Expr*)BitfieldWidth;
14504 SourceLocation Loc = DeclStart;
14505 if (II) Loc = D.getIdentifierLoc();
14507 // FIXME: Unnamed fields can be handled in various different ways, for
14508 // example, unnamed unions inject all members into the struct namespace!
14510 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14511 QualType T = TInfo->getType();
14514 // 6.7.2.1p3, 6.7.2.1p4
14515 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14517 D.setInvalidType();
14524 if (T->isReferenceType()) {
14525 Diag(Loc, diag::err_ivar_reference_type);
14526 D.setInvalidType();
14528 // C99 6.7.2.1p8: A member of a structure or union may have any type other
14529 // than a variably modified type.
14530 else if (T->isVariablyModifiedType()) {
14531 Diag(Loc, diag::err_typecheck_ivar_variable_size);
14532 D.setInvalidType();
14535 // Get the visibility (access control) for this ivar.
14536 ObjCIvarDecl::AccessControl ac =
14537 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14538 : ObjCIvarDecl::None;
14539 // Must set ivar's DeclContext to its enclosing interface.
14540 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14541 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14543 ObjCContainerDecl *EnclosingContext;
14544 if (ObjCImplementationDecl *IMPDecl =
14545 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14546 if (LangOpts.ObjCRuntime.isFragile()) {
14547 // Case of ivar declared in an implementation. Context is that of its class.
14548 EnclosingContext = IMPDecl->getClassInterface();
14549 assert(EnclosingContext && "Implementation has no class interface!");
14552 EnclosingContext = EnclosingDecl;
14554 if (ObjCCategoryDecl *CDecl =
14555 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14556 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14557 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14561 EnclosingContext = EnclosingDecl;
14564 // Construct the decl.
14565 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14566 DeclStart, Loc, II, T,
14567 TInfo, ac, (Expr *)BitfieldWidth);
14570 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14572 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14573 && !isa<TagDecl>(PrevDecl)) {
14574 Diag(Loc, diag::err_duplicate_member) << II;
14575 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14576 NewID->setInvalidDecl();
14580 // Process attributes attached to the ivar.
14581 ProcessDeclAttributes(S, NewID, D);
14583 if (D.isInvalidType())
14584 NewID->setInvalidDecl();
14586 // In ARC, infer 'retaining' for ivars of retainable type.
14587 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14588 NewID->setInvalidDecl();
14590 if (D.getDeclSpec().isModulePrivateSpecified())
14591 NewID->setModulePrivate();
14594 // FIXME: When interfaces are DeclContexts, we'll need to add
14595 // these to the interface.
14597 IdResolver.AddDecl(NewID);
14600 if (LangOpts.ObjCRuntime.isNonFragile() &&
14601 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14602 Diag(Loc, diag::warn_ivars_in_interface);
14607 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14608 /// class and class extensions. For every class \@interface and class
14609 /// extension \@interface, if the last ivar is a bitfield of any type,
14610 /// then add an implicit `char :0` ivar to the end of that interface.
14611 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14612 SmallVectorImpl<Decl *> &AllIvarDecls) {
14613 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14616 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14617 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14619 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14621 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14623 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14624 if (!CD->IsClassExtension())
14627 // No need to add this to end of @implementation.
14631 // All conditions are met. Add a new bitfield to the tail end of ivars.
14632 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14633 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14635 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14636 DeclLoc, DeclLoc, nullptr,
14638 Context.getTrivialTypeSourceInfo(Context.CharTy,
14640 ObjCIvarDecl::Private, BW,
14642 AllIvarDecls.push_back(Ivar);
14645 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14646 ArrayRef<Decl *> Fields, SourceLocation LBrac,
14647 SourceLocation RBrac, AttributeList *Attr) {
14648 assert(EnclosingDecl && "missing record or interface decl");
14650 // If this is an Objective-C @implementation or category and we have
14651 // new fields here we should reset the layout of the interface since
14652 // it will now change.
14653 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14654 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14655 switch (DC->getKind()) {
14657 case Decl::ObjCCategory:
14658 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14660 case Decl::ObjCImplementation:
14662 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14667 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14669 // Start counting up the number of named members; make sure to include
14670 // members of anonymous structs and unions in the total.
14671 unsigned NumNamedMembers = 0;
14673 for (const auto *I : Record->decls()) {
14674 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14675 if (IFD->getDeclName())
14680 // Verify that all the fields are okay.
14681 SmallVector<FieldDecl*, 32> RecFields;
14683 bool ObjCFieldLifetimeErrReported = false;
14684 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14686 FieldDecl *FD = cast<FieldDecl>(*i);
14688 // Get the type for the field.
14689 const Type *FDTy = FD->getType().getTypePtr();
14691 if (!FD->isAnonymousStructOrUnion()) {
14692 // Remember all fields written by the user.
14693 RecFields.push_back(FD);
14696 // If the field is already invalid for some reason, don't emit more
14697 // diagnostics about it.
14698 if (FD->isInvalidDecl()) {
14699 EnclosingDecl->setInvalidDecl();
14704 // A structure or union shall not contain a member with
14705 // incomplete or function type (hence, a structure shall not
14706 // contain an instance of itself, but may contain a pointer to
14707 // an instance of itself), except that the last member of a
14708 // structure with more than one named member may have incomplete
14709 // array type; such a structure (and any union containing,
14710 // possibly recursively, a member that is such a structure)
14711 // shall not be a member of a structure or an element of an
14713 if (FDTy->isFunctionType()) {
14714 // Field declared as a function.
14715 Diag(FD->getLocation(), diag::err_field_declared_as_function)
14716 << FD->getDeclName();
14717 FD->setInvalidDecl();
14718 EnclosingDecl->setInvalidDecl();
14720 } else if (FDTy->isIncompleteArrayType() && Record &&
14721 ((i + 1 == Fields.end() && !Record->isUnion()) ||
14722 ((getLangOpts().MicrosoftExt ||
14723 getLangOpts().CPlusPlus) &&
14724 (i + 1 == Fields.end() || Record->isUnion())))) {
14725 // Flexible array member.
14726 // Microsoft and g++ is more permissive regarding flexible array.
14727 // It will accept flexible array in union and also
14728 // as the sole element of a struct/class.
14729 unsigned DiagID = 0;
14730 if (Record->isUnion())
14731 DiagID = getLangOpts().MicrosoftExt
14732 ? diag::ext_flexible_array_union_ms
14733 : getLangOpts().CPlusPlus
14734 ? diag::ext_flexible_array_union_gnu
14735 : diag::err_flexible_array_union;
14736 else if (NumNamedMembers < 1)
14737 DiagID = getLangOpts().MicrosoftExt
14738 ? diag::ext_flexible_array_empty_aggregate_ms
14739 : getLangOpts().CPlusPlus
14740 ? diag::ext_flexible_array_empty_aggregate_gnu
14741 : diag::err_flexible_array_empty_aggregate;
14744 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14745 << Record->getTagKind();
14746 // While the layout of types that contain virtual bases is not specified
14747 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14748 // virtual bases after the derived members. This would make a flexible
14749 // array member declared at the end of an object not adjacent to the end
14751 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14752 if (RD->getNumVBases() != 0)
14753 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14754 << FD->getDeclName() << Record->getTagKind();
14755 if (!getLangOpts().C99)
14756 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14757 << FD->getDeclName() << Record->getTagKind();
14759 // If the element type has a non-trivial destructor, we would not
14760 // implicitly destroy the elements, so disallow it for now.
14762 // FIXME: GCC allows this. We should probably either implicitly delete
14763 // the destructor of the containing class, or just allow this.
14764 QualType BaseElem = Context.getBaseElementType(FD->getType());
14765 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14766 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14767 << FD->getDeclName() << FD->getType();
14768 FD->setInvalidDecl();
14769 EnclosingDecl->setInvalidDecl();
14772 // Okay, we have a legal flexible array member at the end of the struct.
14773 Record->setHasFlexibleArrayMember(true);
14774 } else if (!FDTy->isDependentType() &&
14775 RequireCompleteType(FD->getLocation(), FD->getType(),
14776 diag::err_field_incomplete)) {
14778 FD->setInvalidDecl();
14779 EnclosingDecl->setInvalidDecl();
14781 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14782 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14783 // A type which contains a flexible array member is considered to be a
14784 // flexible array member.
14785 Record->setHasFlexibleArrayMember(true);
14786 if (!Record->isUnion()) {
14787 // If this is a struct/class and this is not the last element, reject
14788 // it. Note that GCC supports variable sized arrays in the middle of
14790 if (i + 1 != Fields.end())
14791 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14792 << FD->getDeclName() << FD->getType();
14794 // We support flexible arrays at the end of structs in
14795 // other structs as an extension.
14796 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14797 << FD->getDeclName();
14801 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14802 RequireNonAbstractType(FD->getLocation(), FD->getType(),
14803 diag::err_abstract_type_in_decl,
14804 AbstractIvarType)) {
14805 // Ivars can not have abstract class types
14806 FD->setInvalidDecl();
14808 if (Record && FDTTy->getDecl()->hasObjectMember())
14809 Record->setHasObjectMember(true);
14810 if (Record && FDTTy->getDecl()->hasVolatileMember())
14811 Record->setHasVolatileMember(true);
14812 } else if (FDTy->isObjCObjectType()) {
14813 /// A field cannot be an Objective-c object
14814 Diag(FD->getLocation(), diag::err_statically_allocated_object)
14815 << FixItHint::CreateInsertion(FD->getLocation(), "*");
14816 QualType T = Context.getObjCObjectPointerType(FD->getType());
14818 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
14819 Record && !ObjCFieldLifetimeErrReported &&
14820 (!getLangOpts().CPlusPlus || Record->isUnion())) {
14821 // It's an error in ARC or Weak if a field has lifetime.
14822 // We don't want to report this in a system header, though,
14823 // so we just make the field unavailable.
14824 // FIXME: that's really not sufficient; we need to make the type
14825 // itself invalid to, say, initialize or copy.
14826 QualType T = FD->getType();
14827 if (T.hasNonTrivialObjCLifetime()) {
14828 SourceLocation loc = FD->getLocation();
14829 if (getSourceManager().isInSystemHeader(loc)) {
14830 if (!FD->hasAttr<UnavailableAttr>()) {
14831 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14832 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14835 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14836 << T->isBlockPointerType() << Record->getTagKind();
14838 ObjCFieldLifetimeErrReported = true;
14840 } else if (getLangOpts().ObjC1 &&
14841 getLangOpts().getGC() != LangOptions::NonGC &&
14842 Record && !Record->hasObjectMember()) {
14843 if (FD->getType()->isObjCObjectPointerType() ||
14844 FD->getType().isObjCGCStrong())
14845 Record->setHasObjectMember(true);
14846 else if (Context.getAsArrayType(FD->getType())) {
14847 QualType BaseType = Context.getBaseElementType(FD->getType());
14848 if (BaseType->isRecordType() &&
14849 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14850 Record->setHasObjectMember(true);
14851 else if (BaseType->isObjCObjectPointerType() ||
14852 BaseType.isObjCGCStrong())
14853 Record->setHasObjectMember(true);
14856 if (Record && FD->getType().isVolatileQualified())
14857 Record->setHasVolatileMember(true);
14858 // Keep track of the number of named members.
14859 if (FD->getIdentifier())
14863 // Okay, we successfully defined 'Record'.
14865 bool Completed = false;
14866 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14867 if (!CXXRecord->isInvalidDecl()) {
14868 // Set access bits correctly on the directly-declared conversions.
14869 for (CXXRecordDecl::conversion_iterator
14870 I = CXXRecord->conversion_begin(),
14871 E = CXXRecord->conversion_end(); I != E; ++I)
14872 I.setAccess((*I)->getAccess());
14875 if (!CXXRecord->isDependentType()) {
14876 if (CXXRecord->hasUserDeclaredDestructor()) {
14877 // Adjust user-defined destructor exception spec.
14878 if (getLangOpts().CPlusPlus11)
14879 AdjustDestructorExceptionSpec(CXXRecord,
14880 CXXRecord->getDestructor());
14883 if (!CXXRecord->isInvalidDecl()) {
14884 // Add any implicitly-declared members to this class.
14885 AddImplicitlyDeclaredMembersToClass(CXXRecord);
14887 // If we have virtual base classes, we may end up finding multiple
14888 // final overriders for a given virtual function. Check for this
14890 if (CXXRecord->getNumVBases()) {
14891 CXXFinalOverriderMap FinalOverriders;
14892 CXXRecord->getFinalOverriders(FinalOverriders);
14894 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14895 MEnd = FinalOverriders.end();
14897 for (OverridingMethods::iterator SO = M->second.begin(),
14898 SOEnd = M->second.end();
14899 SO != SOEnd; ++SO) {
14900 assert(SO->second.size() > 0 &&
14901 "Virtual function without overridding functions?");
14902 if (SO->second.size() == 1)
14905 // C++ [class.virtual]p2:
14906 // In a derived class, if a virtual member function of a base
14907 // class subobject has more than one final overrider the
14908 // program is ill-formed.
14909 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14910 << (const NamedDecl *)M->first << Record;
14911 Diag(M->first->getLocation(),
14912 diag::note_overridden_virtual_function);
14913 for (OverridingMethods::overriding_iterator
14914 OM = SO->second.begin(),
14915 OMEnd = SO->second.end();
14917 Diag(OM->Method->getLocation(), diag::note_final_overrider)
14918 << (const NamedDecl *)M->first << OM->Method->getParent();
14920 Record->setInvalidDecl();
14923 CXXRecord->completeDefinition(&FinalOverriders);
14931 Record->completeDefinition();
14933 // We may have deferred checking for a deleted destructor. Check now.
14934 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14935 auto *Dtor = CXXRecord->getDestructor();
14936 if (Dtor && Dtor->isImplicit() &&
14937 ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14938 SetDeclDeleted(Dtor, CXXRecord->getLocation());
14941 if (Record->hasAttrs()) {
14942 CheckAlignasUnderalignment(Record);
14944 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14945 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14946 IA->getRange(), IA->getBestCase(),
14947 IA->getSemanticSpelling());
14950 // Check if the structure/union declaration is a type that can have zero
14951 // size in C. For C this is a language extension, for C++ it may cause
14952 // compatibility problems.
14953 bool CheckForZeroSize;
14954 if (!getLangOpts().CPlusPlus) {
14955 CheckForZeroSize = true;
14957 // For C++ filter out types that cannot be referenced in C code.
14958 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14960 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14961 !CXXRecord->isDependentType() &&
14962 CXXRecord->isCLike();
14964 if (CheckForZeroSize) {
14965 bool ZeroSize = true;
14966 bool IsEmpty = true;
14967 unsigned NonBitFields = 0;
14968 for (RecordDecl::field_iterator I = Record->field_begin(),
14969 E = Record->field_end();
14970 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14972 if (I->isUnnamedBitfield()) {
14973 if (I->getBitWidthValue(Context) > 0)
14977 QualType FieldType = I->getType();
14978 if (FieldType->isIncompleteType() ||
14979 !Context.getTypeSizeInChars(FieldType).isZero())
14984 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14985 // allowed in C++, but warn if its declaration is inside
14986 // extern "C" block.
14988 Diag(RecLoc, getLangOpts().CPlusPlus ?
14989 diag::warn_zero_size_struct_union_in_extern_c :
14990 diag::warn_zero_size_struct_union_compat)
14991 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14994 // Structs without named members are extension in C (C99 6.7.2.1p7),
14995 // but are accepted by GCC.
14996 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14997 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14998 diag::ext_no_named_members_in_struct_union)
14999 << Record->isUnion();
15003 ObjCIvarDecl **ClsFields =
15004 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15005 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15006 ID->setEndOfDefinitionLoc(RBrac);
15007 // Add ivar's to class's DeclContext.
15008 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15009 ClsFields[i]->setLexicalDeclContext(ID);
15010 ID->addDecl(ClsFields[i]);
15012 // Must enforce the rule that ivars in the base classes may not be
15014 if (ID->getSuperClass())
15015 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15016 } else if (ObjCImplementationDecl *IMPDecl =
15017 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15018 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15019 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15020 // Ivar declared in @implementation never belongs to the implementation.
15021 // Only it is in implementation's lexical context.
15022 ClsFields[I]->setLexicalDeclContext(IMPDecl);
15023 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15024 IMPDecl->setIvarLBraceLoc(LBrac);
15025 IMPDecl->setIvarRBraceLoc(RBrac);
15026 } else if (ObjCCategoryDecl *CDecl =
15027 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15028 // case of ivars in class extension; all other cases have been
15029 // reported as errors elsewhere.
15030 // FIXME. Class extension does not have a LocEnd field.
15031 // CDecl->setLocEnd(RBrac);
15032 // Add ivar's to class extension's DeclContext.
15033 // Diagnose redeclaration of private ivars.
15034 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15035 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15037 if (const ObjCIvarDecl *ClsIvar =
15038 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15039 Diag(ClsFields[i]->getLocation(),
15040 diag::err_duplicate_ivar_declaration);
15041 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15044 for (const auto *Ext : IDecl->known_extensions()) {
15045 if (const ObjCIvarDecl *ClsExtIvar
15046 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15047 Diag(ClsFields[i]->getLocation(),
15048 diag::err_duplicate_ivar_declaration);
15049 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15054 ClsFields[i]->setLexicalDeclContext(CDecl);
15055 CDecl->addDecl(ClsFields[i]);
15057 CDecl->setIvarLBraceLoc(LBrac);
15058 CDecl->setIvarRBraceLoc(RBrac);
15063 ProcessDeclAttributeList(S, Record, Attr);
15066 /// \brief Determine whether the given integral value is representable within
15067 /// the given type T.
15068 static bool isRepresentableIntegerValue(ASTContext &Context,
15069 llvm::APSInt &Value,
15071 assert(T->isIntegralType(Context) && "Integral type required!");
15072 unsigned BitWidth = Context.getIntWidth(T);
15074 if (Value.isUnsigned() || Value.isNonNegative()) {
15075 if (T->isSignedIntegerOrEnumerationType())
15077 return Value.getActiveBits() <= BitWidth;
15079 return Value.getMinSignedBits() <= BitWidth;
15082 // \brief Given an integral type, return the next larger integral type
15083 // (or a NULL type of no such type exists).
15084 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15085 // FIXME: Int128/UInt128 support, which also needs to be introduced into
15086 // enum checking below.
15087 assert(T->isIntegralType(Context) && "Integral type required!");
15088 const unsigned NumTypes = 4;
15089 QualType SignedIntegralTypes[NumTypes] = {
15090 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15092 QualType UnsignedIntegralTypes[NumTypes] = {
15093 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15094 Context.UnsignedLongLongTy
15097 unsigned BitWidth = Context.getTypeSize(T);
15098 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15099 : UnsignedIntegralTypes;
15100 for (unsigned I = 0; I != NumTypes; ++I)
15101 if (Context.getTypeSize(Types[I]) > BitWidth)
15107 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15108 EnumConstantDecl *LastEnumConst,
15109 SourceLocation IdLoc,
15110 IdentifierInfo *Id,
15112 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15113 llvm::APSInt EnumVal(IntWidth);
15116 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15120 Val = DefaultLvalueConversion(Val).get();
15123 if (Enum->isDependentType() || Val->isTypeDependent())
15124 EltTy = Context.DependentTy;
15126 SourceLocation ExpLoc;
15127 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15128 !getLangOpts().MSVCCompat) {
15129 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15130 // constant-expression in the enumerator-definition shall be a converted
15131 // constant expression of the underlying type.
15132 EltTy = Enum->getIntegerType();
15133 ExprResult Converted =
15134 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15136 if (Converted.isInvalid())
15139 Val = Converted.get();
15140 } else if (!Val->isValueDependent() &&
15141 !(Val = VerifyIntegerConstantExpression(Val,
15142 &EnumVal).get())) {
15143 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15145 if (Enum->isFixed()) {
15146 EltTy = Enum->getIntegerType();
15148 // In Obj-C and Microsoft mode, require the enumeration value to be
15149 // representable in the underlying type of the enumeration. In C++11,
15150 // we perform a non-narrowing conversion as part of converted constant
15151 // expression checking.
15152 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15153 if (getLangOpts().MSVCCompat) {
15154 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15155 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15157 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15159 Val = ImpCastExprToType(Val, EltTy,
15160 EltTy->isBooleanType() ?
15161 CK_IntegralToBoolean : CK_IntegralCast)
15163 } else if (getLangOpts().CPlusPlus) {
15164 // C++11 [dcl.enum]p5:
15165 // If the underlying type is not fixed, the type of each enumerator
15166 // is the type of its initializing value:
15167 // - If an initializer is specified for an enumerator, the
15168 // initializing value has the same type as the expression.
15169 EltTy = Val->getType();
15172 // The expression that defines the value of an enumeration constant
15173 // shall be an integer constant expression that has a value
15174 // representable as an int.
15176 // Complain if the value is not representable in an int.
15177 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15178 Diag(IdLoc, diag::ext_enum_value_not_int)
15179 << EnumVal.toString(10) << Val->getSourceRange()
15180 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15181 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15182 // Force the type of the expression to 'int'.
15183 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15185 EltTy = Val->getType();
15192 if (Enum->isDependentType())
15193 EltTy = Context.DependentTy;
15194 else if (!LastEnumConst) {
15195 // C++0x [dcl.enum]p5:
15196 // If the underlying type is not fixed, the type of each enumerator
15197 // is the type of its initializing value:
15198 // - If no initializer is specified for the first enumerator, the
15199 // initializing value has an unspecified integral type.
15201 // GCC uses 'int' for its unspecified integral type, as does
15203 if (Enum->isFixed()) {
15204 EltTy = Enum->getIntegerType();
15207 EltTy = Context.IntTy;
15210 // Assign the last value + 1.
15211 EnumVal = LastEnumConst->getInitVal();
15213 EltTy = LastEnumConst->getType();
15215 // Check for overflow on increment.
15216 if (EnumVal < LastEnumConst->getInitVal()) {
15217 // C++0x [dcl.enum]p5:
15218 // If the underlying type is not fixed, the type of each enumerator
15219 // is the type of its initializing value:
15221 // - Otherwise the type of the initializing value is the same as
15222 // the type of the initializing value of the preceding enumerator
15223 // unless the incremented value is not representable in that type,
15224 // in which case the type is an unspecified integral type
15225 // sufficient to contain the incremented value. If no such type
15226 // exists, the program is ill-formed.
15227 QualType T = getNextLargerIntegralType(Context, EltTy);
15228 if (T.isNull() || Enum->isFixed()) {
15229 // There is no integral type larger enough to represent this
15230 // value. Complain, then allow the value to wrap around.
15231 EnumVal = LastEnumConst->getInitVal();
15232 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15234 if (Enum->isFixed())
15235 // When the underlying type is fixed, this is ill-formed.
15236 Diag(IdLoc, diag::err_enumerator_wrapped)
15237 << EnumVal.toString(10)
15240 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15241 << EnumVal.toString(10);
15246 // Retrieve the last enumerator's value, extent that type to the
15247 // type that is supposed to be large enough to represent the incremented
15248 // value, then increment.
15249 EnumVal = LastEnumConst->getInitVal();
15250 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15251 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15254 // If we're not in C++, diagnose the overflow of enumerator values,
15255 // which in C99 means that the enumerator value is not representable in
15256 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15257 // permits enumerator values that are representable in some larger
15259 if (!getLangOpts().CPlusPlus && !T.isNull())
15260 Diag(IdLoc, diag::warn_enum_value_overflow);
15261 } else if (!getLangOpts().CPlusPlus &&
15262 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15263 // Enforce C99 6.7.2.2p2 even when we compute the next value.
15264 Diag(IdLoc, diag::ext_enum_value_not_int)
15265 << EnumVal.toString(10) << 1;
15270 if (!EltTy->isDependentType()) {
15271 // Make the enumerator value match the signedness and size of the
15272 // enumerator's type.
15273 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15274 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15277 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15281 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15282 SourceLocation IILoc) {
15283 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15284 !getLangOpts().CPlusPlus)
15285 return SkipBodyInfo();
15287 // We have an anonymous enum definition. Look up the first enumerator to
15288 // determine if we should merge the definition with an existing one and
15290 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15292 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15294 return SkipBodyInfo();
15296 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15298 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15300 Skip.Previous = Hidden;
15304 return SkipBodyInfo();
15307 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15308 SourceLocation IdLoc, IdentifierInfo *Id,
15309 AttributeList *Attr,
15310 SourceLocation EqualLoc, Expr *Val) {
15311 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15312 EnumConstantDecl *LastEnumConst =
15313 cast_or_null<EnumConstantDecl>(lastEnumConst);
15315 // The scope passed in may not be a decl scope. Zip up the scope tree until
15316 // we find one that is.
15317 S = getNonFieldDeclScope(S);
15319 // Verify that there isn't already something declared with this name in this
15321 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15323 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15324 // Maybe we will complain about the shadowed template parameter.
15325 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15326 // Just pretend that we didn't see the previous declaration.
15327 PrevDecl = nullptr;
15330 // C++ [class.mem]p15:
15331 // If T is the name of a class, then each of the following shall have a name
15332 // different from T:
15333 // - every enumerator of every member of class T that is an unscoped
15335 if (!TheEnumDecl->isScoped())
15336 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15337 DeclarationNameInfo(Id, IdLoc));
15339 EnumConstantDecl *New =
15340 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15345 // When in C++, we may get a TagDecl with the same name; in this case the
15346 // enum constant will 'hide' the tag.
15347 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15348 "Received TagDecl when not in C++!");
15349 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15350 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15351 if (isa<EnumConstantDecl>(PrevDecl))
15352 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15354 Diag(IdLoc, diag::err_redefinition) << Id;
15355 notePreviousDefinition(PrevDecl, IdLoc);
15360 // Process attributes.
15361 if (Attr) ProcessDeclAttributeList(S, New, Attr);
15362 AddPragmaAttributes(S, New);
15364 // Register this decl in the current scope stack.
15365 New->setAccess(TheEnumDecl->getAccess());
15366 PushOnScopeChains(New, S);
15368 ActOnDocumentableDecl(New);
15373 // Returns true when the enum initial expression does not trigger the
15374 // duplicate enum warning. A few common cases are exempted as follows:
15375 // Element2 = Element1
15376 // Element2 = Element1 + 1
15377 // Element2 = Element1 - 1
15378 // Where Element2 and Element1 are from the same enum.
15379 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15380 Expr *InitExpr = ECD->getInitExpr();
15383 InitExpr = InitExpr->IgnoreImpCasts();
15385 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15386 if (!BO->isAdditiveOp())
15388 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15391 if (IL->getValue() != 1)
15394 InitExpr = BO->getLHS();
15397 // This checks if the elements are from the same enum.
15398 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15402 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15406 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15416 bool isTombstoneOrEmptyKey;
15417 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15418 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15421 static DupKey GetDupKey(const llvm::APSInt& Val) {
15422 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15426 struct DenseMapInfoDupKey {
15427 static DupKey getEmptyKey() { return DupKey(0, true); }
15428 static DupKey getTombstoneKey() { return DupKey(1, true); }
15429 static unsigned getHashValue(const DupKey Key) {
15430 return (unsigned)(Key.val * 37);
15432 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15433 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15434 LHS.val == RHS.val;
15437 } // end anonymous namespace
15439 // Emits a warning when an element is implicitly set a value that
15440 // a previous element has already been set to.
15441 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15443 QualType EnumType) {
15444 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15446 // Avoid anonymous enums
15447 if (!Enum->getIdentifier())
15450 // Only check for small enums.
15451 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15454 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15455 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15457 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15458 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15461 DuplicatesVector DupVector;
15462 ValueToVectorMap EnumMap;
15464 // Populate the EnumMap with all values represented by enum constants without
15466 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15467 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15469 // Null EnumConstantDecl means a previous diagnostic has been emitted for
15470 // this constant. Skip this enum since it may be ill-formed.
15475 if (ECD->getInitExpr())
15478 DupKey Key = GetDupKey(ECD->getInitVal());
15479 DeclOrVector &Entry = EnumMap[Key];
15481 // First time encountering this value.
15482 if (Entry.isNull())
15486 // Create vectors for any values that has duplicates.
15487 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15488 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15489 if (!ValidDuplicateEnum(ECD, Enum))
15492 DupKey Key = GetDupKey(ECD->getInitVal());
15494 DeclOrVector& Entry = EnumMap[Key];
15495 if (Entry.isNull())
15498 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15499 // Ensure constants are different.
15503 // Create new vector and push values onto it.
15504 ECDVector *Vec = new ECDVector();
15506 Vec->push_back(ECD);
15508 // Update entry to point to the duplicates vector.
15511 // Store the vector somewhere we can consult later for quick emission of
15513 DupVector.push_back(Vec);
15517 ECDVector *Vec = Entry.get<ECDVector*>();
15518 // Make sure constants are not added more than once.
15519 if (*Vec->begin() == ECD)
15522 Vec->push_back(ECD);
15525 // Emit diagnostics.
15526 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15527 DupVectorEnd = DupVector.end();
15528 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15529 ECDVector *Vec = *DupVectorIter;
15530 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15532 // Emit warning for one enum constant.
15533 ECDVector::iterator I = Vec->begin();
15534 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15535 << (*I)->getName() << (*I)->getInitVal().toString(10)
15536 << (*I)->getSourceRange();
15539 // Emit one note for each of the remaining enum constants with
15541 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15542 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15543 << (*I)->getName() << (*I)->getInitVal().toString(10)
15544 << (*I)->getSourceRange();
15549 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15550 bool AllowMask) const {
15551 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15552 assert(ED->isCompleteDefinition() && "expected enum definition");
15554 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15555 llvm::APInt &FlagBits = R.first->second;
15558 for (auto *E : ED->enumerators()) {
15559 const auto &EVal = E->getInitVal();
15560 // Only single-bit enumerators introduce new flag values.
15561 if (EVal.isPowerOf2())
15562 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15566 // A value is in a flag enum if either its bits are a subset of the enum's
15567 // flag bits (the first condition) or we are allowing masks and the same is
15568 // true of its complement (the second condition). When masks are allowed, we
15569 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15571 // While it's true that any value could be used as a mask, the assumption is
15572 // that a mask will have all of the insignificant bits set. Anything else is
15573 // likely a logic error.
15574 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15575 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15578 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15580 ArrayRef<Decl *> Elements,
15581 Scope *S, AttributeList *Attr) {
15582 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15583 QualType EnumType = Context.getTypeDeclType(Enum);
15586 ProcessDeclAttributeList(S, Enum, Attr);
15588 if (Enum->isDependentType()) {
15589 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15590 EnumConstantDecl *ECD =
15591 cast_or_null<EnumConstantDecl>(Elements[i]);
15592 if (!ECD) continue;
15594 ECD->setType(EnumType);
15597 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15601 // TODO: If the result value doesn't fit in an int, it must be a long or long
15602 // long value. ISO C does not support this, but GCC does as an extension,
15604 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15605 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15606 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15608 // Verify that all the values are okay, compute the size of the values, and
15609 // reverse the list.
15610 unsigned NumNegativeBits = 0;
15611 unsigned NumPositiveBits = 0;
15613 // Keep track of whether all elements have type int.
15614 bool AllElementsInt = true;
15616 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15617 EnumConstantDecl *ECD =
15618 cast_or_null<EnumConstantDecl>(Elements[i]);
15619 if (!ECD) continue; // Already issued a diagnostic.
15621 const llvm::APSInt &InitVal = ECD->getInitVal();
15623 // Keep track of the size of positive and negative values.
15624 if (InitVal.isUnsigned() || InitVal.isNonNegative())
15625 NumPositiveBits = std::max(NumPositiveBits,
15626 (unsigned)InitVal.getActiveBits());
15628 NumNegativeBits = std::max(NumNegativeBits,
15629 (unsigned)InitVal.getMinSignedBits());
15631 // Keep track of whether every enum element has type int (very commmon).
15632 if (AllElementsInt)
15633 AllElementsInt = ECD->getType() == Context.IntTy;
15636 // Figure out the type that should be used for this enum.
15638 unsigned BestWidth;
15640 // C++0x N3000 [conv.prom]p3:
15641 // An rvalue of an unscoped enumeration type whose underlying
15642 // type is not fixed can be converted to an rvalue of the first
15643 // of the following types that can represent all the values of
15644 // the enumeration: int, unsigned int, long int, unsigned long
15645 // int, long long int, or unsigned long long int.
15647 // An identifier declared as an enumeration constant has type int.
15648 // The C99 rule is modified by a gcc extension
15649 QualType BestPromotionType;
15651 bool Packed = Enum->hasAttr<PackedAttr>();
15652 // -fshort-enums is the equivalent to specifying the packed attribute on all
15653 // enum definitions.
15654 if (LangOpts.ShortEnums)
15657 if (Enum->isFixed()) {
15658 BestType = Enum->getIntegerType();
15659 if (BestType->isPromotableIntegerType())
15660 BestPromotionType = Context.getPromotedIntegerType(BestType);
15662 BestPromotionType = BestType;
15664 BestWidth = Context.getIntWidth(BestType);
15666 else if (NumNegativeBits) {
15667 // If there is a negative value, figure out the smallest integer type (of
15668 // int/long/longlong) that fits.
15669 // If it's packed, check also if it fits a char or a short.
15670 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15671 BestType = Context.SignedCharTy;
15672 BestWidth = CharWidth;
15673 } else if (Packed && NumNegativeBits <= ShortWidth &&
15674 NumPositiveBits < ShortWidth) {
15675 BestType = Context.ShortTy;
15676 BestWidth = ShortWidth;
15677 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15678 BestType = Context.IntTy;
15679 BestWidth = IntWidth;
15681 BestWidth = Context.getTargetInfo().getLongWidth();
15683 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15684 BestType = Context.LongTy;
15686 BestWidth = Context.getTargetInfo().getLongLongWidth();
15688 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15689 Diag(Enum->getLocation(), diag::ext_enum_too_large);
15690 BestType = Context.LongLongTy;
15693 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15695 // If there is no negative value, figure out the smallest type that fits
15696 // all of the enumerator values.
15697 // If it's packed, check also if it fits a char or a short.
15698 if (Packed && NumPositiveBits <= CharWidth) {
15699 BestType = Context.UnsignedCharTy;
15700 BestPromotionType = Context.IntTy;
15701 BestWidth = CharWidth;
15702 } else if (Packed && NumPositiveBits <= ShortWidth) {
15703 BestType = Context.UnsignedShortTy;
15704 BestPromotionType = Context.IntTy;
15705 BestWidth = ShortWidth;
15706 } else if (NumPositiveBits <= IntWidth) {
15707 BestType = Context.UnsignedIntTy;
15708 BestWidth = IntWidth;
15710 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15711 ? Context.UnsignedIntTy : Context.IntTy;
15712 } else if (NumPositiveBits <=
15713 (BestWidth = Context.getTargetInfo().getLongWidth())) {
15714 BestType = Context.UnsignedLongTy;
15716 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15717 ? Context.UnsignedLongTy : Context.LongTy;
15719 BestWidth = Context.getTargetInfo().getLongLongWidth();
15720 assert(NumPositiveBits <= BestWidth &&
15721 "How could an initializer get larger than ULL?");
15722 BestType = Context.UnsignedLongLongTy;
15724 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15725 ? Context.UnsignedLongLongTy : Context.LongLongTy;
15729 // Loop over all of the enumerator constants, changing their types to match
15730 // the type of the enum if needed.
15731 for (auto *D : Elements) {
15732 auto *ECD = cast_or_null<EnumConstantDecl>(D);
15733 if (!ECD) continue; // Already issued a diagnostic.
15735 // Standard C says the enumerators have int type, but we allow, as an
15736 // extension, the enumerators to be larger than int size. If each
15737 // enumerator value fits in an int, type it as an int, otherwise type it the
15738 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
15739 // that X has type 'int', not 'unsigned'.
15741 // Determine whether the value fits into an int.
15742 llvm::APSInt InitVal = ECD->getInitVal();
15744 // If it fits into an integer type, force it. Otherwise force it to match
15745 // the enum decl type.
15749 if (!getLangOpts().CPlusPlus &&
15750 !Enum->isFixed() &&
15751 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15752 NewTy = Context.IntTy;
15753 NewWidth = IntWidth;
15755 } else if (ECD->getType() == BestType) {
15756 // Already the right type!
15757 if (getLangOpts().CPlusPlus)
15758 // C++ [dcl.enum]p4: Following the closing brace of an
15759 // enum-specifier, each enumerator has the type of its
15761 ECD->setType(EnumType);
15765 NewWidth = BestWidth;
15766 NewSign = BestType->isSignedIntegerOrEnumerationType();
15769 // Adjust the APSInt value.
15770 InitVal = InitVal.extOrTrunc(NewWidth);
15771 InitVal.setIsSigned(NewSign);
15772 ECD->setInitVal(InitVal);
15774 // Adjust the Expr initializer and type.
15775 if (ECD->getInitExpr() &&
15776 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15777 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15779 ECD->getInitExpr(),
15780 /*base paths*/ nullptr,
15782 if (getLangOpts().CPlusPlus)
15783 // C++ [dcl.enum]p4: Following the closing brace of an
15784 // enum-specifier, each enumerator has the type of its
15786 ECD->setType(EnumType);
15788 ECD->setType(NewTy);
15791 Enum->completeDefinition(BestType, BestPromotionType,
15792 NumPositiveBits, NumNegativeBits);
15794 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15796 if (Enum->isClosedFlag()) {
15797 for (Decl *D : Elements) {
15798 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15799 if (!ECD) continue; // Already issued a diagnostic.
15801 llvm::APSInt InitVal = ECD->getInitVal();
15802 if (InitVal != 0 && !InitVal.isPowerOf2() &&
15803 !IsValueInFlagEnum(Enum, InitVal, true))
15804 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15809 // Now that the enum type is defined, ensure it's not been underaligned.
15810 if (Enum->hasAttrs())
15811 CheckAlignasUnderalignment(Enum);
15814 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15815 SourceLocation StartLoc,
15816 SourceLocation EndLoc) {
15817 StringLiteral *AsmString = cast<StringLiteral>(expr);
15819 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15820 AsmString, StartLoc,
15822 CurContext->addDecl(New);
15826 static void checkModuleImportContext(Sema &S, Module *M,
15827 SourceLocation ImportLoc, DeclContext *DC,
15828 bool FromInclude = false) {
15829 SourceLocation ExternCLoc;
15831 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15832 switch (LSD->getLanguage()) {
15833 case LinkageSpecDecl::lang_c:
15834 if (ExternCLoc.isInvalid())
15835 ExternCLoc = LSD->getLocStart();
15837 case LinkageSpecDecl::lang_cxx:
15840 DC = LSD->getParent();
15843 while (isa<LinkageSpecDecl>(DC))
15844 DC = DC->getParent();
15846 if (!isa<TranslationUnitDecl>(DC)) {
15847 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15848 ? diag::ext_module_import_not_at_top_level_noop
15849 : diag::err_module_import_not_at_top_level_fatal)
15850 << M->getFullModuleName() << DC;
15851 S.Diag(cast<Decl>(DC)->getLocStart(),
15852 diag::note_module_import_not_at_top_level) << DC;
15853 } else if (!M->IsExternC && ExternCLoc.isValid()) {
15854 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15855 << M->getFullModuleName();
15856 S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15860 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
15861 SourceLocation ModuleLoc,
15862 ModuleDeclKind MDK,
15863 ModuleIdPath Path) {
15864 // A module implementation unit requires that we are not compiling a module
15865 // of any kind. A module interface unit requires that we are not compiling a
15867 switch (getLangOpts().getCompilingModule()) {
15868 case LangOptions::CMK_None:
15869 // It's OK to compile a module interface as a normal translation unit.
15872 case LangOptions::CMK_ModuleInterface:
15873 if (MDK != ModuleDeclKind::Implementation)
15876 // We were asked to compile a module interface unit but this is a module
15877 // implementation unit. That indicates the 'export' is missing.
15878 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15879 << FixItHint::CreateInsertion(ModuleLoc, "export ");
15882 case LangOptions::CMK_ModuleMap:
15883 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
15887 // FIXME: Create a ModuleDecl and return it.
15889 // FIXME: Most of this work should be done by the preprocessor rather than
15890 // here, in order to support macro import.
15892 // Flatten the dots in a module name. Unlike Clang's hierarchical module map
15893 // modules, the dots here are just another character that can appear in a
15895 std::string ModuleName;
15896 for (auto &Piece : Path) {
15897 if (!ModuleName.empty())
15899 ModuleName += Piece.first->getName();
15902 // If a module name was explicitly specified on the command line, it must be
15904 if (!getLangOpts().CurrentModule.empty() &&
15905 getLangOpts().CurrentModule != ModuleName) {
15906 Diag(Path.front().second, diag::err_current_module_name_mismatch)
15907 << SourceRange(Path.front().second, Path.back().second)
15908 << getLangOpts().CurrentModule;
15911 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15913 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15916 case ModuleDeclKind::Module: {
15917 // FIXME: Check we're not in a submodule.
15919 // We can't have parsed or imported a definition of this module or parsed a
15920 // module map defining it already.
15921 if (auto *M = Map.findModule(ModuleName)) {
15922 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15923 if (M->DefinitionLoc.isValid())
15924 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15925 else if (const auto *FE = M->getASTFile())
15926 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15931 // Create a Module for the module that we're defining.
15932 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15933 assert(Mod && "module creation should not fail");
15935 // Enter the semantic scope of the module.
15936 ActOnModuleBegin(ModuleLoc, Mod);
15940 case ModuleDeclKind::Partition:
15941 // FIXME: Check we are in a submodule of the named module.
15944 case ModuleDeclKind::Implementation:
15945 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15946 PP.getIdentifierInfo(ModuleName), Path[0].second);
15948 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15949 if (Import.isInvalid())
15951 return ConvertDeclToDeclGroup(Import.get());
15954 llvm_unreachable("unexpected module decl kind");
15957 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15958 SourceLocation ImportLoc,
15959 ModuleIdPath Path) {
15961 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15962 /*IsIncludeDirective=*/false);
15966 VisibleModules.setVisible(Mod, ImportLoc);
15968 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15970 // FIXME: we should support importing a submodule within a different submodule
15971 // of the same top-level module. Until we do, make it an error rather than
15972 // silently ignoring the import.
15973 // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15974 // warn on a redundant import of the current module?
15975 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15976 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15977 Diag(ImportLoc, getLangOpts().isCompilingModule()
15978 ? diag::err_module_self_import
15979 : diag::err_module_import_in_implementation)
15980 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15982 SmallVector<SourceLocation, 2> IdentifierLocs;
15983 Module *ModCheck = Mod;
15984 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15985 // If we've run out of module parents, just drop the remaining identifiers.
15986 // We need the length to be consistent.
15989 ModCheck = ModCheck->Parent;
15991 IdentifierLocs.push_back(Path[I].second);
15994 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15995 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15996 Mod, IdentifierLocs);
15997 if (!ModuleScopes.empty())
15998 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15999 TU->addDecl(Import);
16003 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16004 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16005 BuildModuleInclude(DirectiveLoc, Mod);
16008 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16009 // Determine whether we're in the #include buffer for a module. The #includes
16010 // in that buffer do not qualify as module imports; they're just an
16011 // implementation detail of us building the module.
16013 // FIXME: Should we even get ActOnModuleInclude calls for those?
16014 bool IsInModuleIncludes =
16015 TUKind == TU_Module &&
16016 getSourceManager().isWrittenInMainFile(DirectiveLoc);
16018 bool ShouldAddImport = !IsInModuleIncludes;
16020 // If this module import was due to an inclusion directive, create an
16021 // implicit import declaration to capture it in the AST.
16022 if (ShouldAddImport) {
16023 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16024 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16027 if (!ModuleScopes.empty())
16028 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16029 TU->addDecl(ImportD);
16030 Consumer.HandleImplicitImportDecl(ImportD);
16033 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16034 VisibleModules.setVisible(Mod, DirectiveLoc);
16037 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16038 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16040 ModuleScopes.push_back({});
16041 ModuleScopes.back().Module = Mod;
16042 if (getLangOpts().ModulesLocalVisibility)
16043 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16045 VisibleModules.setVisible(Mod, DirectiveLoc);
16047 // The enclosing context is now part of this module.
16048 // FIXME: Consider creating a child DeclContext to hold the entities
16049 // lexically within the module.
16050 if (getLangOpts().trackLocalOwningModule()) {
16051 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16052 cast<Decl>(DC)->setHidden(true);
16053 cast<Decl>(DC)->setLocalOwningModule(Mod);
16058 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16059 if (getLangOpts().ModulesLocalVisibility) {
16060 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16061 // Leaving a module hides namespace names, so our visible namespace cache
16062 // is now out of date.
16063 VisibleNamespaceCache.clear();
16066 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16067 "left the wrong module scope");
16068 ModuleScopes.pop_back();
16070 // We got to the end of processing a local module. Create an
16071 // ImportDecl as we would for an imported module.
16072 FileID File = getSourceManager().getFileID(EomLoc);
16073 SourceLocation DirectiveLoc;
16074 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16075 // We reached the end of a #included module header. Use the #include loc.
16076 assert(File != getSourceManager().getMainFileID() &&
16077 "end of submodule in main source file");
16078 DirectiveLoc = getSourceManager().getIncludeLoc(File);
16080 // We reached an EOM pragma. Use the pragma location.
16081 DirectiveLoc = EomLoc;
16083 BuildModuleInclude(DirectiveLoc, Mod);
16085 // Any further declarations are in whatever module we returned to.
16086 if (getLangOpts().trackLocalOwningModule()) {
16087 // The parser guarantees that this is the same context that we entered
16088 // the module within.
16089 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16090 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16091 if (!getCurrentModule())
16092 cast<Decl>(DC)->setHidden(false);
16097 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16099 // Bail if we're not allowed to implicitly import a module here.
16100 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16101 VisibleModules.isVisible(Mod))
16104 // Create the implicit import declaration.
16105 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16106 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16108 TU->addDecl(ImportD);
16109 Consumer.HandleImplicitImportDecl(ImportD);
16111 // Make the module visible.
16112 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16113 VisibleModules.setVisible(Mod, Loc);
16116 /// We have parsed the start of an export declaration, including the '{'
16118 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16119 SourceLocation LBraceLoc) {
16120 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16122 // C++ Modules TS draft:
16123 // An export-declaration shall appear in the purview of a module other than
16124 // the global module.
16125 if (ModuleScopes.empty() || !ModuleScopes.back().Module ||
16126 ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
16127 Diag(ExportLoc, diag::err_export_not_in_module_interface);
16129 // An export-declaration [...] shall not contain more than one
16132 // The intent here is that an export-declaration cannot appear within another
16133 // export-declaration.
16134 if (D->isExported())
16135 Diag(ExportLoc, diag::err_export_within_export);
16137 CurContext->addDecl(D);
16138 PushDeclContext(S, D);
16142 /// Complete the definition of an export declaration.
16143 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16144 auto *ED = cast<ExportDecl>(D);
16145 if (RBraceLoc.isValid())
16146 ED->setRBraceLoc(RBraceLoc);
16148 // FIXME: Diagnose export of internal-linkage declaration (including
16149 // anonymous namespace).
16155 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16156 IdentifierInfo* AliasName,
16157 SourceLocation PragmaLoc,
16158 SourceLocation NameLoc,
16159 SourceLocation AliasNameLoc) {
16160 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16161 LookupOrdinaryName);
16162 AsmLabelAttr *Attr =
16163 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16165 // If a declaration that:
16166 // 1) declares a function or a variable
16167 // 2) has external linkage
16168 // already exists, add a label attribute to it.
16169 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16170 if (isDeclExternC(PrevDecl))
16171 PrevDecl->addAttr(Attr);
16173 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16174 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16175 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16177 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16180 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16181 SourceLocation PragmaLoc,
16182 SourceLocation NameLoc) {
16183 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16186 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16188 (void)WeakUndeclaredIdentifiers.insert(
16189 std::pair<IdentifierInfo*,WeakInfo>
16190 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16194 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16195 IdentifierInfo* AliasName,
16196 SourceLocation PragmaLoc,
16197 SourceLocation NameLoc,
16198 SourceLocation AliasNameLoc) {
16199 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16200 LookupOrdinaryName);
16201 WeakInfo W = WeakInfo(Name, NameLoc);
16203 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16204 if (!PrevDecl->hasAttr<AliasAttr>())
16205 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16206 DeclApplyPragmaWeak(TUScope, ND, W);
16208 (void)WeakUndeclaredIdentifiers.insert(
16209 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16213 Decl *Sema::getObjCDeclContext() const {
16214 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));