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 "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
50 using namespace clang;
53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55 Decl *Group[2] = { OwnedType, Ptr };
56 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
59 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
64 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
67 bool AllowTemplates=false)
68 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
69 AllowClassTemplates(AllowTemplates) {
70 WantExpressionKeywords = false;
71 WantCXXNamedCasts = false;
72 WantRemainingKeywords = false;
75 bool ValidateCandidate(const TypoCorrection &candidate) override {
76 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
77 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
78 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
79 return (IsType || AllowedTemplate) &&
80 (AllowInvalidDecl || !ND->isInvalidDecl());
82 return !WantClassName && candidate.isKeyword();
86 bool AllowInvalidDecl;
88 bool AllowClassTemplates;
93 /// \brief Determine whether the token kind starts a simple-type-specifier.
94 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96 // FIXME: Take into account the current language when deciding whether a
97 // token kind is a valid type specifier
100 case tok::kw___int64:
101 case tok::kw___int128:
103 case tok::kw_unsigned:
110 case tok::kw_wchar_t:
112 case tok::kw___underlying_type:
113 case tok::kw___auto_type:
116 case tok::annot_typename:
117 case tok::kw_char16_t:
118 case tok::kw_char32_t:
120 case tok::annot_decltype:
121 case tok::kw_decltype:
122 return getLangOpts().CPlusPlus;
132 enum class UnqualifiedTypeNameLookupResult {
139 /// \brief Tries to perform unqualified lookup of the type decls in bases for
141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
142 /// type decl, \a FoundType if only type decls are found.
143 static UnqualifiedTypeNameLookupResult
144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
145 SourceLocation NameLoc,
146 const CXXRecordDecl *RD) {
147 if (!RD->hasDefinition())
148 return UnqualifiedTypeNameLookupResult::NotFound;
149 // Look for type decls in base classes.
150 UnqualifiedTypeNameLookupResult FoundTypeDecl =
151 UnqualifiedTypeNameLookupResult::NotFound;
152 for (const auto &Base : RD->bases()) {
153 const CXXRecordDecl *BaseRD = nullptr;
154 if (auto *BaseTT = Base.getType()->getAs<TagType>())
155 BaseRD = BaseTT->getAsCXXRecordDecl();
156 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
157 // Look for type decls in dependent base classes that have known primary
159 if (!TST || !TST->isDependentType())
161 auto *TD = TST->getTemplateName().getAsTemplateDecl();
164 auto *BasePrimaryTemplate =
165 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
166 if (!BasePrimaryTemplate)
168 BaseRD = BasePrimaryTemplate;
171 for (NamedDecl *ND : BaseRD->lookup(&II)) {
172 if (!isa<TypeDecl>(ND))
173 return UnqualifiedTypeNameLookupResult::FoundNonType;
174 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
176 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
177 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
178 case UnqualifiedTypeNameLookupResult::FoundNonType:
179 return UnqualifiedTypeNameLookupResult::FoundNonType;
180 case UnqualifiedTypeNameLookupResult::FoundType:
181 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183 case UnqualifiedTypeNameLookupResult::NotFound:
190 return FoundTypeDecl;
193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
194 const IdentifierInfo &II,
195 SourceLocation NameLoc) {
196 // Lookup in the parent class template context, if any.
197 const CXXRecordDecl *RD = nullptr;
198 UnqualifiedTypeNameLookupResult FoundTypeDecl =
199 UnqualifiedTypeNameLookupResult::NotFound;
200 for (DeclContext *DC = S.CurContext;
201 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
202 DC = DC->getParent()) {
203 // Look for type decls in dependent base classes that have known primary
205 RD = dyn_cast<CXXRecordDecl>(DC);
206 if (RD && RD->getDescribedClassTemplate())
207 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
209 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
212 // We found some types in dependent base classes. Recover as if the user
213 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
214 // lookup during template instantiation.
215 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
217 ASTContext &Context = S.Context;
218 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
219 cast<Type>(Context.getRecordType(RD)));
220 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
223 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
225 TypeLocBuilder Builder;
226 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
227 DepTL.setNameLoc(NameLoc);
228 DepTL.setElaboratedKeywordLoc(SourceLocation());
229 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
230 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
233 /// \brief If the identifier refers to a type name within this scope,
234 /// return the declaration of that type.
236 /// This routine performs ordinary name lookup of the identifier II
237 /// within the given scope, with optional C++ scope specifier SS, to
238 /// determine whether the name refers to a type. If so, returns an
239 /// opaque pointer (actually a QualType) corresponding to that
240 /// type. Otherwise, returns NULL.
241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
242 Scope *S, CXXScopeSpec *SS,
243 bool isClassName, bool HasTrailingDot,
244 ParsedType ObjectTypePtr,
245 bool IsCtorOrDtorName,
246 bool WantNontrivialTypeSourceInfo,
247 IdentifierInfo **CorrectedII) {
248 // Determine where we will perform name lookup.
249 DeclContext *LookupCtx = nullptr;
251 QualType ObjectType = ObjectTypePtr.get();
252 if (ObjectType->isRecordType())
253 LookupCtx = computeDeclContext(ObjectType);
254 } else if (SS && SS->isNotEmpty()) {
255 LookupCtx = computeDeclContext(*SS, false);
258 if (isDependentScopeSpecifier(*SS)) {
260 // A qualified-id that refers to a type and in which the
261 // nested-name-specifier depends on a template-parameter (14.6.2)
262 // shall be prefixed by the keyword typename to indicate that the
263 // qualified-id denotes a type, forming an
264 // elaborated-type-specifier (7.1.5.3).
266 // We therefore do not perform any name lookup if the result would
267 // refer to a member of an unknown specialization.
268 if (!isClassName && !IsCtorOrDtorName)
271 // We know from the grammar that this name refers to a type,
272 // so build a dependent node to describe the type.
273 if (WantNontrivialTypeSourceInfo)
274 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
276 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
277 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
279 return ParsedType::make(T);
285 if (!LookupCtx->isDependentContext() &&
286 RequireCompleteDeclContext(*SS, LookupCtx))
290 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
291 // lookup for class-names.
292 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
294 LookupResult Result(*this, &II, NameLoc, Kind);
296 // Perform "qualified" name lookup into the declaration context we
297 // computed, which is either the type of the base of a member access
298 // expression or the declaration context associated with a prior
299 // nested-name-specifier.
300 LookupQualifiedName(Result, LookupCtx);
302 if (ObjectTypePtr && Result.empty()) {
303 // C++ [basic.lookup.classref]p3:
304 // If the unqualified-id is ~type-name, the type-name is looked up
305 // in the context of the entire postfix-expression. If the type T of
306 // the object expression is of a class type C, the type-name is also
307 // looked up in the scope of class C. At least one of the lookups shall
308 // find a name that refers to (possibly cv-qualified) T.
309 LookupName(Result, S);
312 // Perform unqualified name lookup.
313 LookupName(Result, S);
315 // For unqualified lookup in a class template in MSVC mode, look into
316 // dependent base classes where the primary class template is known.
317 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
318 if (ParsedType TypeInBase =
319 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
324 NamedDecl *IIDecl = nullptr;
325 switch (Result.getResultKind()) {
326 case LookupResult::NotFound:
327 case LookupResult::NotFoundInCurrentInstantiation:
329 TypoCorrection Correction = CorrectTypo(
330 Result.getLookupNameInfo(), Kind, S, SS,
331 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
333 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
335 bool MemberOfUnknownSpecialization;
336 UnqualifiedId TemplateName;
337 TemplateName.setIdentifier(NewII, NameLoc);
338 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
339 CXXScopeSpec NewSS, *NewSSPtr = SS;
341 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
344 if (Correction && (NNS || NewII != &II) &&
345 // Ignore a correction to a template type as the to-be-corrected
346 // identifier is not a template (typo correction for template names
347 // is handled elsewhere).
348 !(getLangOpts().CPlusPlus && NewSSPtr &&
349 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
350 false, Template, MemberOfUnknownSpecialization))) {
351 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
352 isClassName, HasTrailingDot, ObjectTypePtr,
354 WantNontrivialTypeSourceInfo);
356 diagnoseTypo(Correction,
357 PDiag(diag::err_unknown_type_or_class_name_suggest)
358 << Result.getLookupName() << isClassName);
360 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
361 *CorrectedII = NewII;
366 // If typo correction failed or was not performed, fall through
367 case LookupResult::FoundOverloaded:
368 case LookupResult::FoundUnresolvedValue:
369 Result.suppressDiagnostics();
372 case LookupResult::Ambiguous:
373 // Recover from type-hiding ambiguities by hiding the type. We'll
374 // do the lookup again when looking for an object, and we can
375 // diagnose the error then. If we don't do this, then the error
376 // about hiding the type will be immediately followed by an error
377 // that only makes sense if the identifier was treated like a type.
378 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
379 Result.suppressDiagnostics();
383 // Look to see if we have a type anywhere in the list of results.
384 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
385 Res != ResEnd; ++Res) {
386 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
388 (*Res)->getLocation().getRawEncoding() <
389 IIDecl->getLocation().getRawEncoding())
395 // None of the entities we found is a type, so there is no way
396 // to even assume that the result is a type. In this case, don't
397 // complain about the ambiguity. The parser will either try to
398 // perform this lookup again (e.g., as an object name), which
399 // will produce the ambiguity, or will complain that it expected
401 Result.suppressDiagnostics();
405 // We found a type within the ambiguous lookup; diagnose the
406 // ambiguity and then return that type. This might be the right
407 // answer, or it might not be, but it suppresses any attempt to
408 // perform the name lookup again.
411 case LookupResult::Found:
412 IIDecl = Result.getFoundDecl();
416 assert(IIDecl && "Didn't find decl");
419 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
420 DiagnoseUseOfDecl(IIDecl, NameLoc);
422 T = Context.getTypeDeclType(TD);
423 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
425 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
426 // constructor or destructor name (in such a case, the scope specifier
427 // will be attached to the enclosing Expr or Decl node).
428 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
429 if (WantNontrivialTypeSourceInfo) {
430 // Construct a type with type-source information.
431 TypeLocBuilder Builder;
432 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
434 T = getElaboratedType(ETK_None, *SS, T);
435 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
436 ElabTL.setElaboratedKeywordLoc(SourceLocation());
437 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
438 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
440 T = getElaboratedType(ETK_None, *SS, T);
443 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
444 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
446 T = Context.getObjCInterfaceType(IDecl);
450 // If it's not plausibly a type, suppress diagnostics.
451 Result.suppressDiagnostics();
454 return ParsedType::make(T);
457 // Builds a fake NNS for the given decl context.
458 static NestedNameSpecifier *
459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
460 for (;; DC = DC->getLookupParent()) {
461 DC = DC->getPrimaryContext();
462 auto *ND = dyn_cast<NamespaceDecl>(DC);
463 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
464 return NestedNameSpecifier::Create(Context, nullptr, ND);
465 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
466 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
467 RD->getTypeForDecl());
468 else if (isa<TranslationUnitDecl>(DC))
469 return NestedNameSpecifier::GlobalSpecifier(Context);
471 llvm_unreachable("something isn't in TU scope?");
474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
475 SourceLocation NameLoc) {
476 // Accepting an undeclared identifier as a default argument for a template
477 // type parameter is a Microsoft extension.
478 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
480 // Build a fake DependentNameType that will perform lookup into CurContext at
481 // instantiation time. The name specifier isn't dependent, so template
482 // instantiation won't transform it. It will retry the lookup, however.
483 NestedNameSpecifier *NNS =
484 synthesizeCurrentNestedNameSpecifier(Context, CurContext);
485 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
487 // Build type location information. We synthesized the qualifier, so we have
488 // to build a fake NestedNameSpecifierLoc.
489 NestedNameSpecifierLocBuilder NNSLocBuilder;
490 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
491 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
493 TypeLocBuilder Builder;
494 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
495 DepTL.setNameLoc(NameLoc);
496 DepTL.setElaboratedKeywordLoc(SourceLocation());
497 DepTL.setQualifierLoc(QualifierLoc);
498 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
501 /// isTagName() - This method is called *for error recovery purposes only*
502 /// to determine if the specified name is a valid tag name ("struct foo"). If
503 /// so, this returns the TST for the tag corresponding to it (TST_enum,
504 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
505 /// cases in C where the user forgot to specify the tag.
506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
507 // Do a tag name lookup in this scope.
508 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
509 LookupName(R, S, false);
510 R.suppressDiagnostics();
511 if (R.getResultKind() == LookupResult::Found)
512 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
513 switch (TD->getTagKind()) {
514 case TTK_Struct: return DeclSpec::TST_struct;
515 case TTK_Interface: return DeclSpec::TST_interface;
516 case TTK_Union: return DeclSpec::TST_union;
517 case TTK_Class: return DeclSpec::TST_class;
518 case TTK_Enum: return DeclSpec::TST_enum;
522 return DeclSpec::TST_unspecified;
525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
527 /// then downgrade the missing typename error to a warning.
528 /// This is needed for MSVC compatibility; Example:
530 /// template<class T> class A {
532 /// typedef int TYPE;
534 /// template<class T> class B : public A<T> {
536 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
540 if (CurContext->isRecord()) {
541 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
544 const Type *Ty = SS->getScopeRep()->getAsType();
546 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
547 for (const auto &Base : RD->bases())
548 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
550 return S->isFunctionPrototypeScope();
552 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
556 SourceLocation IILoc,
559 ParsedType &SuggestedType,
560 bool AllowClassTemplates) {
561 // We don't have anything to suggest (yet).
562 SuggestedType = ParsedType();
564 // There may have been a typo in the name of the type. Look up typo
565 // results, in case we have something that we can suggest.
566 if (TypoCorrection Corrected =
567 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
568 llvm::make_unique<TypeNameValidatorCCC>(
569 false, false, AllowClassTemplates),
570 CTK_ErrorRecovery)) {
571 if (Corrected.isKeyword()) {
572 // We corrected to a keyword.
573 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
574 II = Corrected.getCorrectionAsIdentifierInfo();
576 // We found a similarly-named type or interface; suggest that.
577 if (!SS || !SS->isSet()) {
578 diagnoseTypo(Corrected,
579 PDiag(diag::err_unknown_typename_suggest) << II);
580 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
581 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
582 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
583 II->getName().equals(CorrectedStr);
584 diagnoseTypo(Corrected,
585 PDiag(diag::err_unknown_nested_typename_suggest)
586 << II << DC << DroppedSpecifier << SS->getRange());
588 llvm_unreachable("could not have corrected a typo here");
592 if (Corrected.getCorrectionSpecifier())
593 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
595 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
596 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
598 /*IsCtorOrDtorName=*/false,
599 /*NonTrivialTypeSourceInfo=*/true);
604 if (getLangOpts().CPlusPlus) {
605 // See if II is a class template that the user forgot to pass arguments to.
607 Name.setIdentifier(II, IILoc);
608 CXXScopeSpec EmptySS;
609 TemplateTy TemplateResult;
610 bool MemberOfUnknownSpecialization;
611 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
612 Name, ParsedType(), true, TemplateResult,
613 MemberOfUnknownSpecialization) == TNK_Type_template) {
614 TemplateName TplName = TemplateResult.get();
615 Diag(IILoc, diag::err_template_missing_args) << TplName;
616 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
617 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
618 << TplDecl->getTemplateParameters()->getSourceRange();
624 // FIXME: Should we move the logic that tries to recover from a missing tag
625 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
627 if (!SS || (!SS->isSet() && !SS->isInvalid()))
628 Diag(IILoc, diag::err_unknown_typename) << II;
629 else if (DeclContext *DC = computeDeclContext(*SS, false))
630 Diag(IILoc, diag::err_typename_nested_not_found)
631 << II << DC << SS->getRange();
632 else if (isDependentScopeSpecifier(*SS)) {
633 unsigned DiagID = diag::err_typename_missing;
634 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
635 DiagID = diag::ext_typename_missing;
637 Diag(SS->getRange().getBegin(), DiagID)
638 << SS->getScopeRep() << II->getName()
639 << SourceRange(SS->getRange().getBegin(), IILoc)
640 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
641 SuggestedType = ActOnTypenameType(S, SourceLocation(),
642 *SS, *II, IILoc).get();
644 assert(SS && SS->isInvalid() &&
645 "Invalid scope specifier has already been diagnosed");
649 /// \brief Determine whether the given result set contains either a type name
651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
652 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
653 NextToken.is(tok::less);
655 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
656 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
659 if (CheckTemplate && isa<TemplateDecl>(*I))
666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
667 Scope *S, CXXScopeSpec &SS,
668 IdentifierInfo *&Name,
669 SourceLocation NameLoc) {
670 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
671 SemaRef.LookupParsedName(R, S, &SS);
672 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
673 StringRef FixItTagName;
674 switch (Tag->getTagKind()) {
676 FixItTagName = "class ";
680 FixItTagName = "enum ";
684 FixItTagName = "struct ";
688 FixItTagName = "__interface ";
692 FixItTagName = "union ";
696 StringRef TagName = FixItTagName.drop_back();
697 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
698 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
699 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
701 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
703 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
706 // Replace lookup results with just the tag decl.
707 Result.clear(Sema::LookupTagName);
708 SemaRef.LookupParsedName(Result, S, &SS);
715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
717 QualType T, SourceLocation NameLoc) {
718 ASTContext &Context = S.Context;
720 TypeLocBuilder Builder;
721 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
723 T = S.getElaboratedType(ETK_None, SS, T);
724 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
725 ElabTL.setElaboratedKeywordLoc(SourceLocation());
726 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
727 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
730 Sema::NameClassification
731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
732 SourceLocation NameLoc, const Token &NextToken,
733 bool IsAddressOfOperand,
734 std::unique_ptr<CorrectionCandidateCallback> CCC) {
735 DeclarationNameInfo NameInfo(Name, NameLoc);
736 ObjCMethodDecl *CurMethod = getCurMethodDecl();
738 if (NextToken.is(tok::coloncolon)) {
739 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
740 QualType(), false, SS, nullptr, false);
743 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
744 LookupParsedName(Result, S, &SS, !CurMethod);
746 // For unqualified lookup in a class template in MSVC mode, look into
747 // dependent base classes where the primary class template is known.
748 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
749 if (ParsedType TypeInBase =
750 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
754 // Perform lookup for Objective-C instance variables (including automatically
755 // synthesized instance variables), if we're in an Objective-C method.
756 // FIXME: This lookup really, really needs to be folded in to the normal
757 // unqualified lookup mechanism.
758 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
759 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
760 if (E.get() || E.isInvalid())
764 bool SecondTry = false;
765 bool IsFilteredTemplateName = false;
768 switch (Result.getResultKind()) {
769 case LookupResult::NotFound:
770 // If an unqualified-id is followed by a '(', then we have a function
772 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
773 // In C++, this is an ADL-only call.
775 if (getLangOpts().CPlusPlus)
776 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
779 // If the expression that precedes the parenthesized argument list in a
780 // function call consists solely of an identifier, and if no
781 // declaration is visible for this identifier, the identifier is
782 // implicitly declared exactly as if, in the innermost block containing
783 // the function call, the declaration
785 // extern int identifier ();
789 // We also allow this in C99 as an extension.
790 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
792 Result.resolveKind();
793 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
797 // In C, we first see whether there is a tag type by the same name, in
798 // which case it's likely that the user just forgot to write "enum",
799 // "struct", or "union".
800 if (!getLangOpts().CPlusPlus && !SecondTry &&
801 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
805 // Perform typo correction to determine if there is another name that is
806 // close to this name.
807 if (!SecondTry && CCC) {
809 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
810 Result.getLookupKind(), S,
812 CTK_ErrorRecovery)) {
813 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
814 unsigned QualifiedDiag = diag::err_no_member_suggest;
816 NamedDecl *FirstDecl = Corrected.getFoundDecl();
817 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
818 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
819 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
820 UnqualifiedDiag = diag::err_no_template_suggest;
821 QualifiedDiag = diag::err_no_member_template_suggest;
822 } else if (UnderlyingFirstDecl &&
823 (isa<TypeDecl>(UnderlyingFirstDecl) ||
824 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
825 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
826 UnqualifiedDiag = diag::err_unknown_typename_suggest;
827 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
831 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
832 } else {// FIXME: is this even reachable? Test it.
833 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
834 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
835 Name->getName().equals(CorrectedStr);
836 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
837 << Name << computeDeclContext(SS, false)
838 << DroppedSpecifier << SS.getRange());
841 // Update the name, so that the caller has the new name.
842 Name = Corrected.getCorrectionAsIdentifierInfo();
844 // Typo correction corrected to a keyword.
845 if (Corrected.isKeyword())
848 // Also update the LookupResult...
849 // FIXME: This should probably go away at some point
851 Result.setLookupName(Corrected.getCorrection());
853 Result.addDecl(FirstDecl);
855 // If we found an Objective-C instance variable, let
856 // LookupInObjCMethod build the appropriate expression to
857 // reference the ivar.
858 // FIXME: This is a gross hack.
859 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
861 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
869 // We failed to correct; just fall through and let the parser deal with it.
870 Result.suppressDiagnostics();
871 return NameClassification::Unknown();
873 case LookupResult::NotFoundInCurrentInstantiation: {
874 // We performed name lookup into the current instantiation, and there were
875 // dependent bases, so we treat this result the same way as any other
876 // dependent nested-name-specifier.
879 // A name used in a template declaration or definition and that is
880 // dependent on a template-parameter is assumed not to name a type
881 // unless the applicable name lookup finds a type name or the name is
882 // qualified by the keyword typename.
884 // FIXME: If the next token is '<', we might want to ask the parser to
885 // perform some heroics to see if we actually have a
886 // template-argument-list, which would indicate a missing 'template'
888 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
889 NameInfo, IsAddressOfOperand,
890 /*TemplateArgs=*/nullptr);
893 case LookupResult::Found:
894 case LookupResult::FoundOverloaded:
895 case LookupResult::FoundUnresolvedValue:
898 case LookupResult::Ambiguous:
899 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
900 hasAnyAcceptableTemplateNames(Result)) {
901 // C++ [temp.local]p3:
902 // A lookup that finds an injected-class-name (10.2) can result in an
903 // ambiguity in certain cases (for example, if it is found in more than
904 // one base class). If all of the injected-class-names that are found
905 // refer to specializations of the same class template, and if the name
906 // is followed by a template-argument-list, the reference refers to the
907 // class template itself and not a specialization thereof, and is not
910 // This filtering can make an ambiguous result into an unambiguous one,
911 // so try again after filtering out template names.
912 FilterAcceptableTemplateNames(Result);
913 if (!Result.isAmbiguous()) {
914 IsFilteredTemplateName = true;
919 // Diagnose the ambiguity and return an error.
920 return NameClassification::Error();
923 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
924 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
925 // C++ [temp.names]p3:
926 // After name lookup (3.4) finds that a name is a template-name or that
927 // an operator-function-id or a literal- operator-id refers to a set of
928 // overloaded functions any member of which is a function template if
929 // this is followed by a <, the < is always taken as the delimiter of a
930 // template-argument-list and never as the less-than operator.
931 if (!IsFilteredTemplateName)
932 FilterAcceptableTemplateNames(Result);
934 if (!Result.empty()) {
935 bool IsFunctionTemplate;
937 TemplateName Template;
938 if (Result.end() - Result.begin() > 1) {
939 IsFunctionTemplate = true;
940 Template = Context.getOverloadedTemplateName(Result.begin(),
944 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
945 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
946 IsVarTemplate = isa<VarTemplateDecl>(TD);
948 if (SS.isSet() && !SS.isInvalid())
949 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
950 /*TemplateKeyword=*/false,
953 Template = TemplateName(TD);
956 if (IsFunctionTemplate) {
957 // Function templates always go through overload resolution, at which
958 // point we'll perform the various checks (e.g., accessibility) we need
959 // to based on which function we selected.
960 Result.suppressDiagnostics();
962 return NameClassification::FunctionTemplate(Template);
965 return IsVarTemplate ? NameClassification::VarTemplate(Template)
966 : NameClassification::TypeTemplate(Template);
970 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
971 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
972 DiagnoseUseOfDecl(Type, NameLoc);
973 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
974 QualType T = Context.getTypeDeclType(Type);
976 return buildNestedType(*this, SS, T, NameLoc);
977 return ParsedType::make(T);
980 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
982 // FIXME: It's unfortunate that we don't have a Type node for handling this.
983 if (ObjCCompatibleAliasDecl *Alias =
984 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
985 Class = Alias->getClassInterface();
989 DiagnoseUseOfDecl(Class, NameLoc);
991 if (NextToken.is(tok::period)) {
992 // Interface. <something> is parsed as a property reference expression.
993 // Just return "unknown" as a fall-through for now.
994 Result.suppressDiagnostics();
995 return NameClassification::Unknown();
998 QualType T = Context.getObjCInterfaceType(Class);
999 return ParsedType::make(T);
1002 // We can have a type template here if we're classifying a template argument.
1003 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1004 return NameClassification::TypeTemplate(
1005 TemplateName(cast<TemplateDecl>(FirstDecl)));
1007 // Check for a tag type hidden by a non-type decl in a few cases where it
1008 // seems likely a type is wanted instead of the non-type that was found.
1009 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1010 if ((NextToken.is(tok::identifier) ||
1012 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1013 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1014 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1015 DiagnoseUseOfDecl(Type, NameLoc);
1016 QualType T = Context.getTypeDeclType(Type);
1017 if (SS.isNotEmpty())
1018 return buildNestedType(*this, SS, T, NameLoc);
1019 return ParsedType::make(T);
1022 if (FirstDecl->isCXXClassMember())
1023 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1026 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1027 return BuildDeclarationNameExpr(SS, Result, ADL);
1030 // Determines the context to return to after temporarily entering a
1031 // context. This depends in an unnecessarily complicated way on the
1032 // exact ordering of callbacks from the parser.
1033 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1035 // Functions defined inline within classes aren't parsed until we've
1036 // finished parsing the top-level class, so the top-level class is
1037 // the context we'll need to return to.
1038 // A Lambda call operator whose parent is a class must not be treated
1039 // as an inline member function. A Lambda can be used legally
1040 // either as an in-class member initializer or a default argument. These
1041 // are parsed once the class has been marked complete and so the containing
1042 // context would be the nested class (when the lambda is defined in one);
1043 // If the class is not complete, then the lambda is being used in an
1044 // ill-formed fashion (such as to specify the width of a bit-field, or
1045 // in an array-bound) - in which case we still want to return the
1046 // lexically containing DC (which could be a nested class).
1047 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1048 DC = DC->getLexicalParent();
1050 // A function not defined within a class will always return to its
1052 if (!isa<CXXRecordDecl>(DC))
1055 // A C++ inline method/friend is parsed *after* the topmost class
1056 // it was declared in is fully parsed ("complete"); the topmost
1057 // class is the context we need to return to.
1058 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1061 // Return the declaration context of the topmost class the inline method is
1066 return DC->getLexicalParent();
1069 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1070 assert(getContainingDC(DC) == CurContext &&
1071 "The next DeclContext should be lexically contained in the current one.");
1076 void Sema::PopDeclContext() {
1077 assert(CurContext && "DeclContext imbalance!");
1079 CurContext = getContainingDC(CurContext);
1080 assert(CurContext && "Popped translation unit!");
1083 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1085 // Unlike PushDeclContext, the context to which we return is not necessarily
1086 // the containing DC of TD, because the new context will be some pre-existing
1087 // TagDecl definition instead of a fresh one.
1088 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1089 CurContext = cast<TagDecl>(D)->getDefinition();
1090 assert(CurContext && "skipping definition of undefined tag");
1091 // Start lookups from the parent of the current context; we don't want to look
1092 // into the pre-existing complete definition.
1093 S->setEntity(CurContext->getLookupParent());
1097 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1098 CurContext = static_cast<decltype(CurContext)>(Context);
1101 /// EnterDeclaratorContext - Used when we must lookup names in the context
1102 /// of a declarator's nested name specifier.
1104 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1105 // C++0x [basic.lookup.unqual]p13:
1106 // A name used in the definition of a static data member of class
1107 // X (after the qualified-id of the static member) is looked up as
1108 // if the name was used in a member function of X.
1109 // C++0x [basic.lookup.unqual]p14:
1110 // If a variable member of a namespace is defined outside of the
1111 // scope of its namespace then any name used in the definition of
1112 // the variable member (after the declarator-id) is looked up as
1113 // if the definition of the variable member occurred in its
1115 // Both of these imply that we should push a scope whose context
1116 // is the semantic context of the declaration. We can't use
1117 // PushDeclContext here because that context is not necessarily
1118 // lexically contained in the current context. Fortunately,
1119 // the containing scope should have the appropriate information.
1121 assert(!S->getEntity() && "scope already has entity");
1124 Scope *Ancestor = S->getParent();
1125 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1126 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1133 void Sema::ExitDeclaratorContext(Scope *S) {
1134 assert(S->getEntity() == CurContext && "Context imbalance!");
1136 // Switch back to the lexical context. The safety of this is
1137 // enforced by an assert in EnterDeclaratorContext.
1138 Scope *Ancestor = S->getParent();
1139 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1140 CurContext = Ancestor->getEntity();
1142 // We don't need to do anything with the scope, which is going to
1147 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1148 // We assume that the caller has already called
1149 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1150 FunctionDecl *FD = D->getAsFunction();
1154 // Same implementation as PushDeclContext, but enters the context
1155 // from the lexical parent, rather than the top-level class.
1156 assert(CurContext == FD->getLexicalParent() &&
1157 "The next DeclContext should be lexically contained in the current one.");
1159 S->setEntity(CurContext);
1161 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1162 ParmVarDecl *Param = FD->getParamDecl(P);
1163 // If the parameter has an identifier, then add it to the scope
1164 if (Param->getIdentifier()) {
1166 IdResolver.AddDecl(Param);
1172 void Sema::ActOnExitFunctionContext() {
1173 // Same implementation as PopDeclContext, but returns to the lexical parent,
1174 // rather than the top-level class.
1175 assert(CurContext && "DeclContext imbalance!");
1176 CurContext = CurContext->getLexicalParent();
1177 assert(CurContext && "Popped translation unit!");
1181 /// \brief Determine whether we allow overloading of the function
1182 /// PrevDecl with another declaration.
1184 /// This routine determines whether overloading is possible, not
1185 /// whether some new function is actually an overload. It will return
1186 /// true in C++ (where we can always provide overloads) or, as an
1187 /// extension, in C when the previous function is already an
1188 /// overloaded function declaration or has the "overloadable"
1190 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1191 ASTContext &Context) {
1192 if (Context.getLangOpts().CPlusPlus)
1195 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1198 return (Previous.getResultKind() == LookupResult::Found
1199 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1202 /// Add this decl to the scope shadowed decl chains.
1203 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1204 // Move up the scope chain until we find the nearest enclosing
1205 // non-transparent context. The declaration will be introduced into this
1207 while (S->getEntity() && S->getEntity()->isTransparentContext())
1210 // Add scoped declarations into their context, so that they can be
1211 // found later. Declarations without a context won't be inserted
1212 // into any context.
1214 CurContext->addDecl(D);
1216 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1217 // are function-local declarations.
1218 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1219 !D->getDeclContext()->getRedeclContext()->Equals(
1220 D->getLexicalDeclContext()->getRedeclContext()) &&
1221 !D->getLexicalDeclContext()->isFunctionOrMethod())
1224 // Template instantiations should also not be pushed into scope.
1225 if (isa<FunctionDecl>(D) &&
1226 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1229 // If this replaces anything in the current scope,
1230 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1231 IEnd = IdResolver.end();
1232 for (; I != IEnd; ++I) {
1233 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1235 IdResolver.RemoveDecl(*I);
1237 // Should only need to replace one decl.
1244 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1245 // Implicitly-generated labels may end up getting generated in an order that
1246 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1247 // the label at the appropriate place in the identifier chain.
1248 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1249 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1250 if (IDC == CurContext) {
1251 if (!S->isDeclScope(*I))
1253 } else if (IDC->Encloses(CurContext))
1257 IdResolver.InsertDeclAfter(I, D);
1259 IdResolver.AddDecl(D);
1263 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1264 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1265 TUScope->AddDecl(D);
1268 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1269 bool AllowInlineNamespace) {
1270 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1273 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1274 DeclContext *TargetDC = DC->getPrimaryContext();
1276 if (DeclContext *ScopeDC = S->getEntity())
1277 if (ScopeDC->getPrimaryContext() == TargetDC)
1279 } while ((S = S->getParent()));
1284 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1288 /// Filters out lookup results that don't fall within the given scope
1289 /// as determined by isDeclInScope.
1290 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1291 bool ConsiderLinkage,
1292 bool AllowInlineNamespace) {
1293 LookupResult::Filter F = R.makeFilter();
1294 while (F.hasNext()) {
1295 NamedDecl *D = F.next();
1297 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1300 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1309 static bool isUsingDecl(NamedDecl *D) {
1310 return isa<UsingShadowDecl>(D) ||
1311 isa<UnresolvedUsingTypenameDecl>(D) ||
1312 isa<UnresolvedUsingValueDecl>(D);
1315 /// Removes using shadow declarations from the lookup results.
1316 static void RemoveUsingDecls(LookupResult &R) {
1317 LookupResult::Filter F = R.makeFilter();
1319 if (isUsingDecl(F.next()))
1325 /// \brief Check for this common pattern:
1328 /// S(const S&); // DO NOT IMPLEMENT
1329 /// void operator=(const S&); // DO NOT IMPLEMENT
1332 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1333 // FIXME: Should check for private access too but access is set after we get
1335 if (D->doesThisDeclarationHaveABody())
1338 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1339 return CD->isCopyConstructor();
1340 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1341 return Method->isCopyAssignmentOperator();
1345 // We need this to handle
1348 // void *foo() { return 0; }
1351 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1352 // for example. If 'A', foo will have external linkage. If we have '*A',
1353 // foo will have no linkage. Since we can't know until we get to the end
1354 // of the typedef, this function finds out if D might have non-external linkage.
1355 // Callers should verify at the end of the TU if it D has external linkage or
1357 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1358 const DeclContext *DC = D->getDeclContext();
1359 while (!DC->isTranslationUnit()) {
1360 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1361 if (!RD->hasNameForLinkage())
1364 DC = DC->getParent();
1367 return !D->isExternallyVisible();
1370 // FIXME: This needs to be refactored; some other isInMainFile users want
1372 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1373 if (S.TUKind != TU_Complete)
1375 return S.SourceMgr.isInMainFile(Loc);
1378 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1381 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1384 // Ignore all entities declared within templates, and out-of-line definitions
1385 // of members of class templates.
1386 if (D->getDeclContext()->isDependentContext() ||
1387 D->getLexicalDeclContext()->isDependentContext())
1390 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1391 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1394 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1395 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1398 // 'static inline' functions are defined in headers; don't warn.
1399 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1403 if (FD->doesThisDeclarationHaveABody() &&
1404 Context.DeclMustBeEmitted(FD))
1406 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1407 // Constants and utility variables are defined in headers with internal
1408 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1410 if (!isMainFileLoc(*this, VD->getLocation()))
1413 if (Context.DeclMustBeEmitted(VD))
1416 if (VD->isStaticDataMember() &&
1417 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1423 // Only warn for unused decls internal to the translation unit.
1424 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1425 // for inline functions defined in the main source file, for instance.
1426 return mightHaveNonExternalLinkage(D);
1429 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1433 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1434 const FunctionDecl *First = FD->getFirstDecl();
1435 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1436 return; // First should already be in the vector.
1439 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1440 const VarDecl *First = VD->getFirstDecl();
1441 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1442 return; // First should already be in the vector.
1445 if (ShouldWarnIfUnusedFileScopedDecl(D))
1446 UnusedFileScopedDecls.push_back(D);
1449 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1450 if (D->isInvalidDecl())
1453 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1454 D->hasAttr<ObjCPreciseLifetimeAttr>())
1457 if (isa<LabelDecl>(D))
1460 // Except for labels, we only care about unused decls that are local to
1462 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1463 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1464 // For dependent types, the diagnostic is deferred.
1466 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1467 if (!WithinFunction)
1470 if (isa<TypedefNameDecl>(D))
1473 // White-list anything that isn't a local variable.
1474 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1477 // Types of valid local variables should be complete, so this should succeed.
1478 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1480 // White-list anything with an __attribute__((unused)) type.
1481 QualType Ty = VD->getType();
1483 // Only look at the outermost level of typedef.
1484 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1485 if (TT->getDecl()->hasAttr<UnusedAttr>())
1489 // If we failed to complete the type for some reason, or if the type is
1490 // dependent, don't diagnose the variable.
1491 if (Ty->isIncompleteType() || Ty->isDependentType())
1494 if (const TagType *TT = Ty->getAs<TagType>()) {
1495 const TagDecl *Tag = TT->getDecl();
1496 if (Tag->hasAttr<UnusedAttr>())
1499 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1500 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1503 if (const Expr *Init = VD->getInit()) {
1504 if (const ExprWithCleanups *Cleanups =
1505 dyn_cast<ExprWithCleanups>(Init))
1506 Init = Cleanups->getSubExpr();
1507 const CXXConstructExpr *Construct =
1508 dyn_cast<CXXConstructExpr>(Init);
1509 if (Construct && !Construct->isElidable()) {
1510 CXXConstructorDecl *CD = Construct->getConstructor();
1511 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1518 // TODO: __attribute__((unused)) templates?
1524 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1526 if (isa<LabelDecl>(D)) {
1527 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1528 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1529 if (AfterColon.isInvalid())
1531 Hint = FixItHint::CreateRemoval(CharSourceRange::
1532 getCharRange(D->getLocStart(), AfterColon));
1537 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1538 if (D->getTypeForDecl()->isDependentType())
1541 for (auto *TmpD : D->decls()) {
1542 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1543 DiagnoseUnusedDecl(T);
1544 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1545 DiagnoseUnusedNestedTypedefs(R);
1549 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1550 /// unless they are marked attr(unused).
1551 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1552 if (!ShouldDiagnoseUnusedDecl(D))
1555 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1556 // typedefs can be referenced later on, so the diagnostics are emitted
1557 // at end-of-translation-unit.
1558 UnusedLocalTypedefNameCandidates.insert(TD);
1563 GenerateFixForUnusedDecl(D, Context, Hint);
1566 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1567 DiagID = diag::warn_unused_exception_param;
1568 else if (isa<LabelDecl>(D))
1569 DiagID = diag::warn_unused_label;
1571 DiagID = diag::warn_unused_variable;
1573 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1576 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1577 // Verify that we have no forward references left. If so, there was a goto
1578 // or address of a label taken, but no definition of it. Label fwd
1579 // definitions are indicated with a null substmt which is also not a resolved
1580 // MS inline assembly label name.
1581 bool Diagnose = false;
1582 if (L->isMSAsmLabel())
1583 Diagnose = !L->isResolvedMSAsmLabel();
1585 Diagnose = L->getStmt() == nullptr;
1587 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1590 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1591 S->mergeNRVOIntoParent();
1593 if (S->decl_empty()) return;
1594 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1595 "Scope shouldn't contain decls!");
1597 for (auto *TmpD : S->decls()) {
1598 assert(TmpD && "This decl didn't get pushed??");
1600 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1601 NamedDecl *D = cast<NamedDecl>(TmpD);
1603 if (!D->getDeclName()) continue;
1605 // Diagnose unused variables in this scope.
1606 if (!S->hasUnrecoverableErrorOccurred()) {
1607 DiagnoseUnusedDecl(D);
1608 if (const auto *RD = dyn_cast<RecordDecl>(D))
1609 DiagnoseUnusedNestedTypedefs(RD);
1612 // If this was a forward reference to a label, verify it was defined.
1613 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1614 CheckPoppedLabel(LD, *this);
1616 // Remove this name from our lexical scope.
1617 IdResolver.RemoveDecl(D);
1621 /// \brief Look for an Objective-C class in the translation unit.
1623 /// \param Id The name of the Objective-C class we're looking for. If
1624 /// typo-correction fixes this name, the Id will be updated
1625 /// to the fixed name.
1627 /// \param IdLoc The location of the name in the translation unit.
1629 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1630 /// if there is no class with the given name.
1632 /// \returns The declaration of the named Objective-C class, or NULL if the
1633 /// class could not be found.
1634 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1635 SourceLocation IdLoc,
1636 bool DoTypoCorrection) {
1637 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1638 // creation from this context.
1639 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1641 if (!IDecl && DoTypoCorrection) {
1642 // Perform typo correction at the given location, but only if we
1643 // find an Objective-C class name.
1644 if (TypoCorrection C = CorrectTypo(
1645 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1646 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1647 CTK_ErrorRecovery)) {
1648 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1649 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1650 Id = IDecl->getIdentifier();
1653 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1654 // This routine must always return a class definition, if any.
1655 if (Def && Def->getDefinition())
1656 Def = Def->getDefinition();
1660 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1661 /// from S, where a non-field would be declared. This routine copes
1662 /// with the difference between C and C++ scoping rules in structs and
1663 /// unions. For example, the following code is well-formed in C but
1664 /// ill-formed in C++:
1670 /// void test_S6() {
1675 /// For the declaration of BAR, this routine will return a different
1676 /// scope. The scope S will be the scope of the unnamed enumeration
1677 /// within S6. In C++, this routine will return the scope associated
1678 /// with S6, because the enumeration's scope is a transparent
1679 /// context but structures can contain non-field names. In C, this
1680 /// routine will return the translation unit scope, since the
1681 /// enumeration's scope is a transparent context and structures cannot
1682 /// contain non-field names.
1683 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1684 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1685 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1686 (S->isClassScope() && !getLangOpts().CPlusPlus))
1691 /// \brief Looks up the declaration of "struct objc_super" and
1692 /// saves it for later use in building builtin declaration of
1693 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1694 /// pre-existing declaration exists no action takes place.
1695 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1696 IdentifierInfo *II) {
1697 if (!II->isStr("objc_msgSendSuper"))
1699 ASTContext &Context = ThisSema.Context;
1701 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1702 SourceLocation(), Sema::LookupTagName);
1703 ThisSema.LookupName(Result, S);
1704 if (Result.getResultKind() == LookupResult::Found)
1705 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1706 Context.setObjCSuperType(Context.getTagDeclType(TD));
1709 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1711 case ASTContext::GE_None:
1713 case ASTContext::GE_Missing_stdio:
1715 case ASTContext::GE_Missing_setjmp:
1717 case ASTContext::GE_Missing_ucontext:
1718 return "ucontext.h";
1720 llvm_unreachable("unhandled error kind");
1723 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1724 /// file scope. lazily create a decl for it. ForRedeclaration is true
1725 /// if we're creating this built-in in anticipation of redeclaring the
1727 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1728 Scope *S, bool ForRedeclaration,
1729 SourceLocation Loc) {
1730 LookupPredefedObjCSuperType(*this, S, II);
1732 ASTContext::GetBuiltinTypeError Error;
1733 QualType R = Context.GetBuiltinType(ID, Error);
1735 if (ForRedeclaration)
1736 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1737 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1741 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1742 Diag(Loc, diag::ext_implicit_lib_function_decl)
1743 << Context.BuiltinInfo.getName(ID) << R;
1744 if (Context.BuiltinInfo.getHeaderName(ID) &&
1745 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1746 Diag(Loc, diag::note_include_header_or_declare)
1747 << Context.BuiltinInfo.getHeaderName(ID)
1748 << Context.BuiltinInfo.getName(ID);
1751 DeclContext *Parent = Context.getTranslationUnitDecl();
1752 if (getLangOpts().CPlusPlus) {
1753 LinkageSpecDecl *CLinkageDecl =
1754 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1755 LinkageSpecDecl::lang_c, false);
1756 CLinkageDecl->setImplicit();
1757 Parent->addDecl(CLinkageDecl);
1758 Parent = CLinkageDecl;
1761 FunctionDecl *New = FunctionDecl::Create(Context,
1763 Loc, Loc, II, R, /*TInfo=*/nullptr,
1766 R->isFunctionProtoType());
1769 // Create Decl objects for each parameter, adding them to the
1771 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1772 SmallVector<ParmVarDecl*, 16> Params;
1773 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1775 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1776 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1778 parm->setScopeInfo(0, i);
1779 Params.push_back(parm);
1781 New->setParams(Params);
1784 AddKnownFunctionAttributes(New);
1785 RegisterLocallyScopedExternCDecl(New, S);
1787 // TUScope is the translation-unit scope to insert this function into.
1788 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1789 // relate Scopes to DeclContexts, and probably eliminate CurContext
1790 // entirely, but we're not there yet.
1791 DeclContext *SavedContext = CurContext;
1792 CurContext = Parent;
1793 PushOnScopeChains(New, TUScope);
1794 CurContext = SavedContext;
1798 /// Typedef declarations don't have linkage, but they still denote the same
1799 /// entity if their types are the same.
1800 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1802 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1803 TypedefNameDecl *Decl,
1804 LookupResult &Previous) {
1805 // This is only interesting when modules are enabled.
1806 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1809 // Empty sets are uninteresting.
1810 if (Previous.empty())
1813 LookupResult::Filter Filter = Previous.makeFilter();
1814 while (Filter.hasNext()) {
1815 NamedDecl *Old = Filter.next();
1817 // Non-hidden declarations are never ignored.
1818 if (S.isVisible(Old))
1821 // Declarations of the same entity are not ignored, even if they have
1822 // different linkages.
1823 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1824 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1825 Decl->getUnderlyingType()))
1828 // If both declarations give a tag declaration a typedef name for linkage
1829 // purposes, then they declare the same entity.
1830 if (S.getLangOpts().CPlusPlus &&
1831 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1832 Decl->getAnonDeclWithTypedefName())
1842 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1844 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1845 OldType = OldTypedef->getUnderlyingType();
1847 OldType = Context.getTypeDeclType(Old);
1848 QualType NewType = New->getUnderlyingType();
1850 if (NewType->isVariablyModifiedType()) {
1851 // Must not redefine a typedef with a variably-modified type.
1852 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1853 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1855 if (Old->getLocation().isValid())
1856 Diag(Old->getLocation(), diag::note_previous_definition);
1857 New->setInvalidDecl();
1861 if (OldType != NewType &&
1862 !OldType->isDependentType() &&
1863 !NewType->isDependentType() &&
1864 !Context.hasSameType(OldType, NewType)) {
1865 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1866 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1867 << Kind << NewType << OldType;
1868 if (Old->getLocation().isValid())
1869 Diag(Old->getLocation(), diag::note_previous_definition);
1870 New->setInvalidDecl();
1876 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1877 /// same name and scope as a previous declaration 'Old'. Figure out
1878 /// how to resolve this situation, merging decls or emitting
1879 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1881 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1882 LookupResult &OldDecls) {
1883 // If the new decl is known invalid already, don't bother doing any
1885 if (New->isInvalidDecl()) return;
1887 // Allow multiple definitions for ObjC built-in typedefs.
1888 // FIXME: Verify the underlying types are equivalent!
1889 if (getLangOpts().ObjC1) {
1890 const IdentifierInfo *TypeID = New->getIdentifier();
1891 switch (TypeID->getLength()) {
1895 if (!TypeID->isStr("id"))
1897 QualType T = New->getUnderlyingType();
1898 if (!T->isPointerType())
1900 if (!T->isVoidPointerType()) {
1901 QualType PT = T->getAs<PointerType>()->getPointeeType();
1902 if (!PT->isStructureType())
1905 Context.setObjCIdRedefinitionType(T);
1906 // Install the built-in type for 'id', ignoring the current definition.
1907 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1911 if (!TypeID->isStr("Class"))
1913 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1914 // Install the built-in type for 'Class', ignoring the current definition.
1915 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1918 if (!TypeID->isStr("SEL"))
1920 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1921 // Install the built-in type for 'SEL', ignoring the current definition.
1922 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1925 // Fall through - the typedef name was not a builtin type.
1928 // Verify the old decl was also a type.
1929 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1931 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1932 << New->getDeclName();
1934 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1935 if (OldD->getLocation().isValid())
1936 Diag(OldD->getLocation(), diag::note_previous_definition);
1938 return New->setInvalidDecl();
1941 // If the old declaration is invalid, just give up here.
1942 if (Old->isInvalidDecl())
1943 return New->setInvalidDecl();
1945 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1946 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1947 auto *NewTag = New->getAnonDeclWithTypedefName();
1948 NamedDecl *Hidden = nullptr;
1949 if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1950 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1951 !hasVisibleDefinition(OldTag, &Hidden)) {
1952 // There is a definition of this tag, but it is not visible. Use it
1953 // instead of our tag.
1954 New->setTypeForDecl(OldTD->getTypeForDecl());
1955 if (OldTD->isModed())
1956 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1957 OldTD->getUnderlyingType());
1959 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1961 // Make the old tag definition visible.
1962 makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1964 // If this was an unscoped enumeration, yank all of its enumerators
1965 // out of the scope.
1966 if (isa<EnumDecl>(NewTag)) {
1967 Scope *EnumScope = getNonFieldDeclScope(S);
1968 for (auto *D : NewTag->decls()) {
1969 auto *ED = cast<EnumConstantDecl>(D);
1970 assert(EnumScope->isDeclScope(ED));
1971 EnumScope->RemoveDecl(ED);
1972 IdResolver.RemoveDecl(ED);
1973 ED->getLexicalDeclContext()->removeDecl(ED);
1979 // If the typedef types are not identical, reject them in all languages and
1980 // with any extensions enabled.
1981 if (isIncompatibleTypedef(Old, New))
1984 // The types match. Link up the redeclaration chain and merge attributes if
1985 // the old declaration was a typedef.
1986 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1987 New->setPreviousDecl(Typedef);
1988 mergeDeclAttributes(New, Old);
1991 if (getLangOpts().MicrosoftExt)
1994 if (getLangOpts().CPlusPlus) {
1995 // C++ [dcl.typedef]p2:
1996 // In a given non-class scope, a typedef specifier can be used to
1997 // redefine the name of any type declared in that scope to refer
1998 // to the type to which it already refers.
1999 if (!isa<CXXRecordDecl>(CurContext))
2002 // C++0x [dcl.typedef]p4:
2003 // In a given class scope, a typedef specifier can be used to redefine
2004 // any class-name declared in that scope that is not also a typedef-name
2005 // to refer to the type to which it already refers.
2007 // This wording came in via DR424, which was a correction to the
2008 // wording in DR56, which accidentally banned code like:
2011 // typedef struct A { } A;
2014 // in the C++03 standard. We implement the C++0x semantics, which
2015 // allow the above but disallow
2022 // since that was the intent of DR56.
2023 if (!isa<TypedefNameDecl>(Old))
2026 Diag(New->getLocation(), diag::err_redefinition)
2027 << New->getDeclName();
2028 Diag(Old->getLocation(), diag::note_previous_definition);
2029 return New->setInvalidDecl();
2032 // Modules always permit redefinition of typedefs, as does C11.
2033 if (getLangOpts().Modules || getLangOpts().C11)
2036 // If we have a redefinition of a typedef in C, emit a warning. This warning
2037 // is normally mapped to an error, but can be controlled with
2038 // -Wtypedef-redefinition. If either the original or the redefinition is
2039 // in a system header, don't emit this for compatibility with GCC.
2040 if (getDiagnostics().getSuppressSystemWarnings() &&
2041 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2042 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2045 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2046 << New->getDeclName();
2047 Diag(Old->getLocation(), diag::note_previous_definition);
2050 /// DeclhasAttr - returns true if decl Declaration already has the target
2052 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2053 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2054 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2055 for (const auto *i : D->attrs())
2056 if (i->getKind() == A->getKind()) {
2058 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2062 // FIXME: Don't hardcode this check
2063 if (OA && isa<OwnershipAttr>(i))
2064 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2071 static bool isAttributeTargetADefinition(Decl *D) {
2072 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2073 return VD->isThisDeclarationADefinition();
2074 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2075 return TD->isCompleteDefinition() || TD->isBeingDefined();
2079 /// Merge alignment attributes from \p Old to \p New, taking into account the
2080 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2082 /// \return \c true if any attributes were added to \p New.
2083 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2084 // Look for alignas attributes on Old, and pick out whichever attribute
2085 // specifies the strictest alignment requirement.
2086 AlignedAttr *OldAlignasAttr = nullptr;
2087 AlignedAttr *OldStrictestAlignAttr = nullptr;
2088 unsigned OldAlign = 0;
2089 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2090 // FIXME: We have no way of representing inherited dependent alignments
2092 // template<int A, int B> struct alignas(A) X;
2093 // template<int A, int B> struct alignas(B) X {};
2094 // For now, we just ignore any alignas attributes which are not on the
2095 // definition in such a case.
2096 if (I->isAlignmentDependent())
2102 unsigned Align = I->getAlignment(S.Context);
2103 if (Align > OldAlign) {
2105 OldStrictestAlignAttr = I;
2109 // Look for alignas attributes on New.
2110 AlignedAttr *NewAlignasAttr = nullptr;
2111 unsigned NewAlign = 0;
2112 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2113 if (I->isAlignmentDependent())
2119 unsigned Align = I->getAlignment(S.Context);
2120 if (Align > NewAlign)
2124 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2125 // Both declarations have 'alignas' attributes. We require them to match.
2126 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2127 // fall short. (If two declarations both have alignas, they must both match
2128 // every definition, and so must match each other if there is a definition.)
2130 // If either declaration only contains 'alignas(0)' specifiers, then it
2131 // specifies the natural alignment for the type.
2132 if (OldAlign == 0 || NewAlign == 0) {
2134 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2137 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2140 OldAlign = S.Context.getTypeAlign(Ty);
2142 NewAlign = S.Context.getTypeAlign(Ty);
2145 if (OldAlign != NewAlign) {
2146 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2147 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2148 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2149 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2153 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2154 // C++11 [dcl.align]p6:
2155 // if any declaration of an entity has an alignment-specifier,
2156 // every defining declaration of that entity shall specify an
2157 // equivalent alignment.
2159 // If the definition of an object does not have an alignment
2160 // specifier, any other declaration of that object shall also
2161 // have no alignment specifier.
2162 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2164 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2168 bool AnyAdded = false;
2170 // Ensure we have an attribute representing the strictest alignment.
2171 if (OldAlign > NewAlign) {
2172 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2173 Clone->setInherited(true);
2174 New->addAttr(Clone);
2178 // Ensure we have an alignas attribute if the old declaration had one.
2179 if (OldAlignasAttr && !NewAlignasAttr &&
2180 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2181 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2182 Clone->setInherited(true);
2183 New->addAttr(Clone);
2190 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2191 const InheritableAttr *Attr,
2192 Sema::AvailabilityMergeKind AMK) {
2193 InheritableAttr *NewAttr = nullptr;
2194 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2195 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2196 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2197 AA->getIntroduced(), AA->getDeprecated(),
2198 AA->getObsoleted(), AA->getUnavailable(),
2199 AA->getMessage(), AMK,
2200 AttrSpellingListIndex);
2201 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2202 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2203 AttrSpellingListIndex);
2204 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2205 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2206 AttrSpellingListIndex);
2207 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2208 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2209 AttrSpellingListIndex);
2210 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2211 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2212 AttrSpellingListIndex);
2213 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2214 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2215 FA->getFormatIdx(), FA->getFirstArg(),
2216 AttrSpellingListIndex);
2217 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2218 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2219 AttrSpellingListIndex);
2220 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2221 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2222 AttrSpellingListIndex,
2223 IA->getSemanticSpelling());
2224 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2225 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2226 &S.Context.Idents.get(AA->getSpelling()),
2227 AttrSpellingListIndex);
2228 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2229 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2230 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2231 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2232 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2233 NewAttr = S.mergeInternalLinkageAttr(
2234 D, InternalLinkageA->getRange(),
2235 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2236 AttrSpellingListIndex);
2237 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2238 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2239 &S.Context.Idents.get(CommonA->getSpelling()),
2240 AttrSpellingListIndex);
2241 else if (isa<AlignedAttr>(Attr))
2242 // AlignedAttrs are handled separately, because we need to handle all
2243 // such attributes on a declaration at the same time.
2245 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2246 (AMK == Sema::AMK_Override ||
2247 AMK == Sema::AMK_ProtocolImplementation))
2249 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2250 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2253 NewAttr->setInherited(true);
2254 D->addAttr(NewAttr);
2261 static const Decl *getDefinition(const Decl *D) {
2262 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2263 return TD->getDefinition();
2264 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2265 const VarDecl *Def = VD->getDefinition();
2268 return VD->getActingDefinition();
2270 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2271 const FunctionDecl* Def;
2272 if (FD->isDefined(Def))
2278 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2279 for (const auto *Attribute : D->attrs())
2280 if (Attribute->getKind() == Kind)
2285 /// checkNewAttributesAfterDef - If we already have a definition, check that
2286 /// there are no new attributes in this declaration.
2287 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2288 if (!New->hasAttrs())
2291 const Decl *Def = getDefinition(Old);
2292 if (!Def || Def == New)
2295 AttrVec &NewAttributes = New->getAttrs();
2296 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2297 const Attr *NewAttribute = NewAttributes[I];
2299 if (isa<AliasAttr>(NewAttribute)) {
2300 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2301 Sema::SkipBodyInfo SkipBody;
2302 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2304 // If we're skipping this definition, drop the "alias" attribute.
2305 if (SkipBody.ShouldSkip) {
2306 NewAttributes.erase(NewAttributes.begin() + I);
2311 VarDecl *VD = cast<VarDecl>(New);
2312 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2313 VarDecl::TentativeDefinition
2314 ? diag::err_alias_after_tentative
2315 : diag::err_redefinition;
2316 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2317 S.Diag(Def->getLocation(), diag::note_previous_definition);
2318 VD->setInvalidDecl();
2324 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2325 // Tentative definitions are only interesting for the alias check above.
2326 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2332 if (hasAttribute(Def, NewAttribute->getKind())) {
2334 continue; // regular attr merging will take care of validating this.
2337 if (isa<C11NoReturnAttr>(NewAttribute)) {
2338 // C's _Noreturn is allowed to be added to a function after it is defined.
2341 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2342 if (AA->isAlignas()) {
2343 // C++11 [dcl.align]p6:
2344 // if any declaration of an entity has an alignment-specifier,
2345 // every defining declaration of that entity shall specify an
2346 // equivalent alignment.
2348 // If the definition of an object does not have an alignment
2349 // specifier, any other declaration of that object shall also
2350 // have no alignment specifier.
2351 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2353 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2355 NewAttributes.erase(NewAttributes.begin() + I);
2361 S.Diag(NewAttribute->getLocation(),
2362 diag::warn_attribute_precede_definition);
2363 S.Diag(Def->getLocation(), diag::note_previous_definition);
2364 NewAttributes.erase(NewAttributes.begin() + I);
2369 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2370 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2371 AvailabilityMergeKind AMK) {
2372 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2373 UsedAttr *NewAttr = OldAttr->clone(Context);
2374 NewAttr->setInherited(true);
2375 New->addAttr(NewAttr);
2378 if (!Old->hasAttrs() && !New->hasAttrs())
2381 // Attributes declared post-definition are currently ignored.
2382 checkNewAttributesAfterDef(*this, New, Old);
2384 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2385 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2386 if (OldA->getLabel() != NewA->getLabel()) {
2387 // This redeclaration changes __asm__ label.
2388 Diag(New->getLocation(), diag::err_different_asm_label);
2389 Diag(OldA->getLocation(), diag::note_previous_declaration);
2391 } else if (Old->isUsed()) {
2392 // This redeclaration adds an __asm__ label to a declaration that has
2393 // already been ODR-used.
2394 Diag(New->getLocation(), diag::err_late_asm_label_name)
2395 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2399 if (!Old->hasAttrs())
2402 bool foundAny = New->hasAttrs();
2404 // Ensure that any moving of objects within the allocated map is done before
2406 if (!foundAny) New->setAttrs(AttrVec());
2408 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2409 // Ignore deprecated/unavailable/availability attributes if requested.
2410 AvailabilityMergeKind LocalAMK = AMK_None;
2411 if (isa<DeprecatedAttr>(I) ||
2412 isa<UnavailableAttr>(I) ||
2413 isa<AvailabilityAttr>(I)) {
2418 case AMK_Redeclaration:
2420 case AMK_ProtocolImplementation:
2427 if (isa<UsedAttr>(I))
2430 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2434 if (mergeAlignedAttrs(*this, New, Old))
2437 if (!foundAny) New->dropAttrs();
2440 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2442 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2443 const ParmVarDecl *oldDecl,
2445 // C++11 [dcl.attr.depend]p2:
2446 // The first declaration of a function shall specify the
2447 // carries_dependency attribute for its declarator-id if any declaration
2448 // of the function specifies the carries_dependency attribute.
2449 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2450 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2451 S.Diag(CDA->getLocation(),
2452 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2453 // Find the first declaration of the parameter.
2454 // FIXME: Should we build redeclaration chains for function parameters?
2455 const FunctionDecl *FirstFD =
2456 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2457 const ParmVarDecl *FirstVD =
2458 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2459 S.Diag(FirstVD->getLocation(),
2460 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2463 if (!oldDecl->hasAttrs())
2466 bool foundAny = newDecl->hasAttrs();
2468 // Ensure that any moving of objects within the allocated map is
2469 // done before we process them.
2470 if (!foundAny) newDecl->setAttrs(AttrVec());
2472 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2473 if (!DeclHasAttr(newDecl, I)) {
2474 InheritableAttr *newAttr =
2475 cast<InheritableParamAttr>(I->clone(S.Context));
2476 newAttr->setInherited(true);
2477 newDecl->addAttr(newAttr);
2482 if (!foundAny) newDecl->dropAttrs();
2485 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2486 const ParmVarDecl *OldParam,
2488 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2489 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2490 if (*Oldnullability != *Newnullability) {
2491 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2492 << DiagNullabilityKind(
2494 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2496 << DiagNullabilityKind(
2498 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2500 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2503 QualType NewT = NewParam->getType();
2504 NewT = S.Context.getAttributedType(
2505 AttributedType::getNullabilityAttrKind(*Oldnullability),
2507 NewParam->setType(NewT);
2514 /// Used in MergeFunctionDecl to keep track of function parameters in
2516 struct GNUCompatibleParamWarning {
2517 ParmVarDecl *OldParm;
2518 ParmVarDecl *NewParm;
2519 QualType PromotedType;
2524 /// getSpecialMember - get the special member enum for a method.
2525 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2526 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2527 if (Ctor->isDefaultConstructor())
2528 return Sema::CXXDefaultConstructor;
2530 if (Ctor->isCopyConstructor())
2531 return Sema::CXXCopyConstructor;
2533 if (Ctor->isMoveConstructor())
2534 return Sema::CXXMoveConstructor;
2535 } else if (isa<CXXDestructorDecl>(MD)) {
2536 return Sema::CXXDestructor;
2537 } else if (MD->isCopyAssignmentOperator()) {
2538 return Sema::CXXCopyAssignment;
2539 } else if (MD->isMoveAssignmentOperator()) {
2540 return Sema::CXXMoveAssignment;
2543 return Sema::CXXInvalid;
2546 // Determine whether the previous declaration was a definition, implicit
2547 // declaration, or a declaration.
2548 template <typename T>
2549 static std::pair<diag::kind, SourceLocation>
2550 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2551 diag::kind PrevDiag;
2552 SourceLocation OldLocation = Old->getLocation();
2553 if (Old->isThisDeclarationADefinition())
2554 PrevDiag = diag::note_previous_definition;
2555 else if (Old->isImplicit()) {
2556 PrevDiag = diag::note_previous_implicit_declaration;
2557 if (OldLocation.isInvalid())
2558 OldLocation = New->getLocation();
2560 PrevDiag = diag::note_previous_declaration;
2561 return std::make_pair(PrevDiag, OldLocation);
2564 /// canRedefineFunction - checks if a function can be redefined. Currently,
2565 /// only extern inline functions can be redefined, and even then only in
2567 static bool canRedefineFunction(const FunctionDecl *FD,
2568 const LangOptions& LangOpts) {
2569 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2570 !LangOpts.CPlusPlus &&
2571 FD->isInlineSpecified() &&
2572 FD->getStorageClass() == SC_Extern);
2575 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2576 const AttributedType *AT = T->getAs<AttributedType>();
2577 while (AT && !AT->isCallingConv())
2578 AT = AT->getModifiedType()->getAs<AttributedType>();
2582 template <typename T>
2583 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2584 const DeclContext *DC = Old->getDeclContext();
2588 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2589 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2591 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2596 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2597 static bool isExternC(VarTemplateDecl *) { return false; }
2599 /// \brief Check whether a redeclaration of an entity introduced by a
2600 /// using-declaration is valid, given that we know it's not an overload
2601 /// (nor a hidden tag declaration).
2602 template<typename ExpectedDecl>
2603 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2604 ExpectedDecl *New) {
2605 // C++11 [basic.scope.declarative]p4:
2606 // Given a set of declarations in a single declarative region, each of
2607 // which specifies the same unqualified name,
2608 // -- they shall all refer to the same entity, or all refer to functions
2609 // and function templates; or
2610 // -- exactly one declaration shall declare a class name or enumeration
2611 // name that is not a typedef name and the other declarations shall all
2612 // refer to the same variable or enumerator, or all refer to functions
2613 // and function templates; in this case the class name or enumeration
2614 // name is hidden (3.3.10).
2616 // C++11 [namespace.udecl]p14:
2617 // If a function declaration in namespace scope or block scope has the
2618 // same name and the same parameter-type-list as a function introduced
2619 // by a using-declaration, and the declarations do not declare the same
2620 // function, the program is ill-formed.
2622 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2624 !Old->getDeclContext()->getRedeclContext()->Equals(
2625 New->getDeclContext()->getRedeclContext()) &&
2626 !(isExternC(Old) && isExternC(New)))
2630 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2631 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2632 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2638 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2639 const FunctionDecl *B) {
2640 assert(A->getNumParams() == B->getNumParams());
2642 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2643 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2644 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2647 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2650 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2653 /// MergeFunctionDecl - We just parsed a function 'New' from
2654 /// declarator D which has the same name and scope as a previous
2655 /// declaration 'Old'. Figure out how to resolve this situation,
2656 /// merging decls or emitting diagnostics as appropriate.
2658 /// In C++, New and Old must be declarations that are not
2659 /// overloaded. Use IsOverload to determine whether New and Old are
2660 /// overloaded, and to select the Old declaration that New should be
2663 /// Returns true if there was an error, false otherwise.
2664 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2665 Scope *S, bool MergeTypeWithOld) {
2666 // Verify the old decl was also a function.
2667 FunctionDecl *Old = OldD->getAsFunction();
2669 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2670 if (New->getFriendObjectKind()) {
2671 Diag(New->getLocation(), diag::err_using_decl_friend);
2672 Diag(Shadow->getTargetDecl()->getLocation(),
2673 diag::note_using_decl_target);
2674 Diag(Shadow->getUsingDecl()->getLocation(),
2675 diag::note_using_decl) << 0;
2679 // Check whether the two declarations might declare the same function.
2680 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2682 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2684 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2685 << New->getDeclName();
2686 Diag(OldD->getLocation(), diag::note_previous_definition);
2691 // If the old declaration is invalid, just give up here.
2692 if (Old->isInvalidDecl())
2695 diag::kind PrevDiag;
2696 SourceLocation OldLocation;
2697 std::tie(PrevDiag, OldLocation) =
2698 getNoteDiagForInvalidRedeclaration(Old, New);
2700 // Don't complain about this if we're in GNU89 mode and the old function
2701 // is an extern inline function.
2702 // Don't complain about specializations. They are not supposed to have
2704 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2705 New->getStorageClass() == SC_Static &&
2706 Old->hasExternalFormalLinkage() &&
2707 !New->getTemplateSpecializationInfo() &&
2708 !canRedefineFunction(Old, getLangOpts())) {
2709 if (getLangOpts().MicrosoftExt) {
2710 Diag(New->getLocation(), diag::ext_static_non_static) << New;
2711 Diag(OldLocation, PrevDiag);
2713 Diag(New->getLocation(), diag::err_static_non_static) << New;
2714 Diag(OldLocation, PrevDiag);
2719 if (New->hasAttr<InternalLinkageAttr>() &&
2720 !Old->hasAttr<InternalLinkageAttr>()) {
2721 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2722 << New->getDeclName();
2723 Diag(Old->getLocation(), diag::note_previous_definition);
2724 New->dropAttr<InternalLinkageAttr>();
2727 // If a function is first declared with a calling convention, but is later
2728 // declared or defined without one, all following decls assume the calling
2729 // convention of the first.
2731 // It's OK if a function is first declared without a calling convention,
2732 // but is later declared or defined with the default calling convention.
2734 // To test if either decl has an explicit calling convention, we look for
2735 // AttributedType sugar nodes on the type as written. If they are missing or
2736 // were canonicalized away, we assume the calling convention was implicit.
2738 // Note also that we DO NOT return at this point, because we still have
2739 // other tests to run.
2740 QualType OldQType = Context.getCanonicalType(Old->getType());
2741 QualType NewQType = Context.getCanonicalType(New->getType());
2742 const FunctionType *OldType = cast<FunctionType>(OldQType);
2743 const FunctionType *NewType = cast<FunctionType>(NewQType);
2744 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2745 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2746 bool RequiresAdjustment = false;
2748 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2749 FunctionDecl *First = Old->getFirstDecl();
2750 const FunctionType *FT =
2751 First->getType().getCanonicalType()->castAs<FunctionType>();
2752 FunctionType::ExtInfo FI = FT->getExtInfo();
2753 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2754 if (!NewCCExplicit) {
2755 // Inherit the CC from the previous declaration if it was specified
2756 // there but not here.
2757 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2758 RequiresAdjustment = true;
2760 // Calling conventions aren't compatible, so complain.
2761 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2762 Diag(New->getLocation(), diag::err_cconv_change)
2763 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2765 << (!FirstCCExplicit ? "" :
2766 FunctionType::getNameForCallConv(FI.getCC()));
2768 // Put the note on the first decl, since it is the one that matters.
2769 Diag(First->getLocation(), diag::note_previous_declaration);
2774 // FIXME: diagnose the other way around?
2775 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2776 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2777 RequiresAdjustment = true;
2780 // Merge regparm attribute.
2781 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2782 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2783 if (NewTypeInfo.getHasRegParm()) {
2784 Diag(New->getLocation(), diag::err_regparm_mismatch)
2785 << NewType->getRegParmType()
2786 << OldType->getRegParmType();
2787 Diag(OldLocation, diag::note_previous_declaration);
2791 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2792 RequiresAdjustment = true;
2795 // Merge ns_returns_retained attribute.
2796 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2797 if (NewTypeInfo.getProducesResult()) {
2798 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2799 Diag(OldLocation, diag::note_previous_declaration);
2803 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2804 RequiresAdjustment = true;
2807 if (RequiresAdjustment) {
2808 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2809 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2810 New->setType(QualType(AdjustedType, 0));
2811 NewQType = Context.getCanonicalType(New->getType());
2812 NewType = cast<FunctionType>(NewQType);
2815 // If this redeclaration makes the function inline, we may need to add it to
2816 // UndefinedButUsed.
2817 if (!Old->isInlined() && New->isInlined() &&
2818 !New->hasAttr<GNUInlineAttr>() &&
2819 !getLangOpts().GNUInline &&
2820 Old->isUsed(false) &&
2821 !Old->isDefined() && !New->isThisDeclarationADefinition())
2822 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2825 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2827 if (New->hasAttr<GNUInlineAttr>() &&
2828 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2829 UndefinedButUsed.erase(Old->getCanonicalDecl());
2832 // If pass_object_size params don't match up perfectly, this isn't a valid
2834 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2835 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2836 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2837 << New->getDeclName();
2838 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2842 if (getLangOpts().CPlusPlus) {
2844 // Certain function declarations cannot be overloaded:
2845 // -- Function declarations that differ only in the return type
2846 // cannot be overloaded.
2848 // Go back to the type source info to compare the declared return types,
2849 // per C++1y [dcl.type.auto]p13:
2850 // Redeclarations or specializations of a function or function template
2851 // with a declared return type that uses a placeholder type shall also
2852 // use that placeholder, not a deduced type.
2853 QualType OldDeclaredReturnType =
2854 (Old->getTypeSourceInfo()
2855 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2856 : OldType)->getReturnType();
2857 QualType NewDeclaredReturnType =
2858 (New->getTypeSourceInfo()
2859 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2860 : NewType)->getReturnType();
2862 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2863 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2864 New->isLocalExternDecl())) {
2865 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2866 OldDeclaredReturnType->isObjCObjectPointerType())
2867 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2868 if (ResQT.isNull()) {
2869 if (New->isCXXClassMember() && New->isOutOfLine())
2870 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2871 << New << New->getReturnTypeSourceRange();
2873 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2874 << New->getReturnTypeSourceRange();
2875 Diag(OldLocation, PrevDiag) << Old << Old->getType()
2876 << Old->getReturnTypeSourceRange();
2883 QualType OldReturnType = OldType->getReturnType();
2884 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2885 if (OldReturnType != NewReturnType) {
2886 // If this function has a deduced return type and has already been
2887 // defined, copy the deduced value from the old declaration.
2888 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2889 if (OldAT && OldAT->isDeduced()) {
2891 SubstAutoType(New->getType(),
2892 OldAT->isDependentType() ? Context.DependentTy
2893 : OldAT->getDeducedType()));
2894 NewQType = Context.getCanonicalType(
2895 SubstAutoType(NewQType,
2896 OldAT->isDependentType() ? Context.DependentTy
2897 : OldAT->getDeducedType()));
2901 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2902 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2903 if (OldMethod && NewMethod) {
2904 // Preserve triviality.
2905 NewMethod->setTrivial(OldMethod->isTrivial());
2907 // MSVC allows explicit template specialization at class scope:
2908 // 2 CXXMethodDecls referring to the same function will be injected.
2909 // We don't want a redeclaration error.
2910 bool IsClassScopeExplicitSpecialization =
2911 OldMethod->isFunctionTemplateSpecialization() &&
2912 NewMethod->isFunctionTemplateSpecialization();
2913 bool isFriend = NewMethod->getFriendObjectKind();
2915 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2916 !IsClassScopeExplicitSpecialization) {
2917 // -- Member function declarations with the same name and the
2918 // same parameter types cannot be overloaded if any of them
2919 // is a static member function declaration.
2920 if (OldMethod->isStatic() != NewMethod->isStatic()) {
2921 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2922 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2926 // C++ [class.mem]p1:
2927 // [...] A member shall not be declared twice in the
2928 // member-specification, except that a nested class or member
2929 // class template can be declared and then later defined.
2930 if (ActiveTemplateInstantiations.empty()) {
2932 if (isa<CXXConstructorDecl>(OldMethod))
2933 NewDiag = diag::err_constructor_redeclared;
2934 else if (isa<CXXDestructorDecl>(NewMethod))
2935 NewDiag = diag::err_destructor_redeclared;
2936 else if (isa<CXXConversionDecl>(NewMethod))
2937 NewDiag = diag::err_conv_function_redeclared;
2939 NewDiag = diag::err_member_redeclared;
2941 Diag(New->getLocation(), NewDiag);
2943 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2944 << New << New->getType();
2946 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2949 // Complain if this is an explicit declaration of a special
2950 // member that was initially declared implicitly.
2952 // As an exception, it's okay to befriend such methods in order
2953 // to permit the implicit constructor/destructor/operator calls.
2954 } else if (OldMethod->isImplicit()) {
2956 NewMethod->setImplicit();
2958 Diag(NewMethod->getLocation(),
2959 diag::err_definition_of_implicitly_declared_member)
2960 << New << getSpecialMember(OldMethod);
2963 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2964 Diag(NewMethod->getLocation(),
2965 diag::err_definition_of_explicitly_defaulted_member)
2966 << getSpecialMember(OldMethod);
2971 // C++11 [dcl.attr.noreturn]p1:
2972 // The first declaration of a function shall specify the noreturn
2973 // attribute if any declaration of that function specifies the noreturn
2975 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2976 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2977 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2978 Diag(Old->getFirstDecl()->getLocation(),
2979 diag::note_noreturn_missing_first_decl);
2982 // C++11 [dcl.attr.depend]p2:
2983 // The first declaration of a function shall specify the
2984 // carries_dependency attribute for its declarator-id if any declaration
2985 // of the function specifies the carries_dependency attribute.
2986 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2987 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2988 Diag(CDA->getLocation(),
2989 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2990 Diag(Old->getFirstDecl()->getLocation(),
2991 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2995 // All declarations for a function shall agree exactly in both the
2996 // return type and the parameter-type-list.
2997 // We also want to respect all the extended bits except noreturn.
2999 // noreturn should now match unless the old type info didn't have it.
3000 QualType OldQTypeForComparison = OldQType;
3001 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3002 assert(OldQType == QualType(OldType, 0));
3003 const FunctionType *OldTypeForComparison
3004 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3005 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3006 assert(OldQTypeForComparison.isCanonical());
3009 if (haveIncompatibleLanguageLinkages(Old, New)) {
3010 // As a special case, retain the language linkage from previous
3011 // declarations of a friend function as an extension.
3013 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3014 // and is useful because there's otherwise no way to specify language
3015 // linkage within class scope.
3017 // Check cautiously as the friend object kind isn't yet complete.
3018 if (New->getFriendObjectKind() != Decl::FOK_None) {
3019 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3020 Diag(OldLocation, PrevDiag);
3022 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3023 Diag(OldLocation, PrevDiag);
3028 if (OldQTypeForComparison == NewQType)
3029 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3031 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3032 New->isLocalExternDecl()) {
3033 // It's OK if we couldn't merge types for a local function declaraton
3034 // if either the old or new type is dependent. We'll merge the types
3035 // when we instantiate the function.
3039 // Fall through for conflicting redeclarations and redefinitions.
3042 // C: Function types need to be compatible, not identical. This handles
3043 // duplicate function decls like "void f(int); void f(enum X);" properly.
3044 if (!getLangOpts().CPlusPlus &&
3045 Context.typesAreCompatible(OldQType, NewQType)) {
3046 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3047 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3048 const FunctionProtoType *OldProto = nullptr;
3049 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3050 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3051 // The old declaration provided a function prototype, but the
3052 // new declaration does not. Merge in the prototype.
3053 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3054 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3056 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3057 OldProto->getExtProtoInfo());
3058 New->setType(NewQType);
3059 New->setHasInheritedPrototype();
3061 // Synthesize parameters with the same types.
3062 SmallVector<ParmVarDecl*, 16> Params;
3063 for (const auto &ParamType : OldProto->param_types()) {
3064 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3065 SourceLocation(), nullptr,
3066 ParamType, /*TInfo=*/nullptr,
3068 Param->setScopeInfo(0, Params.size());
3069 Param->setImplicit();
3070 Params.push_back(Param);
3073 New->setParams(Params);
3076 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3079 // GNU C permits a K&R definition to follow a prototype declaration
3080 // if the declared types of the parameters in the K&R definition
3081 // match the types in the prototype declaration, even when the
3082 // promoted types of the parameters from the K&R definition differ
3083 // from the types in the prototype. GCC then keeps the types from
3086 // If a variadic prototype is followed by a non-variadic K&R definition,
3087 // the K&R definition becomes variadic. This is sort of an edge case, but
3088 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3090 if (!getLangOpts().CPlusPlus &&
3091 Old->hasPrototype() && !New->hasPrototype() &&
3092 New->getType()->getAs<FunctionProtoType>() &&
3093 Old->getNumParams() == New->getNumParams()) {
3094 SmallVector<QualType, 16> ArgTypes;
3095 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3096 const FunctionProtoType *OldProto
3097 = Old->getType()->getAs<FunctionProtoType>();
3098 const FunctionProtoType *NewProto
3099 = New->getType()->getAs<FunctionProtoType>();
3101 // Determine whether this is the GNU C extension.
3102 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3103 NewProto->getReturnType());
3104 bool LooseCompatible = !MergedReturn.isNull();
3105 for (unsigned Idx = 0, End = Old->getNumParams();
3106 LooseCompatible && Idx != End; ++Idx) {
3107 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3108 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3109 if (Context.typesAreCompatible(OldParm->getType(),
3110 NewProto->getParamType(Idx))) {
3111 ArgTypes.push_back(NewParm->getType());
3112 } else if (Context.typesAreCompatible(OldParm->getType(),
3114 /*CompareUnqualified=*/true)) {
3115 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3116 NewProto->getParamType(Idx) };
3117 Warnings.push_back(Warn);
3118 ArgTypes.push_back(NewParm->getType());
3120 LooseCompatible = false;
3123 if (LooseCompatible) {
3124 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3125 Diag(Warnings[Warn].NewParm->getLocation(),
3126 diag::ext_param_promoted_not_compatible_with_prototype)
3127 << Warnings[Warn].PromotedType
3128 << Warnings[Warn].OldParm->getType();
3129 if (Warnings[Warn].OldParm->getLocation().isValid())
3130 Diag(Warnings[Warn].OldParm->getLocation(),
3131 diag::note_previous_declaration);
3134 if (MergeTypeWithOld)
3135 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3136 OldProto->getExtProtoInfo()));
3137 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3140 // Fall through to diagnose conflicting types.
3143 // A function that has already been declared has been redeclared or
3144 // defined with a different type; show an appropriate diagnostic.
3146 // If the previous declaration was an implicitly-generated builtin
3147 // declaration, then at the very least we should use a specialized note.
3149 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3150 // If it's actually a library-defined builtin function like 'malloc'
3151 // or 'printf', just warn about the incompatible redeclaration.
3152 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3153 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3154 Diag(OldLocation, diag::note_previous_builtin_declaration)
3155 << Old << Old->getType();
3157 // If this is a global redeclaration, just forget hereafter
3158 // about the "builtin-ness" of the function.
3160 // Doing this for local extern declarations is problematic. If
3161 // the builtin declaration remains visible, a second invalid
3162 // local declaration will produce a hard error; if it doesn't
3163 // remain visible, a single bogus local redeclaration (which is
3164 // actually only a warning) could break all the downstream code.
3165 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3166 New->getIdentifier()->revertBuiltin();
3171 PrevDiag = diag::note_previous_builtin_declaration;
3174 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3175 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3179 /// \brief Completes the merge of two function declarations that are
3180 /// known to be compatible.
3182 /// This routine handles the merging of attributes and other
3183 /// properties of function declarations from the old declaration to
3184 /// the new declaration, once we know that New is in fact a
3185 /// redeclaration of Old.
3188 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3189 Scope *S, bool MergeTypeWithOld) {
3190 // Merge the attributes
3191 mergeDeclAttributes(New, Old);
3193 // Merge "pure" flag.
3197 // Merge "used" flag.
3198 if (Old->getMostRecentDecl()->isUsed(false))
3201 // Merge attributes from the parameters. These can mismatch with K&R
3203 if (New->getNumParams() == Old->getNumParams())
3204 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3205 ParmVarDecl *NewParam = New->getParamDecl(i);
3206 ParmVarDecl *OldParam = Old->getParamDecl(i);
3207 mergeParamDeclAttributes(NewParam, OldParam, *this);
3208 mergeParamDeclTypes(NewParam, OldParam, *this);
3211 if (getLangOpts().CPlusPlus)
3212 return MergeCXXFunctionDecl(New, Old, S);
3214 // Merge the function types so the we get the composite types for the return
3215 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3217 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3218 if (!Merged.isNull() && MergeTypeWithOld)
3219 New->setType(Merged);
3225 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3226 ObjCMethodDecl *oldMethod) {
3228 // Merge the attributes, including deprecated/unavailable
3229 AvailabilityMergeKind MergeKind =
3230 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3231 ? AMK_ProtocolImplementation
3232 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3235 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3237 // Merge attributes from the parameters.
3238 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3239 oe = oldMethod->param_end();
3240 for (ObjCMethodDecl::param_iterator
3241 ni = newMethod->param_begin(), ne = newMethod->param_end();
3242 ni != ne && oi != oe; ++ni, ++oi)
3243 mergeParamDeclAttributes(*ni, *oi, *this);
3245 CheckObjCMethodOverride(newMethod, oldMethod);
3248 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3249 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3250 /// emitting diagnostics as appropriate.
3252 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3253 /// to here in AddInitializerToDecl. We can't check them before the initializer
3255 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3256 bool MergeTypeWithOld) {
3257 if (New->isInvalidDecl() || Old->isInvalidDecl())
3261 if (getLangOpts().CPlusPlus) {
3262 if (New->getType()->isUndeducedType()) {
3263 // We don't know what the new type is until the initializer is attached.
3265 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3266 // These could still be something that needs exception specs checked.
3267 return MergeVarDeclExceptionSpecs(New, Old);
3269 // C++ [basic.link]p10:
3270 // [...] the types specified by all declarations referring to a given
3271 // object or function shall be identical, except that declarations for an
3272 // array object can specify array types that differ by the presence or
3273 // absence of a major array bound (8.3.4).
3274 else if (Old->getType()->isIncompleteArrayType() &&
3275 New->getType()->isArrayType()) {
3276 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3277 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3278 if (Context.hasSameType(OldArray->getElementType(),
3279 NewArray->getElementType()))
3280 MergedT = New->getType();
3281 } else if (Old->getType()->isArrayType() &&
3282 New->getType()->isIncompleteArrayType()) {
3283 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3284 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3285 if (Context.hasSameType(OldArray->getElementType(),
3286 NewArray->getElementType()))
3287 MergedT = Old->getType();
3288 } else if (New->getType()->isObjCObjectPointerType() &&
3289 Old->getType()->isObjCObjectPointerType()) {
3290 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3295 // All declarations that refer to the same object or function shall have
3297 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3299 if (MergedT.isNull()) {
3300 // It's OK if we couldn't merge types if either type is dependent, for a
3301 // block-scope variable. In other cases (static data members of class
3302 // templates, variable templates, ...), we require the types to be
3304 // FIXME: The C++ standard doesn't say anything about this.
3305 if ((New->getType()->isDependentType() ||
3306 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3307 // If the old type was dependent, we can't merge with it, so the new type
3308 // becomes dependent for now. We'll reproduce the original type when we
3309 // instantiate the TypeSourceInfo for the variable.
3310 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3311 New->setType(Context.DependentTy);
3315 // FIXME: Even if this merging succeeds, some other non-visible declaration
3316 // of this variable might have an incompatible type. For instance:
3318 // extern int arr[];
3319 // void f() { extern int arr[2]; }
3320 // void g() { extern int arr[3]; }
3322 // Neither C nor C++ requires a diagnostic for this, but we should still try
3324 Diag(New->getLocation(), New->isThisDeclarationADefinition()
3325 ? diag::err_redefinition_different_type
3326 : diag::err_redeclaration_different_type)
3327 << New->getDeclName() << New->getType() << Old->getType();
3329 diag::kind PrevDiag;
3330 SourceLocation OldLocation;
3331 std::tie(PrevDiag, OldLocation) =
3332 getNoteDiagForInvalidRedeclaration(Old, New);
3333 Diag(OldLocation, PrevDiag);
3334 return New->setInvalidDecl();
3337 // Don't actually update the type on the new declaration if the old
3338 // declaration was an extern declaration in a different scope.
3339 if (MergeTypeWithOld)
3340 New->setType(MergedT);
3343 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3344 LookupResult &Previous) {
3346 // For an identifier with internal or external linkage declared
3347 // in a scope in which a prior declaration of that identifier is
3348 // visible, if the prior declaration specifies internal or
3349 // external linkage, the type of the identifier at the later
3350 // declaration becomes the composite type.
3352 // If the variable isn't visible, we do not merge with its type.
3353 if (Previous.isShadowed())
3356 if (S.getLangOpts().CPlusPlus) {
3357 // C++11 [dcl.array]p3:
3358 // If there is a preceding declaration of the entity in the same
3359 // scope in which the bound was specified, an omitted array bound
3360 // is taken to be the same as in that earlier declaration.
3361 return NewVD->isPreviousDeclInSameBlockScope() ||
3362 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3363 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3365 // If the old declaration was function-local, don't merge with its
3366 // type unless we're in the same function.
3367 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3368 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3372 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3373 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3374 /// situation, merging decls or emitting diagnostics as appropriate.
3376 /// Tentative definition rules (C99 6.9.2p2) are checked by
3377 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3378 /// definitions here, since the initializer hasn't been attached.
3380 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3381 // If the new decl is already invalid, don't do any other checking.
3382 if (New->isInvalidDecl())
3385 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3388 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3390 // Verify the old decl was also a variable or variable template.
3391 VarDecl *Old = nullptr;
3392 VarTemplateDecl *OldTemplate = nullptr;
3393 if (Previous.isSingleResult()) {
3395 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3396 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3399 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3400 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3401 return New->setInvalidDecl();
3403 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3406 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3407 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3408 return New->setInvalidDecl();
3412 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3413 << New->getDeclName();
3414 Diag(Previous.getRepresentativeDecl()->getLocation(),
3415 diag::note_previous_definition);
3416 return New->setInvalidDecl();
3419 // Ensure the template parameters are compatible.
3421 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3422 OldTemplate->getTemplateParameters(),
3423 /*Complain=*/true, TPL_TemplateMatch))
3424 return New->setInvalidDecl();
3426 // C++ [class.mem]p1:
3427 // A member shall not be declared twice in the member-specification [...]
3429 // Here, we need only consider static data members.
3430 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3431 Diag(New->getLocation(), diag::err_duplicate_member)
3432 << New->getIdentifier();
3433 Diag(Old->getLocation(), diag::note_previous_declaration);
3434 New->setInvalidDecl();
3437 mergeDeclAttributes(New, Old);
3438 // Warn if an already-declared variable is made a weak_import in a subsequent
3440 if (New->hasAttr<WeakImportAttr>() &&
3441 Old->getStorageClass() == SC_None &&
3442 !Old->hasAttr<WeakImportAttr>()) {
3443 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3444 Diag(Old->getLocation(), diag::note_previous_definition);
3445 // Remove weak_import attribute on new declaration.
3446 New->dropAttr<WeakImportAttr>();
3449 if (New->hasAttr<InternalLinkageAttr>() &&
3450 !Old->hasAttr<InternalLinkageAttr>()) {
3451 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3452 << New->getDeclName();
3453 Diag(Old->getLocation(), diag::note_previous_definition);
3454 New->dropAttr<InternalLinkageAttr>();
3458 VarDecl *MostRecent = Old->getMostRecentDecl();
3459 if (MostRecent != Old) {
3460 MergeVarDeclTypes(New, MostRecent,
3461 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3462 if (New->isInvalidDecl())
3466 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3467 if (New->isInvalidDecl())
3470 diag::kind PrevDiag;
3471 SourceLocation OldLocation;
3472 std::tie(PrevDiag, OldLocation) =
3473 getNoteDiagForInvalidRedeclaration(Old, New);
3475 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3476 if (New->getStorageClass() == SC_Static &&
3477 !New->isStaticDataMember() &&
3478 Old->hasExternalFormalLinkage()) {
3479 if (getLangOpts().MicrosoftExt) {
3480 Diag(New->getLocation(), diag::ext_static_non_static)
3481 << New->getDeclName();
3482 Diag(OldLocation, PrevDiag);
3484 Diag(New->getLocation(), diag::err_static_non_static)
3485 << New->getDeclName();
3486 Diag(OldLocation, PrevDiag);
3487 return New->setInvalidDecl();
3491 // For an identifier declared with the storage-class specifier
3492 // extern in a scope in which a prior declaration of that
3493 // identifier is visible,23) if the prior declaration specifies
3494 // internal or external linkage, the linkage of the identifier at
3495 // the later declaration is the same as the linkage specified at
3496 // the prior declaration. If no prior declaration is visible, or
3497 // if the prior declaration specifies no linkage, then the
3498 // identifier has external linkage.
3499 if (New->hasExternalStorage() && Old->hasLinkage())
3501 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3502 !New->isStaticDataMember() &&
3503 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3504 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3505 Diag(OldLocation, PrevDiag);
3506 return New->setInvalidDecl();
3509 // Check if extern is followed by non-extern and vice-versa.
3510 if (New->hasExternalStorage() &&
3511 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3512 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3513 Diag(OldLocation, PrevDiag);
3514 return New->setInvalidDecl();
3516 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3517 !New->hasExternalStorage()) {
3518 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3519 Diag(OldLocation, PrevDiag);
3520 return New->setInvalidDecl();
3523 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3525 // FIXME: The test for external storage here seems wrong? We still
3526 // need to check for mismatches.
3527 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3528 // Don't complain about out-of-line definitions of static members.
3529 !(Old->getLexicalDeclContext()->isRecord() &&
3530 !New->getLexicalDeclContext()->isRecord())) {
3531 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3532 Diag(OldLocation, PrevDiag);
3533 return New->setInvalidDecl();
3536 if (New->getTLSKind() != Old->getTLSKind()) {
3537 if (!Old->getTLSKind()) {
3538 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3539 Diag(OldLocation, PrevDiag);
3540 } else if (!New->getTLSKind()) {
3541 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3542 Diag(OldLocation, PrevDiag);
3544 // Do not allow redeclaration to change the variable between requiring
3545 // static and dynamic initialization.
3546 // FIXME: GCC allows this, but uses the TLS keyword on the first
3547 // declaration to determine the kind. Do we need to be compatible here?
3548 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3549 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3550 Diag(OldLocation, PrevDiag);
3554 // C++ doesn't have tentative definitions, so go right ahead and check here.
3556 if (getLangOpts().CPlusPlus &&
3557 New->isThisDeclarationADefinition() == VarDecl::Definition &&
3558 (Def = Old->getDefinition())) {
3559 NamedDecl *Hidden = nullptr;
3560 if (!hasVisibleDefinition(Def, &Hidden) &&
3561 (New->getFormalLinkage() == InternalLinkage ||
3562 New->getDescribedVarTemplate() ||
3563 New->getNumTemplateParameterLists() ||
3564 New->getDeclContext()->isDependentContext())) {
3565 // The previous definition is hidden, and multiple definitions are
3566 // permitted (in separate TUs). Form another definition of it.
3568 Diag(New->getLocation(), diag::err_redefinition) << New;
3569 Diag(Def->getLocation(), diag::note_previous_definition);
3570 New->setInvalidDecl();
3575 if (haveIncompatibleLanguageLinkages(Old, New)) {
3576 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3577 Diag(OldLocation, PrevDiag);
3578 New->setInvalidDecl();
3582 // Merge "used" flag.
3583 if (Old->getMostRecentDecl()->isUsed(false))
3586 // Keep a chain of previous declarations.
3587 New->setPreviousDecl(Old);
3589 NewTemplate->setPreviousDecl(OldTemplate);
3591 // Inherit access appropriately.
3592 New->setAccess(Old->getAccess());
3594 NewTemplate->setAccess(New->getAccess());
3597 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3598 /// no declarator (e.g. "struct foo;") is parsed.
3599 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3601 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3604 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3605 // disambiguate entities defined in different scopes.
3606 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3608 // We will pick our mangling number depending on which version of MSVC is being
3610 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3611 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3612 ? S->getMSCurManglingNumber()
3613 : S->getMSLastManglingNumber();
3616 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3617 if (!Context.getLangOpts().CPlusPlus)
3620 if (isa<CXXRecordDecl>(Tag->getParent())) {
3621 // If this tag is the direct child of a class, number it if
3623 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3625 MangleNumberingContext &MCtx =
3626 Context.getManglingNumberContext(Tag->getParent());
3627 Context.setManglingNumber(
3628 Tag, MCtx.getManglingNumber(
3629 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3633 // If this tag isn't a direct child of a class, number it if it is local.
3634 Decl *ManglingContextDecl;
3635 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3636 Tag->getDeclContext(), ManglingContextDecl)) {
3637 Context.setManglingNumber(
3638 Tag, MCtx->getManglingNumber(
3639 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3643 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3644 TypedefNameDecl *NewTD) {
3645 if (TagFromDeclSpec->isInvalidDecl())
3648 // Do nothing if the tag already has a name for linkage purposes.
3649 if (TagFromDeclSpec->hasNameForLinkage())
3652 // A well-formed anonymous tag must always be a TUK_Definition.
3653 assert(TagFromDeclSpec->isThisDeclarationADefinition());
3655 // The type must match the tag exactly; no qualifiers allowed.
3656 if (!Context.hasSameType(NewTD->getUnderlyingType(),
3657 Context.getTagDeclType(TagFromDeclSpec))) {
3658 if (getLangOpts().CPlusPlus)
3659 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3663 // If we've already computed linkage for the anonymous tag, then
3664 // adding a typedef name for the anonymous decl can change that
3665 // linkage, which might be a serious problem. Diagnose this as
3666 // unsupported and ignore the typedef name. TODO: we should
3667 // pursue this as a language defect and establish a formal rule
3668 // for how to handle it.
3669 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3670 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3672 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3673 tagLoc = getLocForEndOfToken(tagLoc);
3675 llvm::SmallString<40> textToInsert;
3676 textToInsert += ' ';
3677 textToInsert += NewTD->getIdentifier()->getName();
3678 Diag(tagLoc, diag::note_typedef_changes_linkage)
3679 << FixItHint::CreateInsertion(tagLoc, textToInsert);
3683 // Otherwise, set this is the anon-decl typedef for the tag.
3684 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3687 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3689 case DeclSpec::TST_class:
3691 case DeclSpec::TST_struct:
3693 case DeclSpec::TST_interface:
3695 case DeclSpec::TST_union:
3697 case DeclSpec::TST_enum:
3700 llvm_unreachable("unexpected type specifier");
3704 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3705 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3706 /// parameters to cope with template friend declarations.
3707 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3709 MultiTemplateParamsArg TemplateParams,
3710 bool IsExplicitInstantiation) {
3711 Decl *TagD = nullptr;
3712 TagDecl *Tag = nullptr;
3713 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3714 DS.getTypeSpecType() == DeclSpec::TST_struct ||
3715 DS.getTypeSpecType() == DeclSpec::TST_interface ||
3716 DS.getTypeSpecType() == DeclSpec::TST_union ||
3717 DS.getTypeSpecType() == DeclSpec::TST_enum) {
3718 TagD = DS.getRepAsDecl();
3720 if (!TagD) // We probably had an error
3723 // Note that the above type specs guarantee that the
3724 // type rep is a Decl, whereas in many of the others
3726 if (isa<TagDecl>(TagD))
3727 Tag = cast<TagDecl>(TagD);
3728 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3729 Tag = CTD->getTemplatedDecl();
3733 handleTagNumbering(Tag, S);
3734 Tag->setFreeStanding();
3735 if (Tag->isInvalidDecl())
3739 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3740 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3741 // or incomplete types shall not be restrict-qualified."
3742 if (TypeQuals & DeclSpec::TQ_restrict)
3743 Diag(DS.getRestrictSpecLoc(),
3744 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3745 << DS.getSourceRange();
3748 if (DS.isConstexprSpecified()) {
3749 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3750 // and definitions of functions and variables.
3752 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3753 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3755 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3756 // Don't emit warnings after this error.
3760 if (DS.isConceptSpecified()) {
3761 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3762 // either a function concept and its definition or a variable concept and
3764 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3768 DiagnoseFunctionSpecifiers(DS);
3770 if (DS.isFriendSpecified()) {
3771 // If we're dealing with a decl but not a TagDecl, assume that
3772 // whatever routines created it handled the friendship aspect.
3775 return ActOnFriendTypeDecl(S, DS, TemplateParams);
3778 const CXXScopeSpec &SS = DS.getTypeSpecScope();
3779 bool IsExplicitSpecialization =
3780 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3781 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3782 !IsExplicitInstantiation && !IsExplicitSpecialization &&
3783 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3784 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3785 // nested-name-specifier unless it is an explicit instantiation
3786 // or an explicit specialization.
3788 // FIXME: We allow class template partial specializations here too, per the
3789 // obvious intent of DR1819.
3791 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3792 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3793 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3797 // Track whether this decl-specifier declares anything.
3798 bool DeclaresAnything = true;
3800 // Handle anonymous struct definitions.
3801 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3802 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3803 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3804 if (getLangOpts().CPlusPlus ||
3805 Record->getDeclContext()->isRecord())
3806 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3807 Context.getPrintingPolicy());
3809 DeclaresAnything = false;
3814 // A struct-declaration that does not declare an anonymous structure or
3815 // anonymous union shall contain a struct-declarator-list.
3817 // This rule also existed in C89 and C99; the grammar for struct-declaration
3818 // did not permit a struct-declaration without a struct-declarator-list.
3819 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3820 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3821 // Check for Microsoft C extension: anonymous struct/union member.
3822 // Handle 2 kinds of anonymous struct/union:
3826 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3827 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
3828 if ((Tag && Tag->getDeclName()) ||
3829 DS.getTypeSpecType() == DeclSpec::TST_typename) {
3830 RecordDecl *Record = nullptr;
3832 Record = dyn_cast<RecordDecl>(Tag);
3833 else if (const RecordType *RT =
3834 DS.getRepAsType().get()->getAsStructureType())
3835 Record = RT->getDecl();
3836 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3837 Record = UT->getDecl();
3839 if (Record && getLangOpts().MicrosoftExt) {
3840 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3841 << Record->isUnion() << DS.getSourceRange();
3842 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3845 DeclaresAnything = false;
3849 // Skip all the checks below if we have a type error.
3850 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3851 (TagD && TagD->isInvalidDecl()))
3854 if (getLangOpts().CPlusPlus &&
3855 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3856 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3857 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3858 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3859 DeclaresAnything = false;
3861 if (!DS.isMissingDeclaratorOk()) {
3862 // Customize diagnostic for a typedef missing a name.
3863 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3864 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3865 << DS.getSourceRange();
3867 DeclaresAnything = false;
3870 if (DS.isModulePrivateSpecified() &&
3871 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3872 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3873 << Tag->getTagKind()
3874 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3876 ActOnDocumentableDecl(TagD);
3879 // A declaration [...] shall declare at least a declarator [...], a tag,
3880 // or the members of an enumeration.
3882 // [If there are no declarators], and except for the declaration of an
3883 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3884 // names into the program, or shall redeclare a name introduced by a
3885 // previous declaration.
3886 if (!DeclaresAnything) {
3887 // In C, we allow this as a (popular) extension / bug. Don't bother
3888 // producing further diagnostics for redundant qualifiers after this.
3889 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3894 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3895 // init-declarator-list of the declaration shall not be empty.
3896 // C++ [dcl.fct.spec]p1:
3897 // If a cv-qualifier appears in a decl-specifier-seq, the
3898 // init-declarator-list of the declaration shall not be empty.
3900 // Spurious qualifiers here appear to be valid in C.
3901 unsigned DiagID = diag::warn_standalone_specifier;
3902 if (getLangOpts().CPlusPlus)
3903 DiagID = diag::ext_standalone_specifier;
3905 // Note that a linkage-specification sets a storage class, but
3906 // 'extern "C" struct foo;' is actually valid and not theoretically
3908 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3909 if (SCS == DeclSpec::SCS_mutable)
3910 // Since mutable is not a viable storage class specifier in C, there is
3911 // no reason to treat it as an extension. Instead, diagnose as an error.
3912 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3913 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3914 Diag(DS.getStorageClassSpecLoc(), DiagID)
3915 << DeclSpec::getSpecifierName(SCS);
3918 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3919 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3920 << DeclSpec::getSpecifierName(TSCS);
3921 if (DS.getTypeQualifiers()) {
3922 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3923 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3924 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3925 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3926 // Restrict is covered above.
3927 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3928 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3931 // Warn about ignored type attributes, for example:
3932 // __attribute__((aligned)) struct A;
3933 // Attributes should be placed after tag to apply to type declaration.
3934 if (!DS.getAttributes().empty()) {
3935 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3936 if (TypeSpecType == DeclSpec::TST_class ||
3937 TypeSpecType == DeclSpec::TST_struct ||
3938 TypeSpecType == DeclSpec::TST_interface ||
3939 TypeSpecType == DeclSpec::TST_union ||
3940 TypeSpecType == DeclSpec::TST_enum) {
3941 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3942 attrs = attrs->getNext())
3943 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3944 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3951 /// We are trying to inject an anonymous member into the given scope;
3952 /// check if there's an existing declaration that can't be overloaded.
3954 /// \return true if this is a forbidden redeclaration
3955 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3958 DeclarationName Name,
3959 SourceLocation NameLoc,
3961 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3962 Sema::ForRedeclaration);
3963 if (!SemaRef.LookupName(R, S)) return false;
3965 // Pick a representative declaration.
3966 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3967 assert(PrevDecl && "Expected a non-null Decl");
3969 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3972 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
3974 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3979 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3980 /// anonymous struct or union AnonRecord into the owning context Owner
3981 /// and scope S. This routine will be invoked just after we realize
3982 /// that an unnamed union or struct is actually an anonymous union or
3989 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3990 /// // f into the surrounding scope.x
3993 /// This routine is recursive, injecting the names of nested anonymous
3994 /// structs/unions into the owning context and scope as well.
3995 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3997 RecordDecl *AnonRecord,
3999 SmallVectorImpl<NamedDecl *> &Chaining,
4000 bool MSAnonStruct) {
4001 bool Invalid = false;
4003 // Look every FieldDecl and IndirectFieldDecl with a name.
4004 for (auto *D : AnonRecord->decls()) {
4005 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4006 cast<NamedDecl>(D)->getDeclName()) {
4007 ValueDecl *VD = cast<ValueDecl>(D);
4008 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4010 AnonRecord->isUnion())) {
4011 // C++ [class.union]p2:
4012 // The names of the members of an anonymous union shall be
4013 // distinct from the names of any other entity in the
4014 // scope in which the anonymous union is declared.
4017 // C++ [class.union]p2:
4018 // For the purpose of name lookup, after the anonymous union
4019 // definition, the members of the anonymous union are
4020 // considered to have been defined in the scope in which the
4021 // anonymous union is declared.
4022 unsigned OldChainingSize = Chaining.size();
4023 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4024 Chaining.append(IF->chain_begin(), IF->chain_end());
4026 Chaining.push_back(VD);
4028 assert(Chaining.size() >= 2);
4029 NamedDecl **NamedChain =
4030 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4031 for (unsigned i = 0; i < Chaining.size(); i++)
4032 NamedChain[i] = Chaining[i];
4034 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4035 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4036 VD->getType(), NamedChain, Chaining.size());
4038 for (const auto *Attr : VD->attrs())
4039 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4041 IndirectField->setAccess(AS);
4042 IndirectField->setImplicit();
4043 SemaRef.PushOnScopeChains(IndirectField, S);
4045 // That includes picking up the appropriate access specifier.
4046 if (AS != AS_none) IndirectField->setAccess(AS);
4048 Chaining.resize(OldChainingSize);
4056 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4057 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4058 /// illegal input values are mapped to SC_None.
4060 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4061 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4062 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4063 "Parser allowed 'typedef' as storage class VarDecl.");
4064 switch (StorageClassSpec) {
4065 case DeclSpec::SCS_unspecified: return SC_None;
4066 case DeclSpec::SCS_extern:
4067 if (DS.isExternInLinkageSpec())
4070 case DeclSpec::SCS_static: return SC_Static;
4071 case DeclSpec::SCS_auto: return SC_Auto;
4072 case DeclSpec::SCS_register: return SC_Register;
4073 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4074 // Illegal SCSs map to None: error reporting is up to the caller.
4075 case DeclSpec::SCS_mutable: // Fall through.
4076 case DeclSpec::SCS_typedef: return SC_None;
4078 llvm_unreachable("unknown storage class specifier");
4081 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4082 assert(Record->hasInClassInitializer());
4084 for (const auto *I : Record->decls()) {
4085 const auto *FD = dyn_cast<FieldDecl>(I);
4086 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4087 FD = IFD->getAnonField();
4088 if (FD && FD->hasInClassInitializer())
4089 return FD->getLocation();
4092 llvm_unreachable("couldn't find in-class initializer");
4095 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4096 SourceLocation DefaultInitLoc) {
4097 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4100 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4101 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4104 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4105 CXXRecordDecl *AnonUnion) {
4106 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4109 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4112 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4113 /// anonymous structure or union. Anonymous unions are a C++ feature
4114 /// (C++ [class.union]) and a C11 feature; anonymous structures
4115 /// are a C11 feature and GNU C++ extension.
4116 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4119 const PrintingPolicy &Policy) {
4120 DeclContext *Owner = Record->getDeclContext();
4122 // Diagnose whether this anonymous struct/union is an extension.
4123 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4124 Diag(Record->getLocation(), diag::ext_anonymous_union);
4125 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4126 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4127 else if (!Record->isUnion() && !getLangOpts().C11)
4128 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4130 // C and C++ require different kinds of checks for anonymous
4132 bool Invalid = false;
4133 if (getLangOpts().CPlusPlus) {
4134 const char *PrevSpec = nullptr;
4136 if (Record->isUnion()) {
4137 // C++ [class.union]p6:
4138 // Anonymous unions declared in a named namespace or in the
4139 // global namespace shall be declared static.
4140 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4141 (isa<TranslationUnitDecl>(Owner) ||
4142 (isa<NamespaceDecl>(Owner) &&
4143 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4144 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4145 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4147 // Recover by adding 'static'.
4148 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4149 PrevSpec, DiagID, Policy);
4151 // C++ [class.union]p6:
4152 // A storage class is not allowed in a declaration of an
4153 // anonymous union in a class scope.
4154 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4155 isa<RecordDecl>(Owner)) {
4156 Diag(DS.getStorageClassSpecLoc(),
4157 diag::err_anonymous_union_with_storage_spec)
4158 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4160 // Recover by removing the storage specifier.
4161 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4163 PrevSpec, DiagID, Context.getPrintingPolicy());
4167 // Ignore const/volatile/restrict qualifiers.
4168 if (DS.getTypeQualifiers()) {
4169 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4170 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4171 << Record->isUnion() << "const"
4172 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4173 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4174 Diag(DS.getVolatileSpecLoc(),
4175 diag::ext_anonymous_struct_union_qualified)
4176 << Record->isUnion() << "volatile"
4177 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4178 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4179 Diag(DS.getRestrictSpecLoc(),
4180 diag::ext_anonymous_struct_union_qualified)
4181 << Record->isUnion() << "restrict"
4182 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4183 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4184 Diag(DS.getAtomicSpecLoc(),
4185 diag::ext_anonymous_struct_union_qualified)
4186 << Record->isUnion() << "_Atomic"
4187 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4189 DS.ClearTypeQualifiers();
4192 // C++ [class.union]p2:
4193 // The member-specification of an anonymous union shall only
4194 // define non-static data members. [Note: nested types and
4195 // functions cannot be declared within an anonymous union. ]
4196 for (auto *Mem : Record->decls()) {
4197 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4198 // C++ [class.union]p3:
4199 // An anonymous union shall not have private or protected
4200 // members (clause 11).
4201 assert(FD->getAccess() != AS_none);
4202 if (FD->getAccess() != AS_public) {
4203 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4204 << Record->isUnion() << (FD->getAccess() == AS_protected);
4208 // C++ [class.union]p1
4209 // An object of a class with a non-trivial constructor, a non-trivial
4210 // copy constructor, a non-trivial destructor, or a non-trivial copy
4211 // assignment operator cannot be a member of a union, nor can an
4212 // array of such objects.
4213 if (CheckNontrivialField(FD))
4215 } else if (Mem->isImplicit()) {
4216 // Any implicit members are fine.
4217 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4218 // This is a type that showed up in an
4219 // elaborated-type-specifier inside the anonymous struct or
4220 // union, but which actually declares a type outside of the
4221 // anonymous struct or union. It's okay.
4222 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4223 if (!MemRecord->isAnonymousStructOrUnion() &&
4224 MemRecord->getDeclName()) {
4225 // Visual C++ allows type definition in anonymous struct or union.
4226 if (getLangOpts().MicrosoftExt)
4227 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4228 << Record->isUnion();
4230 // This is a nested type declaration.
4231 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4232 << Record->isUnion();
4236 // This is an anonymous type definition within another anonymous type.
4237 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4238 // not part of standard C++.
4239 Diag(MemRecord->getLocation(),
4240 diag::ext_anonymous_record_with_anonymous_type)
4241 << Record->isUnion();
4243 } else if (isa<AccessSpecDecl>(Mem)) {
4244 // Any access specifier is fine.
4245 } else if (isa<StaticAssertDecl>(Mem)) {
4246 // In C++1z, static_assert declarations are also fine.
4248 // We have something that isn't a non-static data
4249 // member. Complain about it.
4250 unsigned DK = diag::err_anonymous_record_bad_member;
4251 if (isa<TypeDecl>(Mem))
4252 DK = diag::err_anonymous_record_with_type;
4253 else if (isa<FunctionDecl>(Mem))
4254 DK = diag::err_anonymous_record_with_function;
4255 else if (isa<VarDecl>(Mem))
4256 DK = diag::err_anonymous_record_with_static;
4258 // Visual C++ allows type definition in anonymous struct or union.
4259 if (getLangOpts().MicrosoftExt &&
4260 DK == diag::err_anonymous_record_with_type)
4261 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4262 << Record->isUnion();
4264 Diag(Mem->getLocation(), DK) << Record->isUnion();
4270 // C++11 [class.union]p8 (DR1460):
4271 // At most one variant member of a union may have a
4272 // brace-or-equal-initializer.
4273 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4275 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4276 cast<CXXRecordDecl>(Record));
4279 if (!Record->isUnion() && !Owner->isRecord()) {
4280 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4281 << getLangOpts().CPlusPlus;
4285 // Mock up a declarator.
4286 Declarator Dc(DS, Declarator::MemberContext);
4287 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4288 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4290 // Create a declaration for this anonymous struct/union.
4291 NamedDecl *Anon = nullptr;
4292 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4293 Anon = FieldDecl::Create(Context, OwningClass,
4295 Record->getLocation(),
4296 /*IdentifierInfo=*/nullptr,
4297 Context.getTypeDeclType(Record),
4299 /*BitWidth=*/nullptr, /*Mutable=*/false,
4300 /*InitStyle=*/ICIS_NoInit);
4301 Anon->setAccess(AS);
4302 if (getLangOpts().CPlusPlus)
4303 FieldCollector->Add(cast<FieldDecl>(Anon));
4305 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4306 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4307 if (SCSpec == DeclSpec::SCS_mutable) {
4308 // mutable can only appear on non-static class members, so it's always
4310 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4315 Anon = VarDecl::Create(Context, Owner,
4317 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4318 Context.getTypeDeclType(Record),
4321 // Default-initialize the implicit variable. This initialization will be
4322 // trivial in almost all cases, except if a union member has an in-class
4324 // union { int n = 0; };
4325 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4327 Anon->setImplicit();
4329 // Mark this as an anonymous struct/union type.
4330 Record->setAnonymousStructOrUnion(true);
4332 // Add the anonymous struct/union object to the current
4333 // context. We'll be referencing this object when we refer to one of
4335 Owner->addDecl(Anon);
4337 // Inject the members of the anonymous struct/union into the owning
4338 // context and into the identifier resolver chain for name lookup
4340 SmallVector<NamedDecl*, 2> Chain;
4341 Chain.push_back(Anon);
4343 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4347 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4348 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4349 Decl *ManglingContextDecl;
4350 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4351 NewVD->getDeclContext(), ManglingContextDecl)) {
4352 Context.setManglingNumber(
4353 NewVD, MCtx->getManglingNumber(
4354 NewVD, getMSManglingNumber(getLangOpts(), S)));
4355 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4361 Anon->setInvalidDecl();
4366 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4367 /// Microsoft C anonymous structure.
4368 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4371 /// struct A { int a; };
4372 /// struct B { struct A; int b; };
4379 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4380 RecordDecl *Record) {
4381 assert(Record && "expected a record!");
4383 // Mock up a declarator.
4384 Declarator Dc(DS, Declarator::TypeNameContext);
4385 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4386 assert(TInfo && "couldn't build declarator info for anonymous struct");
4388 auto *ParentDecl = cast<RecordDecl>(CurContext);
4389 QualType RecTy = Context.getTypeDeclType(Record);
4391 // Create a declaration for this anonymous struct.
4392 NamedDecl *Anon = FieldDecl::Create(Context,
4396 /*IdentifierInfo=*/nullptr,
4399 /*BitWidth=*/nullptr, /*Mutable=*/false,
4400 /*InitStyle=*/ICIS_NoInit);
4401 Anon->setImplicit();
4403 // Add the anonymous struct object to the current context.
4404 CurContext->addDecl(Anon);
4406 // Inject the members of the anonymous struct into the current
4407 // context and into the identifier resolver chain for name lookup
4409 SmallVector<NamedDecl*, 2> Chain;
4410 Chain.push_back(Anon);
4412 RecordDecl *RecordDef = Record->getDefinition();
4413 if (RequireCompleteType(Anon->getLocation(), RecTy,
4414 diag::err_field_incomplete) ||
4415 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4416 AS_none, Chain, true)) {
4417 Anon->setInvalidDecl();
4418 ParentDecl->setInvalidDecl();
4424 /// GetNameForDeclarator - Determine the full declaration name for the
4425 /// given Declarator.
4426 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4427 return GetNameFromUnqualifiedId(D.getName());
4430 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4432 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4433 DeclarationNameInfo NameInfo;
4434 NameInfo.setLoc(Name.StartLocation);
4436 switch (Name.getKind()) {
4438 case UnqualifiedId::IK_ImplicitSelfParam:
4439 case UnqualifiedId::IK_Identifier:
4440 NameInfo.setName(Name.Identifier);
4441 NameInfo.setLoc(Name.StartLocation);
4444 case UnqualifiedId::IK_OperatorFunctionId:
4445 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4446 Name.OperatorFunctionId.Operator));
4447 NameInfo.setLoc(Name.StartLocation);
4448 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4449 = Name.OperatorFunctionId.SymbolLocations[0];
4450 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4451 = Name.EndLocation.getRawEncoding();
4454 case UnqualifiedId::IK_LiteralOperatorId:
4455 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4457 NameInfo.setLoc(Name.StartLocation);
4458 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4461 case UnqualifiedId::IK_ConversionFunctionId: {
4462 TypeSourceInfo *TInfo;
4463 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4465 return DeclarationNameInfo();
4466 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4467 Context.getCanonicalType(Ty)));
4468 NameInfo.setLoc(Name.StartLocation);
4469 NameInfo.setNamedTypeInfo(TInfo);
4473 case UnqualifiedId::IK_ConstructorName: {
4474 TypeSourceInfo *TInfo;
4475 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4477 return DeclarationNameInfo();
4478 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4479 Context.getCanonicalType(Ty)));
4480 NameInfo.setLoc(Name.StartLocation);
4481 NameInfo.setNamedTypeInfo(TInfo);
4485 case UnqualifiedId::IK_ConstructorTemplateId: {
4486 // In well-formed code, we can only have a constructor
4487 // template-id that refers to the current context, so go there
4488 // to find the actual type being constructed.
4489 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4490 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4491 return DeclarationNameInfo();
4493 // Determine the type of the class being constructed.
4494 QualType CurClassType = Context.getTypeDeclType(CurClass);
4496 // FIXME: Check two things: that the template-id names the same type as
4497 // CurClassType, and that the template-id does not occur when the name
4500 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4501 Context.getCanonicalType(CurClassType)));
4502 NameInfo.setLoc(Name.StartLocation);
4503 // FIXME: should we retrieve TypeSourceInfo?
4504 NameInfo.setNamedTypeInfo(nullptr);
4508 case UnqualifiedId::IK_DestructorName: {
4509 TypeSourceInfo *TInfo;
4510 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4512 return DeclarationNameInfo();
4513 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4514 Context.getCanonicalType(Ty)));
4515 NameInfo.setLoc(Name.StartLocation);
4516 NameInfo.setNamedTypeInfo(TInfo);
4520 case UnqualifiedId::IK_TemplateId: {
4521 TemplateName TName = Name.TemplateId->Template.get();
4522 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4523 return Context.getNameForTemplate(TName, TNameLoc);
4526 } // switch (Name.getKind())
4528 llvm_unreachable("Unknown name kind");
4531 static QualType getCoreType(QualType Ty) {
4533 if (Ty->isPointerType() || Ty->isReferenceType())
4534 Ty = Ty->getPointeeType();
4535 else if (Ty->isArrayType())
4536 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4538 return Ty.withoutLocalFastQualifiers();
4542 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4543 /// and Definition have "nearly" matching parameters. This heuristic is
4544 /// used to improve diagnostics in the case where an out-of-line function
4545 /// definition doesn't match any declaration within the class or namespace.
4546 /// Also sets Params to the list of indices to the parameters that differ
4547 /// between the declaration and the definition. If hasSimilarParameters
4548 /// returns true and Params is empty, then all of the parameters match.
4549 static bool hasSimilarParameters(ASTContext &Context,
4550 FunctionDecl *Declaration,
4551 FunctionDecl *Definition,
4552 SmallVectorImpl<unsigned> &Params) {
4554 if (Declaration->param_size() != Definition->param_size())
4556 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4557 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4558 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4560 // The parameter types are identical
4561 if (Context.hasSameType(DefParamTy, DeclParamTy))
4564 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4565 QualType DefParamBaseTy = getCoreType(DefParamTy);
4566 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4567 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4569 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4570 (DeclTyName && DeclTyName == DefTyName))
4571 Params.push_back(Idx);
4572 else // The two parameters aren't even close
4579 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4580 /// declarator needs to be rebuilt in the current instantiation.
4581 /// Any bits of declarator which appear before the name are valid for
4582 /// consideration here. That's specifically the type in the decl spec
4583 /// and the base type in any member-pointer chunks.
4584 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4585 DeclarationName Name) {
4586 // The types we specifically need to rebuild are:
4587 // - typenames, typeofs, and decltypes
4588 // - types which will become injected class names
4589 // Of course, we also need to rebuild any type referencing such a
4590 // type. It's safest to just say "dependent", but we call out a
4593 DeclSpec &DS = D.getMutableDeclSpec();
4594 switch (DS.getTypeSpecType()) {
4595 case DeclSpec::TST_typename:
4596 case DeclSpec::TST_typeofType:
4597 case DeclSpec::TST_underlyingType:
4598 case DeclSpec::TST_atomic: {
4599 // Grab the type from the parser.
4600 TypeSourceInfo *TSI = nullptr;
4601 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4602 if (T.isNull() || !T->isDependentType()) break;
4604 // Make sure there's a type source info. This isn't really much
4605 // of a waste; most dependent types should have type source info
4606 // attached already.
4608 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4610 // Rebuild the type in the current instantiation.
4611 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4612 if (!TSI) return true;
4614 // Store the new type back in the decl spec.
4615 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4616 DS.UpdateTypeRep(LocType);
4620 case DeclSpec::TST_decltype:
4621 case DeclSpec::TST_typeofExpr: {
4622 Expr *E = DS.getRepAsExpr();
4623 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4624 if (Result.isInvalid()) return true;
4625 DS.UpdateExprRep(Result.get());
4630 // Nothing to do for these decl specs.
4634 // It doesn't matter what order we do this in.
4635 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4636 DeclaratorChunk &Chunk = D.getTypeObject(I);
4638 // The only type information in the declarator which can come
4639 // before the declaration name is the base type of a member
4641 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4644 // Rebuild the scope specifier in-place.
4645 CXXScopeSpec &SS = Chunk.Mem.Scope();
4646 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4653 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4654 D.setFunctionDefinitionKind(FDK_Declaration);
4655 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4657 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4658 Dcl && Dcl->getDeclContext()->isFileContext())
4659 Dcl->setTopLevelDeclInObjCContainer();
4664 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4665 /// If T is the name of a class, then each of the following shall have a
4666 /// name different from T:
4667 /// - every static data member of class T;
4668 /// - every member function of class T
4669 /// - every member of class T that is itself a type;
4670 /// \returns true if the declaration name violates these rules.
4671 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4672 DeclarationNameInfo NameInfo) {
4673 DeclarationName Name = NameInfo.getName();
4675 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4676 while (Record && Record->isAnonymousStructOrUnion())
4677 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4678 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4679 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4686 /// \brief Diagnose a declaration whose declarator-id has the given
4687 /// nested-name-specifier.
4689 /// \param SS The nested-name-specifier of the declarator-id.
4691 /// \param DC The declaration context to which the nested-name-specifier
4694 /// \param Name The name of the entity being declared.
4696 /// \param Loc The location of the name of the entity being declared.
4698 /// \returns true if we cannot safely recover from this error, false otherwise.
4699 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4700 DeclarationName Name,
4701 SourceLocation Loc) {
4702 DeclContext *Cur = CurContext;
4703 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4704 Cur = Cur->getParent();
4706 // If the user provided a superfluous scope specifier that refers back to the
4707 // class in which the entity is already declared, diagnose and ignore it.
4713 // Note, it was once ill-formed to give redundant qualification in all
4714 // contexts, but that rule was removed by DR482.
4715 if (Cur->Equals(DC)) {
4716 if (Cur->isRecord()) {
4717 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4718 : diag::err_member_extra_qualification)
4719 << Name << FixItHint::CreateRemoval(SS.getRange());
4722 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4727 // Check whether the qualifying scope encloses the scope of the original
4729 if (!Cur->Encloses(DC)) {
4730 if (Cur->isRecord())
4731 Diag(Loc, diag::err_member_qualification)
4732 << Name << SS.getRange();
4733 else if (isa<TranslationUnitDecl>(DC))
4734 Diag(Loc, diag::err_invalid_declarator_global_scope)
4735 << Name << SS.getRange();
4736 else if (isa<FunctionDecl>(Cur))
4737 Diag(Loc, diag::err_invalid_declarator_in_function)
4738 << Name << SS.getRange();
4739 else if (isa<BlockDecl>(Cur))
4740 Diag(Loc, diag::err_invalid_declarator_in_block)
4741 << Name << SS.getRange();
4743 Diag(Loc, diag::err_invalid_declarator_scope)
4744 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4749 if (Cur->isRecord()) {
4750 // Cannot qualify members within a class.
4751 Diag(Loc, diag::err_member_qualification)
4752 << Name << SS.getRange();
4755 // C++ constructors and destructors with incorrect scopes can break
4756 // our AST invariants by having the wrong underlying types. If
4757 // that's the case, then drop this declaration entirely.
4758 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4759 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4760 !Context.hasSameType(Name.getCXXNameType(),
4761 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4767 // C++11 [dcl.meaning]p1:
4768 // [...] "The nested-name-specifier of the qualified declarator-id shall
4769 // not begin with a decltype-specifer"
4770 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4771 while (SpecLoc.getPrefix())
4772 SpecLoc = SpecLoc.getPrefix();
4773 if (dyn_cast_or_null<DecltypeType>(
4774 SpecLoc.getNestedNameSpecifier()->getAsType()))
4775 Diag(Loc, diag::err_decltype_in_declarator)
4776 << SpecLoc.getTypeLoc().getSourceRange();
4781 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4782 MultiTemplateParamsArg TemplateParamLists) {
4783 // TODO: consider using NameInfo for diagnostic.
4784 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4785 DeclarationName Name = NameInfo.getName();
4787 // All of these full declarators require an identifier. If it doesn't have
4788 // one, the ParsedFreeStandingDeclSpec action should be used.
4790 if (!D.isInvalidType()) // Reject this if we think it is valid.
4791 Diag(D.getDeclSpec().getLocStart(),
4792 diag::err_declarator_need_ident)
4793 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4795 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4798 // The scope passed in may not be a decl scope. Zip up the scope tree until
4799 // we find one that is.
4800 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4801 (S->getFlags() & Scope::TemplateParamScope) != 0)
4804 DeclContext *DC = CurContext;
4805 if (D.getCXXScopeSpec().isInvalid())
4807 else if (D.getCXXScopeSpec().isSet()) {
4808 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4809 UPPC_DeclarationQualifier))
4812 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4813 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4814 if (!DC || isa<EnumDecl>(DC)) {
4815 // If we could not compute the declaration context, it's because the
4816 // declaration context is dependent but does not refer to a class,
4817 // class template, or class template partial specialization. Complain
4818 // and return early, to avoid the coming semantic disaster.
4819 Diag(D.getIdentifierLoc(),
4820 diag::err_template_qualified_declarator_no_match)
4821 << D.getCXXScopeSpec().getScopeRep()
4822 << D.getCXXScopeSpec().getRange();
4825 bool IsDependentContext = DC->isDependentContext();
4827 if (!IsDependentContext &&
4828 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4831 // If a class is incomplete, do not parse entities inside it.
4832 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4833 Diag(D.getIdentifierLoc(),
4834 diag::err_member_def_undefined_record)
4835 << Name << DC << D.getCXXScopeSpec().getRange();
4838 if (!D.getDeclSpec().isFriendSpecified()) {
4839 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4840 Name, D.getIdentifierLoc())) {
4848 // Check whether we need to rebuild the type of the given
4849 // declaration in the current instantiation.
4850 if (EnteringContext && IsDependentContext &&
4851 TemplateParamLists.size() != 0) {
4852 ContextRAII SavedContext(*this, DC);
4853 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4858 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4859 QualType R = TInfo->getType();
4861 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4862 // If this is a typedef, we'll end up spewing multiple diagnostics.
4863 // Just return early; it's safer. If this is a function, let the
4864 // "constructor cannot have a return type" diagnostic handle it.
4865 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4868 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4869 UPPC_DeclarationType))
4872 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4875 // See if this is a redefinition of a variable in the same scope.
4876 if (!D.getCXXScopeSpec().isSet()) {
4877 bool IsLinkageLookup = false;
4878 bool CreateBuiltins = false;
4880 // If the declaration we're planning to build will be a function
4881 // or object with linkage, then look for another declaration with
4882 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4884 // If the declaration we're planning to build will be declared with
4885 // external linkage in the translation unit, create any builtin with
4887 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4889 else if (CurContext->isFunctionOrMethod() &&
4890 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4891 R->isFunctionType())) {
4892 IsLinkageLookup = true;
4894 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4895 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4896 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4897 CreateBuiltins = true;
4899 if (IsLinkageLookup)
4900 Previous.clear(LookupRedeclarationWithLinkage);
4902 LookupName(Previous, S, CreateBuiltins);
4903 } else { // Something like "int foo::x;"
4904 LookupQualifiedName(Previous, DC);
4906 // C++ [dcl.meaning]p1:
4907 // When the declarator-id is qualified, the declaration shall refer to a
4908 // previously declared member of the class or namespace to which the
4909 // qualifier refers (or, in the case of a namespace, of an element of the
4910 // inline namespace set of that namespace (7.3.1)) or to a specialization
4913 // Note that we already checked the context above, and that we do not have
4914 // enough information to make sure that Previous contains the declaration
4915 // we want to match. For example, given:
4922 // void X::f(int) { } // ill-formed
4924 // In this case, Previous will point to the overload set
4925 // containing the two f's declared in X, but neither of them
4928 // C++ [dcl.meaning]p1:
4929 // [...] the member shall not merely have been introduced by a
4930 // using-declaration in the scope of the class or namespace nominated by
4931 // the nested-name-specifier of the declarator-id.
4932 RemoveUsingDecls(Previous);
4935 if (Previous.isSingleResult() &&
4936 Previous.getFoundDecl()->isTemplateParameter()) {
4937 // Maybe we will complain about the shadowed template parameter.
4938 if (!D.isInvalidType())
4939 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4940 Previous.getFoundDecl());
4942 // Just pretend that we didn't see the previous declaration.
4946 // In C++, the previous declaration we find might be a tag type
4947 // (class or enum). In this case, the new declaration will hide the
4948 // tag type. Note that this does does not apply if we're declaring a
4949 // typedef (C++ [dcl.typedef]p4).
4950 if (Previous.isSingleTagDecl() &&
4951 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4954 // Check that there are no default arguments other than in the parameters
4955 // of a function declaration (C++ only).
4956 if (getLangOpts().CPlusPlus)
4957 CheckExtraCXXDefaultArguments(D);
4959 if (D.getDeclSpec().isConceptSpecified()) {
4960 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
4961 // applied only to the definition of a function template or variable
4962 // template, declared in namespace scope
4963 if (!TemplateParamLists.size()) {
4964 Diag(D.getDeclSpec().getConceptSpecLoc(),
4965 diag:: err_concept_wrong_decl_kind);
4969 if (!DC->getRedeclContext()->isFileContext()) {
4970 Diag(D.getIdentifierLoc(),
4971 diag::err_concept_decls_may_only_appear_in_namespace_scope);
4978 bool AddToScope = true;
4979 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4980 if (TemplateParamLists.size()) {
4981 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4985 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4986 } else if (R->isFunctionType()) {
4987 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4991 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4998 // If this has an identifier and is not an invalid redeclaration or
4999 // function template specialization, add it to the scope stack.
5000 if (New->getDeclName() && AddToScope &&
5001 !(D.isRedeclaration() && New->isInvalidDecl())) {
5002 // Only make a locally-scoped extern declaration visible if it is the first
5003 // declaration of this entity. Qualified lookup for such an entity should
5004 // only find this declaration if there is no visible declaration of it.
5005 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5006 PushOnScopeChains(New, S, AddToContext);
5008 CurContext->addHiddenDecl(New);
5014 /// Helper method to turn variable array types into constant array
5015 /// types in certain situations which would otherwise be errors (for
5016 /// GCC compatibility).
5017 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5018 ASTContext &Context,
5019 bool &SizeIsNegative,
5020 llvm::APSInt &Oversized) {
5021 // This method tries to turn a variable array into a constant
5022 // array even when the size isn't an ICE. This is necessary
5023 // for compatibility with code that depends on gcc's buggy
5024 // constant expression folding, like struct {char x[(int)(char*)2];}
5025 SizeIsNegative = false;
5028 if (T->isDependentType())
5031 QualifierCollector Qs;
5032 const Type *Ty = Qs.strip(T);
5034 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5035 QualType Pointee = PTy->getPointeeType();
5036 QualType FixedType =
5037 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5039 if (FixedType.isNull()) return FixedType;
5040 FixedType = Context.getPointerType(FixedType);
5041 return Qs.apply(Context, FixedType);
5043 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5044 QualType Inner = PTy->getInnerType();
5045 QualType FixedType =
5046 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5048 if (FixedType.isNull()) return FixedType;
5049 FixedType = Context.getParenType(FixedType);
5050 return Qs.apply(Context, FixedType);
5053 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5056 // FIXME: We should probably handle this case
5057 if (VLATy->getElementType()->isVariablyModifiedType())
5061 if (!VLATy->getSizeExpr() ||
5062 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5065 // Check whether the array size is negative.
5066 if (Res.isSigned() && Res.isNegative()) {
5067 SizeIsNegative = true;
5071 // Check whether the array is too large to be addressed.
5072 unsigned ActiveSizeBits
5073 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5075 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5080 return Context.getConstantArrayType(VLATy->getElementType(),
5081 Res, ArrayType::Normal, 0);
5085 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5086 SrcTL = SrcTL.getUnqualifiedLoc();
5087 DstTL = DstTL.getUnqualifiedLoc();
5088 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5089 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5090 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5091 DstPTL.getPointeeLoc());
5092 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5095 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5096 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5097 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5098 DstPTL.getInnerLoc());
5099 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5100 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5103 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5104 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5105 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5106 TypeLoc DstElemTL = DstATL.getElementLoc();
5107 DstElemTL.initializeFullCopy(SrcElemTL);
5108 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5109 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5110 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5113 /// Helper method to turn variable array types into constant array
5114 /// types in certain situations which would otherwise be errors (for
5115 /// GCC compatibility).
5116 static TypeSourceInfo*
5117 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5118 ASTContext &Context,
5119 bool &SizeIsNegative,
5120 llvm::APSInt &Oversized) {
5122 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5123 SizeIsNegative, Oversized);
5124 if (FixedTy.isNull())
5126 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5127 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5128 FixedTInfo->getTypeLoc());
5132 /// \brief Register the given locally-scoped extern "C" declaration so
5133 /// that it can be found later for redeclarations. We include any extern "C"
5134 /// declaration that is not visible in the translation unit here, not just
5135 /// function-scope declarations.
5137 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5138 if (!getLangOpts().CPlusPlus &&
5139 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5140 // Don't need to track declarations in the TU in C.
5143 // Note that we have a locally-scoped external with this name.
5144 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5147 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5148 // FIXME: We can have multiple results via __attribute__((overloadable)).
5149 auto Result = Context.getExternCContextDecl()->lookup(Name);
5150 return Result.empty() ? nullptr : *Result.begin();
5153 /// \brief Diagnose function specifiers on a declaration of an identifier that
5154 /// does not identify a function.
5155 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5156 // FIXME: We should probably indicate the identifier in question to avoid
5157 // confusion for constructs like "inline int a(), b;"
5158 if (DS.isInlineSpecified())
5159 Diag(DS.getInlineSpecLoc(),
5160 diag::err_inline_non_function);
5162 if (DS.isVirtualSpecified())
5163 Diag(DS.getVirtualSpecLoc(),
5164 diag::err_virtual_non_function);
5166 if (DS.isExplicitSpecified())
5167 Diag(DS.getExplicitSpecLoc(),
5168 diag::err_explicit_non_function);
5170 if (DS.isNoreturnSpecified())
5171 Diag(DS.getNoreturnSpecLoc(),
5172 diag::err_noreturn_non_function);
5176 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5177 TypeSourceInfo *TInfo, LookupResult &Previous) {
5178 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5179 if (D.getCXXScopeSpec().isSet()) {
5180 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5181 << D.getCXXScopeSpec().getRange();
5183 // Pretend we didn't see the scope specifier.
5188 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5190 if (D.getDeclSpec().isConstexprSpecified())
5191 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5193 if (D.getDeclSpec().isConceptSpecified())
5194 Diag(D.getDeclSpec().getConceptSpecLoc(),
5195 diag::err_concept_wrong_decl_kind);
5197 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5198 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5199 << D.getName().getSourceRange();
5203 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5204 if (!NewTD) return nullptr;
5206 // Handle attributes prior to checking for duplicates in MergeVarDecl
5207 ProcessDeclAttributes(S, NewTD, D);
5209 CheckTypedefForVariablyModifiedType(S, NewTD);
5211 bool Redeclaration = D.isRedeclaration();
5212 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5213 D.setRedeclaration(Redeclaration);
5218 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5219 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5220 // then it shall have block scope.
5221 // Note that variably modified types must be fixed before merging the decl so
5222 // that redeclarations will match.
5223 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5224 QualType T = TInfo->getType();
5225 if (T->isVariablyModifiedType()) {
5226 getCurFunction()->setHasBranchProtectedScope();
5228 if (S->getFnParent() == nullptr) {
5229 bool SizeIsNegative;
5230 llvm::APSInt Oversized;
5231 TypeSourceInfo *FixedTInfo =
5232 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5236 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5237 NewTD->setTypeSourceInfo(FixedTInfo);
5240 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5241 else if (T->isVariableArrayType())
5242 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5243 else if (Oversized.getBoolValue())
5244 Diag(NewTD->getLocation(), diag::err_array_too_large)
5245 << Oversized.toString(10);
5247 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5248 NewTD->setInvalidDecl();
5255 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5256 /// declares a typedef-name, either using the 'typedef' type specifier or via
5257 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5259 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5260 LookupResult &Previous, bool &Redeclaration) {
5261 // Merge the decl with the existing one if appropriate. If the decl is
5262 // in an outer scope, it isn't the same thing.
5263 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5264 /*AllowInlineNamespace*/false);
5265 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5266 if (!Previous.empty()) {
5267 Redeclaration = true;
5268 MergeTypedefNameDecl(S, NewTD, Previous);
5271 // If this is the C FILE type, notify the AST context.
5272 if (IdentifierInfo *II = NewTD->getIdentifier())
5273 if (!NewTD->isInvalidDecl() &&
5274 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5275 if (II->isStr("FILE"))
5276 Context.setFILEDecl(NewTD);
5277 else if (II->isStr("jmp_buf"))
5278 Context.setjmp_bufDecl(NewTD);
5279 else if (II->isStr("sigjmp_buf"))
5280 Context.setsigjmp_bufDecl(NewTD);
5281 else if (II->isStr("ucontext_t"))
5282 Context.setucontext_tDecl(NewTD);
5288 /// \brief Determines whether the given declaration is an out-of-scope
5289 /// previous declaration.
5291 /// This routine should be invoked when name lookup has found a
5292 /// previous declaration (PrevDecl) that is not in the scope where a
5293 /// new declaration by the same name is being introduced. If the new
5294 /// declaration occurs in a local scope, previous declarations with
5295 /// linkage may still be considered previous declarations (C99
5296 /// 6.2.2p4-5, C++ [basic.link]p6).
5298 /// \param PrevDecl the previous declaration found by name
5301 /// \param DC the context in which the new declaration is being
5304 /// \returns true if PrevDecl is an out-of-scope previous declaration
5305 /// for a new delcaration with the same name.
5307 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5308 ASTContext &Context) {
5312 if (!PrevDecl->hasLinkage())
5315 if (Context.getLangOpts().CPlusPlus) {
5316 // C++ [basic.link]p6:
5317 // If there is a visible declaration of an entity with linkage
5318 // having the same name and type, ignoring entities declared
5319 // outside the innermost enclosing namespace scope, the block
5320 // scope declaration declares that same entity and receives the
5321 // linkage of the previous declaration.
5322 DeclContext *OuterContext = DC->getRedeclContext();
5323 if (!OuterContext->isFunctionOrMethod())
5324 // This rule only applies to block-scope declarations.
5327 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5328 if (PrevOuterContext->isRecord())
5329 // We found a member function: ignore it.
5332 // Find the innermost enclosing namespace for the new and
5333 // previous declarations.
5334 OuterContext = OuterContext->getEnclosingNamespaceContext();
5335 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5337 // The previous declaration is in a different namespace, so it
5338 // isn't the same function.
5339 if (!OuterContext->Equals(PrevOuterContext))
5346 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5347 CXXScopeSpec &SS = D.getCXXScopeSpec();
5348 if (!SS.isSet()) return;
5349 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5352 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5353 QualType type = decl->getType();
5354 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5355 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5356 // Various kinds of declaration aren't allowed to be __autoreleasing.
5357 unsigned kind = -1U;
5358 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5359 if (var->hasAttr<BlocksAttr>())
5360 kind = 0; // __block
5361 else if (!var->hasLocalStorage())
5363 } else if (isa<ObjCIvarDecl>(decl)) {
5365 } else if (isa<FieldDecl>(decl)) {
5370 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5373 } else if (lifetime == Qualifiers::OCL_None) {
5374 // Try to infer lifetime.
5375 if (!type->isObjCLifetimeType())
5378 lifetime = type->getObjCARCImplicitLifetime();
5379 type = Context.getLifetimeQualifiedType(type, lifetime);
5380 decl->setType(type);
5383 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5384 // Thread-local variables cannot have lifetime.
5385 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5386 var->getTLSKind()) {
5387 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5396 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5397 // Ensure that an auto decl is deduced otherwise the checks below might cache
5398 // the wrong linkage.
5399 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5401 // 'weak' only applies to declarations with external linkage.
5402 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5403 if (!ND.isExternallyVisible()) {
5404 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5405 ND.dropAttr<WeakAttr>();
5408 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5409 if (ND.isExternallyVisible()) {
5410 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5411 ND.dropAttr<WeakRefAttr>();
5412 ND.dropAttr<AliasAttr>();
5416 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5417 if (VD->hasInit()) {
5418 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5419 assert(VD->isThisDeclarationADefinition() &&
5420 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5421 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5422 VD->dropAttr<AliasAttr>();
5427 // 'selectany' only applies to externally visible variable declarations.
5428 // It does not apply to functions.
5429 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5430 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5431 S.Diag(Attr->getLocation(),
5432 diag::err_attribute_selectany_non_extern_data);
5433 ND.dropAttr<SelectAnyAttr>();
5437 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5438 // dll attributes require external linkage. Static locals may have external
5439 // linkage but still cannot be explicitly imported or exported.
5440 auto *VD = dyn_cast<VarDecl>(&ND);
5441 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5442 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5444 ND.setInvalidDecl();
5448 // Virtual functions cannot be marked as 'notail'.
5449 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5450 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5451 if (MD->isVirtual()) {
5452 S.Diag(ND.getLocation(),
5453 diag::err_invalid_attribute_on_virtual_function)
5455 ND.dropAttr<NotTailCalledAttr>();
5459 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5461 bool IsSpecialization) {
5462 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5463 OldDecl = OldTD->getTemplatedDecl();
5464 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5465 NewDecl = NewTD->getTemplatedDecl();
5467 if (!OldDecl || !NewDecl)
5470 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5471 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5472 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5473 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5475 // dllimport and dllexport are inheritable attributes so we have to exclude
5476 // inherited attribute instances.
5477 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5478 (NewExportAttr && !NewExportAttr->isInherited());
5480 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5481 // the only exception being explicit specializations.
5482 // Implicitly generated declarations are also excluded for now because there
5483 // is no other way to switch these to use dllimport or dllexport.
5484 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5486 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5487 // Allow with a warning for free functions and global variables.
5488 bool JustWarn = false;
5489 if (!OldDecl->isCXXClassMember()) {
5490 auto *VD = dyn_cast<VarDecl>(OldDecl);
5491 if (VD && !VD->getDescribedVarTemplate())
5493 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5494 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5498 // We cannot change a declaration that's been used because IR has already
5499 // been emitted. Dllimported functions will still work though (modulo
5500 // address equality) as they can use the thunk.
5501 if (OldDecl->isUsed())
5502 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5505 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5506 : diag::err_attribute_dll_redeclaration;
5507 S.Diag(NewDecl->getLocation(), DiagID)
5509 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5510 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5512 NewDecl->setInvalidDecl();
5517 // A redeclaration is not allowed to drop a dllimport attribute, the only
5518 // exceptions being inline function definitions, local extern declarations,
5519 // and qualified friend declarations.
5520 // NB: MSVC converts such a declaration to dllexport.
5521 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5522 if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5523 // Ignore static data because out-of-line definitions are diagnosed
5525 IsStaticDataMember = VD->isStaticDataMember();
5526 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5527 IsInline = FD->isInlined();
5528 IsQualifiedFriend = FD->getQualifier() &&
5529 FD->getFriendObjectKind() == Decl::FOK_Declared;
5532 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5533 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5534 S.Diag(NewDecl->getLocation(),
5535 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5536 << NewDecl << OldImportAttr;
5537 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5538 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5539 OldDecl->dropAttr<DLLImportAttr>();
5540 NewDecl->dropAttr<DLLImportAttr>();
5541 } else if (IsInline && OldImportAttr &&
5542 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5543 // In MinGW, seeing a function declared inline drops the dllimport attribute.
5544 OldDecl->dropAttr<DLLImportAttr>();
5545 NewDecl->dropAttr<DLLImportAttr>();
5546 S.Diag(NewDecl->getLocation(),
5547 diag::warn_dllimport_dropped_from_inline_function)
5548 << NewDecl << OldImportAttr;
5552 /// Given that we are within the definition of the given function,
5553 /// will that definition behave like C99's 'inline', where the
5554 /// definition is discarded except for optimization purposes?
5555 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5556 // Try to avoid calling GetGVALinkageForFunction.
5558 // All cases of this require the 'inline' keyword.
5559 if (!FD->isInlined()) return false;
5561 // This is only possible in C++ with the gnu_inline attribute.
5562 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5565 // Okay, go ahead and call the relatively-more-expensive function.
5568 // AST quite reasonably asserts that it's working on a function
5569 // definition. We don't really have a way to tell it that we're
5570 // currently defining the function, so just lie to it in +Asserts
5571 // builds. This is an awful hack.
5576 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5585 /// Determine whether a variable is extern "C" prior to attaching
5586 /// an initializer. We can't just call isExternC() here, because that
5587 /// will also compute and cache whether the declaration is externally
5588 /// visible, which might change when we attach the initializer.
5590 /// This can only be used if the declaration is known to not be a
5591 /// redeclaration of an internal linkage declaration.
5597 /// Attaching the initializer here makes this declaration not externally
5598 /// visible, because its type has internal linkage.
5600 /// FIXME: This is a hack.
5601 template<typename T>
5602 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5603 if (S.getLangOpts().CPlusPlus) {
5604 // In C++, the overloadable attribute negates the effects of extern "C".
5605 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5608 // So do CUDA's host/device attributes if overloading is enabled.
5609 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
5610 (D->template hasAttr<CUDADeviceAttr>() ||
5611 D->template hasAttr<CUDAHostAttr>()))
5614 return D->isExternC();
5617 static bool shouldConsiderLinkage(const VarDecl *VD) {
5618 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5619 if (DC->isFunctionOrMethod())
5620 return VD->hasExternalStorage();
5621 if (DC->isFileContext())
5625 llvm_unreachable("Unexpected context");
5628 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5629 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5630 if (DC->isFileContext() || DC->isFunctionOrMethod())
5634 llvm_unreachable("Unexpected context");
5637 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5638 AttributeList::Kind Kind) {
5639 for (const AttributeList *L = AttrList; L; L = L->getNext())
5640 if (L->getKind() == Kind)
5645 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5646 AttributeList::Kind Kind) {
5647 // Check decl attributes on the DeclSpec.
5648 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5651 // Walk the declarator structure, checking decl attributes that were in a type
5652 // position to the decl itself.
5653 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5654 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5658 // Finally, check attributes on the decl itself.
5659 return hasParsedAttr(S, PD.getAttributes(), Kind);
5662 /// Adjust the \c DeclContext for a function or variable that might be a
5663 /// function-local external declaration.
5664 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5665 if (!DC->isFunctionOrMethod())
5668 // If this is a local extern function or variable declared within a function
5669 // template, don't add it into the enclosing namespace scope until it is
5670 // instantiated; it might have a dependent type right now.
5671 if (DC->isDependentContext())
5674 // C++11 [basic.link]p7:
5675 // When a block scope declaration of an entity with linkage is not found to
5676 // refer to some other declaration, then that entity is a member of the
5677 // innermost enclosing namespace.
5679 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5680 // semantically-enclosing namespace, not a lexically-enclosing one.
5681 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5682 DC = DC->getParent();
5686 /// \brief Returns true if given declaration has external C language linkage.
5687 static bool isDeclExternC(const Decl *D) {
5688 if (const auto *FD = dyn_cast<FunctionDecl>(D))
5689 return FD->isExternC();
5690 if (const auto *VD = dyn_cast<VarDecl>(D))
5691 return VD->isExternC();
5693 llvm_unreachable("Unknown type of decl!");
5697 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5698 TypeSourceInfo *TInfo, LookupResult &Previous,
5699 MultiTemplateParamsArg TemplateParamLists,
5701 QualType R = TInfo->getType();
5702 DeclarationName Name = GetNameForDeclarator(D).getName();
5704 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5705 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5707 // dllimport globals without explicit storage class are treated as extern. We
5708 // have to change the storage class this early to get the right DeclContext.
5709 if (SC == SC_None && !DC->isRecord() &&
5710 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5711 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5714 DeclContext *OriginalDC = DC;
5715 bool IsLocalExternDecl = SC == SC_Extern &&
5716 adjustContextForLocalExternDecl(DC);
5718 if (getLangOpts().OpenCL) {
5719 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5721 while (NR->isPointerType()) {
5722 if (NR->isFunctionPointerType()) {
5723 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5727 NR = NR->getPointeeType();
5730 if (!getOpenCLOptions().cl_khr_fp16) {
5731 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5732 // half array type (unless the cl_khr_fp16 extension is enabled).
5733 if (Context.getBaseElementType(R)->isHalfType()) {
5734 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5740 if (SCSpec == DeclSpec::SCS_mutable) {
5741 // mutable can only appear on non-static class members, so it's always
5743 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5748 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5749 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5750 D.getDeclSpec().getStorageClassSpecLoc())) {
5751 // In C++11, the 'register' storage class specifier is deprecated.
5752 // Suppress the warning in system macros, it's used in macros in some
5753 // popular C system headers, such as in glibc's htonl() macro.
5754 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5755 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5756 : diag::warn_deprecated_register)
5757 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5760 IdentifierInfo *II = Name.getAsIdentifierInfo();
5762 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5767 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5769 if (!DC->isRecord() && S->getFnParent() == nullptr) {
5770 // C99 6.9p2: The storage-class specifiers auto and register shall not
5771 // appear in the declaration specifiers in an external declaration.
5772 // Global Register+Asm is a GNU extension we support.
5773 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5774 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5779 if (getLangOpts().OpenCL) {
5780 // OpenCL v1.2 s6.9.b p4:
5781 // The sampler type cannot be used with the __local and __global address
5782 // space qualifiers.
5783 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5784 R.getAddressSpace() == LangAS::opencl_global)) {
5785 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5788 // OpenCL 1.2 spec, p6.9 r:
5789 // The event type cannot be used to declare a program scope variable.
5790 // The event type cannot be used with the __local, __constant and __global
5791 // address space qualifiers.
5792 if (R->isEventT()) {
5793 if (S->getParent() == nullptr) {
5794 Diag(D.getLocStart(), diag::err_event_t_global_var);
5798 if (R.getAddressSpace()) {
5799 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5805 bool IsExplicitSpecialization = false;
5806 bool IsVariableTemplateSpecialization = false;
5807 bool IsPartialSpecialization = false;
5808 bool IsVariableTemplate = false;
5809 VarDecl *NewVD = nullptr;
5810 VarTemplateDecl *NewTemplate = nullptr;
5811 TemplateParameterList *TemplateParams = nullptr;
5812 if (!getLangOpts().CPlusPlus) {
5813 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5814 D.getIdentifierLoc(), II,
5817 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5818 ParsingInitForAutoVars.insert(NewVD);
5820 if (D.isInvalidType())
5821 NewVD->setInvalidDecl();
5823 bool Invalid = false;
5825 if (DC->isRecord() && !CurContext->isRecord()) {
5826 // This is an out-of-line definition of a static data member.
5831 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5832 diag::err_static_out_of_line)
5833 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5838 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5839 // to names of variables declared in a block or to function parameters.
5840 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5843 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5844 diag::err_storage_class_for_static_member)
5845 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5847 case SC_PrivateExtern:
5848 llvm_unreachable("C storage class in c++!");
5852 if (SC == SC_Static && CurContext->isRecord()) {
5853 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5854 if (RD->isLocalClass())
5855 Diag(D.getIdentifierLoc(),
5856 diag::err_static_data_member_not_allowed_in_local_class)
5857 << Name << RD->getDeclName();
5859 // C++98 [class.union]p1: If a union contains a static data member,
5860 // the program is ill-formed. C++11 drops this restriction.
5862 Diag(D.getIdentifierLoc(),
5863 getLangOpts().CPlusPlus11
5864 ? diag::warn_cxx98_compat_static_data_member_in_union
5865 : diag::ext_static_data_member_in_union) << Name;
5866 // We conservatively disallow static data members in anonymous structs.
5867 else if (!RD->getDeclName())
5868 Diag(D.getIdentifierLoc(),
5869 diag::err_static_data_member_not_allowed_in_anon_struct)
5870 << Name << RD->isUnion();
5874 // Match up the template parameter lists with the scope specifier, then
5875 // determine whether we have a template or a template specialization.
5876 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5877 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5878 D.getCXXScopeSpec(),
5879 D.getName().getKind() == UnqualifiedId::IK_TemplateId
5880 ? D.getName().TemplateId
5883 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5885 if (TemplateParams) {
5886 if (!TemplateParams->size() &&
5887 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5888 // There is an extraneous 'template<>' for this variable. Complain
5889 // about it, but allow the declaration of the variable.
5890 Diag(TemplateParams->getTemplateLoc(),
5891 diag::err_template_variable_noparams)
5893 << SourceRange(TemplateParams->getTemplateLoc(),
5894 TemplateParams->getRAngleLoc());
5895 TemplateParams = nullptr;
5897 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5898 // This is an explicit specialization or a partial specialization.
5899 // FIXME: Check that we can declare a specialization here.
5900 IsVariableTemplateSpecialization = true;
5901 IsPartialSpecialization = TemplateParams->size() > 0;
5902 } else { // if (TemplateParams->size() > 0)
5903 // This is a template declaration.
5904 IsVariableTemplate = true;
5906 // Check that we can declare a template here.
5907 if (CheckTemplateDeclScope(S, TemplateParams))
5910 // Only C++1y supports variable templates (N3651).
5911 Diag(D.getIdentifierLoc(),
5912 getLangOpts().CPlusPlus14
5913 ? diag::warn_cxx11_compat_variable_template
5914 : diag::ext_variable_template);
5919 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5920 "should have a 'template<>' for this decl");
5923 if (IsVariableTemplateSpecialization) {
5924 SourceLocation TemplateKWLoc =
5925 TemplateParamLists.size() > 0
5926 ? TemplateParamLists[0]->getTemplateLoc()
5928 DeclResult Res = ActOnVarTemplateSpecialization(
5929 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5930 IsPartialSpecialization);
5931 if (Res.isInvalid())
5933 NewVD = cast<VarDecl>(Res.get());
5936 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5937 D.getIdentifierLoc(), II, R, TInfo, SC);
5939 // If this is supposed to be a variable template, create it as such.
5940 if (IsVariableTemplate) {
5942 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5943 TemplateParams, NewVD);
5944 NewVD->setDescribedVarTemplate(NewTemplate);
5947 // If this decl has an auto type in need of deduction, make a note of the
5948 // Decl so we can diagnose uses of it in its own initializer.
5949 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5950 ParsingInitForAutoVars.insert(NewVD);
5952 if (D.isInvalidType() || Invalid) {
5953 NewVD->setInvalidDecl();
5955 NewTemplate->setInvalidDecl();
5958 SetNestedNameSpecifier(NewVD, D);
5960 // If we have any template parameter lists that don't directly belong to
5961 // the variable (matching the scope specifier), store them.
5962 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5963 if (TemplateParamLists.size() > VDTemplateParamLists)
5964 NewVD->setTemplateParameterListsInfo(
5965 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
5967 if (D.getDeclSpec().isConstexprSpecified())
5968 NewVD->setConstexpr(true);
5970 if (D.getDeclSpec().isConceptSpecified()) {
5971 NewVD->setConcept(true);
5973 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
5974 // be declared with the thread_local, inline, friend, or constexpr
5975 // specifiers, [...]
5976 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
5977 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5978 diag::err_concept_decl_invalid_specifiers)
5980 NewVD->setInvalidDecl(true);
5983 if (D.getDeclSpec().isConstexprSpecified()) {
5984 Diag(D.getDeclSpec().getConstexprSpecLoc(),
5985 diag::err_concept_decl_invalid_specifiers)
5987 NewVD->setInvalidDecl(true);
5992 // Set the lexical context. If the declarator has a C++ scope specifier, the
5993 // lexical context will be different from the semantic context.
5994 NewVD->setLexicalDeclContext(CurContext);
5996 NewTemplate->setLexicalDeclContext(CurContext);
5998 if (IsLocalExternDecl)
5999 NewVD->setLocalExternDecl();
6001 bool EmitTLSUnsupportedError = false;
6002 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6003 // C++11 [dcl.stc]p4:
6004 // When thread_local is applied to a variable of block scope the
6005 // storage-class-specifier static is implied if it does not appear
6007 // Core issue: 'static' is not implied if the variable is declared
6009 if (NewVD->hasLocalStorage() &&
6010 (SCSpec != DeclSpec::SCS_unspecified ||
6011 TSCS != DeclSpec::TSCS_thread_local ||
6012 !DC->isFunctionOrMethod()))
6013 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6014 diag::err_thread_non_global)
6015 << DeclSpec::getSpecifierName(TSCS);
6016 else if (!Context.getTargetInfo().isTLSSupported()) {
6017 if (getLangOpts().CUDA) {
6018 // Postpone error emission until we've collected attributes required to
6019 // figure out whether it's a host or device variable and whether the
6020 // error should be ignored.
6021 EmitTLSUnsupportedError = true;
6022 // We still need to mark the variable as TLS so it shows up in AST with
6023 // proper storage class for other tools to use even if we're not going
6024 // to emit any code for it.
6025 NewVD->setTSCSpec(TSCS);
6027 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6028 diag::err_thread_unsupported);
6030 NewVD->setTSCSpec(TSCS);
6034 // An inline definition of a function with external linkage shall
6035 // not contain a definition of a modifiable object with static or
6036 // thread storage duration...
6037 // We only apply this when the function is required to be defined
6038 // elsewhere, i.e. when the function is not 'extern inline'. Note
6039 // that a local variable with thread storage duration still has to
6040 // be marked 'static'. Also note that it's possible to get these
6041 // semantics in C++ using __attribute__((gnu_inline)).
6042 if (SC == SC_Static && S->getFnParent() != nullptr &&
6043 !NewVD->getType().isConstQualified()) {
6044 FunctionDecl *CurFD = getCurFunctionDecl();
6045 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6046 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6047 diag::warn_static_local_in_extern_inline);
6048 MaybeSuggestAddingStaticToDecl(CurFD);
6052 if (D.getDeclSpec().isModulePrivateSpecified()) {
6053 if (IsVariableTemplateSpecialization)
6054 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6055 << (IsPartialSpecialization ? 1 : 0)
6056 << FixItHint::CreateRemoval(
6057 D.getDeclSpec().getModulePrivateSpecLoc());
6058 else if (IsExplicitSpecialization)
6059 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6061 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6062 else if (NewVD->hasLocalStorage())
6063 Diag(NewVD->getLocation(), diag::err_module_private_local)
6064 << 0 << NewVD->getDeclName()
6065 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6066 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6068 NewVD->setModulePrivate();
6070 NewTemplate->setModulePrivate();
6074 // Handle attributes prior to checking for duplicates in MergeVarDecl
6075 ProcessDeclAttributes(S, NewVD, D);
6077 if (getLangOpts().CUDA) {
6078 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6079 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6080 diag::err_thread_unsupported);
6081 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6082 // storage [duration]."
6083 if (SC == SC_None && S->getFnParent() != nullptr &&
6084 (NewVD->hasAttr<CUDASharedAttr>() ||
6085 NewVD->hasAttr<CUDAConstantAttr>())) {
6086 NewVD->setStorageClass(SC_Static);
6090 // Ensure that dllimport globals without explicit storage class are treated as
6091 // extern. The storage class is set above using parsed attributes. Now we can
6092 // check the VarDecl itself.
6093 assert(!NewVD->hasAttr<DLLImportAttr>() ||
6094 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6095 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6097 // In auto-retain/release, infer strong retension for variables of
6099 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6100 NewVD->setInvalidDecl();
6102 // Handle GNU asm-label extension (encoded as an attribute).
6103 if (Expr *E = (Expr*)D.getAsmLabel()) {
6104 // The parser guarantees this is a string.
6105 StringLiteral *SE = cast<StringLiteral>(E);
6106 StringRef Label = SE->getString();
6107 if (S->getFnParent() != nullptr) {
6111 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6114 // Local Named register
6115 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6116 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6117 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6121 case SC_PrivateExtern:
6124 } else if (SC == SC_Register) {
6125 // Global Named register
6126 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6127 const auto &TI = Context.getTargetInfo();
6128 bool HasSizeMismatch;
6130 if (!TI.isValidGCCRegisterName(Label))
6131 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6132 else if (!TI.validateGlobalRegisterVariable(Label,
6133 Context.getTypeSize(R),
6135 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6136 else if (HasSizeMismatch)
6137 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6140 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6141 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6142 NewVD->setInvalidDecl(true);
6146 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6147 Context, Label, 0));
6148 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6149 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6150 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6151 if (I != ExtnameUndeclaredIdentifiers.end()) {
6152 if (isDeclExternC(NewVD)) {
6153 NewVD->addAttr(I->second);
6154 ExtnameUndeclaredIdentifiers.erase(I);
6156 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6157 << /*Variable*/1 << NewVD;
6161 // Diagnose shadowed variables before filtering for scope.
6162 if (D.getCXXScopeSpec().isEmpty())
6163 CheckShadow(S, NewVD, Previous);
6165 // Don't consider existing declarations that are in a different
6166 // scope and are out-of-semantic-context declarations (if the new
6167 // declaration has linkage).
6168 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6169 D.getCXXScopeSpec().isNotEmpty() ||
6170 IsExplicitSpecialization ||
6171 IsVariableTemplateSpecialization);
6173 // Check whether the previous declaration is in the same block scope. This
6174 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6175 if (getLangOpts().CPlusPlus &&
6176 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6177 NewVD->setPreviousDeclInSameBlockScope(
6178 Previous.isSingleResult() && !Previous.isShadowed() &&
6179 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6181 if (!getLangOpts().CPlusPlus) {
6182 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6184 // If this is an explicit specialization of a static data member, check it.
6185 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6186 CheckMemberSpecialization(NewVD, Previous))
6187 NewVD->setInvalidDecl();
6189 // Merge the decl with the existing one if appropriate.
6190 if (!Previous.empty()) {
6191 if (Previous.isSingleResult() &&
6192 isa<FieldDecl>(Previous.getFoundDecl()) &&
6193 D.getCXXScopeSpec().isSet()) {
6194 // The user tried to define a non-static data member
6195 // out-of-line (C++ [dcl.meaning]p1).
6196 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6197 << D.getCXXScopeSpec().getRange();
6199 NewVD->setInvalidDecl();
6201 } else if (D.getCXXScopeSpec().isSet()) {
6202 // No previous declaration in the qualifying scope.
6203 Diag(D.getIdentifierLoc(), diag::err_no_member)
6204 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6205 << D.getCXXScopeSpec().getRange();
6206 NewVD->setInvalidDecl();
6209 if (!IsVariableTemplateSpecialization)
6210 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6213 VarTemplateDecl *PrevVarTemplate =
6214 NewVD->getPreviousDecl()
6215 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6218 // Check the template parameter list of this declaration, possibly
6219 // merging in the template parameter list from the previous variable
6220 // template declaration.
6221 if (CheckTemplateParameterList(
6223 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6225 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6226 DC->isDependentContext())
6227 ? TPC_ClassTemplateMember
6229 NewVD->setInvalidDecl();
6231 // If we are providing an explicit specialization of a static variable
6232 // template, make a note of that.
6233 if (PrevVarTemplate &&
6234 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6235 PrevVarTemplate->setMemberSpecialization();
6239 ProcessPragmaWeak(S, NewVD);
6241 // If this is the first declaration of an extern C variable, update
6242 // the map of such variables.
6243 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6244 isIncompleteDeclExternC(*this, NewVD))
6245 RegisterLocallyScopedExternCDecl(NewVD, S);
6247 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6248 Decl *ManglingContextDecl;
6249 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6250 NewVD->getDeclContext(), ManglingContextDecl)) {
6251 Context.setManglingNumber(
6252 NewVD, MCtx->getManglingNumber(
6253 NewVD, getMSManglingNumber(getLangOpts(), S)));
6254 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6258 // Special handling of variable named 'main'.
6259 if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6260 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6261 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6263 // C++ [basic.start.main]p3
6264 // A program that declares a variable main at global scope is ill-formed.
6265 if (getLangOpts().CPlusPlus)
6266 Diag(D.getLocStart(), diag::err_main_global_variable);
6268 // In C, and external-linkage variable named main results in undefined
6270 else if (NewVD->hasExternalFormalLinkage())
6271 Diag(D.getLocStart(), diag::warn_main_redefined);
6274 if (D.isRedeclaration() && !Previous.empty()) {
6275 checkDLLAttributeRedeclaration(
6276 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6277 IsExplicitSpecialization);
6281 if (NewVD->isInvalidDecl())
6282 NewTemplate->setInvalidDecl();
6283 ActOnDocumentableDecl(NewTemplate);
6290 /// \brief Diagnose variable or built-in function shadowing. Implements
6293 /// This method is called whenever a VarDecl is added to a "useful"
6296 /// \param S the scope in which the shadowing name is being declared
6297 /// \param R the lookup of the name
6299 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6300 // Return if warning is ignored.
6301 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6304 // Don't diagnose declarations at file scope.
6305 if (D->hasGlobalStorage())
6308 DeclContext *NewDC = D->getDeclContext();
6310 // Only diagnose if we're shadowing an unambiguous field or variable.
6311 if (R.getResultKind() != LookupResult::Found)
6314 NamedDecl* ShadowedDecl = R.getFoundDecl();
6315 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6318 // Fields are not shadowed by variables in C++ static methods.
6319 if (isa<FieldDecl>(ShadowedDecl))
6320 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6324 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6325 if (shadowedVar->isExternC()) {
6326 // For shadowing external vars, make sure that we point to the global
6327 // declaration, not a locally scoped extern declaration.
6328 for (auto I : shadowedVar->redecls())
6329 if (I->isFileVarDecl()) {
6335 DeclContext *OldDC = ShadowedDecl->getDeclContext();
6337 // Only warn about certain kinds of shadowing for class members.
6338 if (NewDC && NewDC->isRecord()) {
6339 // In particular, don't warn about shadowing non-class members.
6340 if (!OldDC->isRecord())
6343 // TODO: should we warn about static data members shadowing
6344 // static data members from base classes?
6346 // TODO: don't diagnose for inaccessible shadowed members.
6347 // This is hard to do perfectly because we might friend the
6348 // shadowing context, but that's just a false negative.
6351 // Determine what kind of declaration we're shadowing.
6353 if (isa<RecordDecl>(OldDC)) {
6354 if (isa<FieldDecl>(ShadowedDecl))
6357 Kind = 2; // static data member
6358 } else if (OldDC->isFileContext())
6363 DeclarationName Name = R.getLookupName();
6365 // Emit warning and note.
6366 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6368 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6369 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6372 /// \brief Check -Wshadow without the advantage of a previous lookup.
6373 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6374 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6377 LookupResult R(*this, D->getDeclName(), D->getLocation(),
6378 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6380 CheckShadow(S, D, R);
6383 /// Check for conflict between this global or extern "C" declaration and
6384 /// previous global or extern "C" declarations. This is only used in C++.
6385 template<typename T>
6386 static bool checkGlobalOrExternCConflict(
6387 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6388 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6389 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6391 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6392 // The common case: this global doesn't conflict with any extern "C"
6398 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6399 // Both the old and new declarations have C language linkage. This is a
6402 Previous.addDecl(Prev);
6406 // This is a global, non-extern "C" declaration, and there is a previous
6407 // non-global extern "C" declaration. Diagnose if this is a variable
6409 if (!isa<VarDecl>(ND))
6412 // The declaration is extern "C". Check for any declaration in the
6413 // translation unit which might conflict.
6415 // We have already performed the lookup into the translation unit.
6417 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6419 if (isa<VarDecl>(*I)) {
6425 DeclContext::lookup_result R =
6426 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6427 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6429 if (isa<VarDecl>(*I)) {
6433 // FIXME: If we have any other entity with this name in global scope,
6434 // the declaration is ill-formed, but that is a defect: it breaks the
6435 // 'stat' hack, for instance. Only variables can have mangled name
6436 // clashes with extern "C" declarations, so only they deserve a
6445 // Use the first declaration's location to ensure we point at something which
6446 // is lexically inside an extern "C" linkage-spec.
6447 assert(Prev && "should have found a previous declaration to diagnose");
6448 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6449 Prev = FD->getFirstDecl();
6451 Prev = cast<VarDecl>(Prev)->getFirstDecl();
6453 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6455 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6460 /// Apply special rules for handling extern "C" declarations. Returns \c true
6461 /// if we have found that this is a redeclaration of some prior entity.
6463 /// Per C++ [dcl.link]p6:
6464 /// Two declarations [for a function or variable] with C language linkage
6465 /// with the same name that appear in different scopes refer to the same
6466 /// [entity]. An entity with C language linkage shall not be declared with
6467 /// the same name as an entity in global scope.
6468 template<typename T>
6469 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6470 LookupResult &Previous) {
6471 if (!S.getLangOpts().CPlusPlus) {
6472 // In C, when declaring a global variable, look for a corresponding 'extern'
6473 // variable declared in function scope. We don't need this in C++, because
6474 // we find local extern decls in the surrounding file-scope DeclContext.
6475 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6476 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6478 Previous.addDecl(Prev);
6485 // A declaration in the translation unit can conflict with an extern "C"
6487 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6488 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6490 // An extern "C" declaration can conflict with a declaration in the
6491 // translation unit or can be a redeclaration of an extern "C" declaration
6492 // in another scope.
6493 if (isIncompleteDeclExternC(S,ND))
6494 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6496 // Neither global nor extern "C": nothing to do.
6500 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6501 // If the decl is already known invalid, don't check it.
6502 if (NewVD->isInvalidDecl())
6505 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6506 QualType T = TInfo->getType();
6508 // Defer checking an 'auto' type until its initializer is attached.
6509 if (T->isUndeducedType())
6512 if (NewVD->hasAttrs())
6513 CheckAlignasUnderalignment(NewVD);
6515 if (T->isObjCObjectType()) {
6516 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6517 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6518 T = Context.getObjCObjectPointerType(T);
6522 // Emit an error if an address space was applied to decl with local storage.
6523 // This includes arrays of objects with address space qualifiers, but not
6524 // automatic variables that point to other address spaces.
6525 // ISO/IEC TR 18037 S5.1.2
6526 if (!getLangOpts().OpenCL
6527 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6528 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6529 NewVD->setInvalidDecl();
6533 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6535 if (getLangOpts().OpenCLVersion == 120 &&
6536 !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6537 NewVD->isStaticLocal()) {
6538 Diag(NewVD->getLocation(), diag::err_static_function_scope);
6539 NewVD->setInvalidDecl();
6543 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6544 // __constant address space.
6545 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6546 // variables inside a function can also be declared in the global
6548 if (getLangOpts().OpenCL) {
6549 if (NewVD->isFileVarDecl()) {
6550 if (!T->isSamplerT() &&
6551 !(T.getAddressSpace() == LangAS::opencl_constant ||
6552 (T.getAddressSpace() == LangAS::opencl_global &&
6553 getLangOpts().OpenCLVersion == 200))) {
6554 if (getLangOpts().OpenCLVersion == 200)
6555 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6556 << "global or constant";
6558 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6560 NewVD->setInvalidDecl();
6564 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6565 // variables inside a function can also be declared in the global
6567 if (NewVD->isStaticLocal() &&
6568 !(T.getAddressSpace() == LangAS::opencl_constant ||
6569 (T.getAddressSpace() == LangAS::opencl_global &&
6570 getLangOpts().OpenCLVersion == 200))) {
6571 if (getLangOpts().OpenCLVersion == 200)
6572 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6573 << "global or constant";
6575 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6577 NewVD->setInvalidDecl();
6580 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6582 if (T.getAddressSpace() == LangAS::opencl_constant ||
6583 T.getAddressSpace() == LangAS::opencl_local) {
6584 FunctionDecl *FD = getCurFunctionDecl();
6585 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6586 if (T.getAddressSpace() == LangAS::opencl_constant)
6587 Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6590 Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6592 NewVD->setInvalidDecl();
6599 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6600 && !NewVD->hasAttr<BlocksAttr>()) {
6601 if (getLangOpts().getGC() != LangOptions::NonGC)
6602 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6604 assert(!getLangOpts().ObjCAutoRefCount);
6605 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6609 bool isVM = T->isVariablyModifiedType();
6610 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6611 NewVD->hasAttr<BlocksAttr>())
6612 getCurFunction()->setHasBranchProtectedScope();
6614 if ((isVM && NewVD->hasLinkage()) ||
6615 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6616 bool SizeIsNegative;
6617 llvm::APSInt Oversized;
6618 TypeSourceInfo *FixedTInfo =
6619 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6620 SizeIsNegative, Oversized);
6621 if (!FixedTInfo && T->isVariableArrayType()) {
6622 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6623 // FIXME: This won't give the correct result for
6625 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6627 if (NewVD->isFileVarDecl())
6628 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6630 else if (NewVD->isStaticLocal())
6631 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6634 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6636 NewVD->setInvalidDecl();
6641 if (NewVD->isFileVarDecl())
6642 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6644 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6645 NewVD->setInvalidDecl();
6649 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6650 NewVD->setType(FixedTInfo->getType());
6651 NewVD->setTypeSourceInfo(FixedTInfo);
6654 if (T->isVoidType()) {
6655 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6656 // of objects and functions.
6657 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6658 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6660 NewVD->setInvalidDecl();
6665 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6666 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6667 NewVD->setInvalidDecl();
6671 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6672 Diag(NewVD->getLocation(), diag::err_block_on_vm);
6673 NewVD->setInvalidDecl();
6677 if (NewVD->isConstexpr() && !T->isDependentType() &&
6678 RequireLiteralType(NewVD->getLocation(), T,
6679 diag::err_constexpr_var_non_literal)) {
6680 NewVD->setInvalidDecl();
6685 /// \brief Perform semantic checking on a newly-created variable
6688 /// This routine performs all of the type-checking required for a
6689 /// variable declaration once it has been built. It is used both to
6690 /// check variables after they have been parsed and their declarators
6691 /// have been translated into a declaration, and to check variables
6692 /// that have been instantiated from a template.
6694 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6696 /// Returns true if the variable declaration is a redeclaration.
6697 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6698 CheckVariableDeclarationType(NewVD);
6700 // If the decl is already known invalid, don't check it.
6701 if (NewVD->isInvalidDecl())
6704 // If we did not find anything by this name, look for a non-visible
6705 // extern "C" declaration with the same name.
6706 if (Previous.empty() &&
6707 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6708 Previous.setShadowed();
6710 if (!Previous.empty()) {
6711 MergeVarDecl(NewVD, Previous);
6718 struct FindOverriddenMethod {
6720 CXXMethodDecl *Method;
6722 /// Member lookup function that determines whether a given C++
6723 /// method overrides a method in a base class, to be used with
6724 /// CXXRecordDecl::lookupInBases().
6725 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6726 RecordDecl *BaseRecord =
6727 Specifier->getType()->getAs<RecordType>()->getDecl();
6729 DeclarationName Name = Method->getDeclName();
6731 // FIXME: Do we care about other names here too?
6732 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6733 // We really want to find the base class destructor here.
6734 QualType T = S->Context.getTypeDeclType(BaseRecord);
6735 CanQualType CT = S->Context.getCanonicalType(T);
6737 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6740 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6741 Path.Decls = Path.Decls.slice(1)) {
6742 NamedDecl *D = Path.Decls.front();
6743 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6744 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6753 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6754 } // end anonymous namespace
6756 /// \brief Report an error regarding overriding, along with any relevant
6757 /// overriden methods.
6759 /// \param DiagID the primary error to report.
6760 /// \param MD the overriding method.
6761 /// \param OEK which overrides to include as notes.
6762 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6763 OverrideErrorKind OEK = OEK_All) {
6764 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6765 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6766 E = MD->end_overridden_methods();
6768 // This check (& the OEK parameter) could be replaced by a predicate, but
6769 // without lambdas that would be overkill. This is still nicer than writing
6770 // out the diag loop 3 times.
6771 if ((OEK == OEK_All) ||
6772 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6773 (OEK == OEK_Deleted && (*I)->isDeleted()))
6774 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6778 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6779 /// and if so, check that it's a valid override and remember it.
6780 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6781 // Look for methods in base classes that this method might override.
6783 FindOverriddenMethod FOM;
6786 bool hasDeletedOverridenMethods = false;
6787 bool hasNonDeletedOverridenMethods = false;
6788 bool AddedAny = false;
6789 if (DC->lookupInBases(FOM, Paths)) {
6790 for (auto *I : Paths.found_decls()) {
6791 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6792 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6793 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6794 !CheckOverridingFunctionAttributes(MD, OldMD) &&
6795 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6796 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6797 hasDeletedOverridenMethods |= OldMD->isDeleted();
6798 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6805 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6806 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6808 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6809 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6816 // Struct for holding all of the extra arguments needed by
6817 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6818 struct ActOnFDArgs {
6821 MultiTemplateParamsArg TemplateParamLists;
6828 // Callback to only accept typo corrections that have a non-zero edit distance.
6829 // Also only accept corrections that have the same parent decl.
6830 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6832 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6833 CXXRecordDecl *Parent)
6834 : Context(Context), OriginalFD(TypoFD),
6835 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6837 bool ValidateCandidate(const TypoCorrection &candidate) override {
6838 if (candidate.getEditDistance() == 0)
6841 SmallVector<unsigned, 1> MismatchedParams;
6842 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6843 CDeclEnd = candidate.end();
6844 CDecl != CDeclEnd; ++CDecl) {
6845 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6847 if (FD && !FD->hasBody() &&
6848 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6849 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6850 CXXRecordDecl *Parent = MD->getParent();
6851 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6853 } else if (!ExpectedParent) {
6863 ASTContext &Context;
6864 FunctionDecl *OriginalFD;
6865 CXXRecordDecl *ExpectedParent;
6870 /// \brief Generate diagnostics for an invalid function redeclaration.
6872 /// This routine handles generating the diagnostic messages for an invalid
6873 /// function redeclaration, including finding possible similar declarations
6874 /// or performing typo correction if there are no previous declarations with
6877 /// Returns a NamedDecl iff typo correction was performed and substituting in
6878 /// the new declaration name does not cause new errors.
6879 static NamedDecl *DiagnoseInvalidRedeclaration(
6880 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6881 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6882 DeclarationName Name = NewFD->getDeclName();
6883 DeclContext *NewDC = NewFD->getDeclContext();
6884 SmallVector<unsigned, 1> MismatchedParams;
6885 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6886 TypoCorrection Correction;
6887 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6888 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6889 : diag::err_member_decl_does_not_match;
6890 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6891 IsLocalFriend ? Sema::LookupLocalFriendName
6892 : Sema::LookupOrdinaryName,
6893 Sema::ForRedeclaration);
6895 NewFD->setInvalidDecl();
6897 SemaRef.LookupName(Prev, S);
6899 SemaRef.LookupQualifiedName(Prev, NewDC);
6900 assert(!Prev.isAmbiguous() &&
6901 "Cannot have an ambiguity in previous-declaration lookup");
6902 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6903 if (!Prev.empty()) {
6904 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6905 Func != FuncEnd; ++Func) {
6906 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6908 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6909 // Add 1 to the index so that 0 can mean the mismatch didn't
6910 // involve a parameter
6912 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6913 NearMatches.push_back(std::make_pair(FD, ParamNum));
6916 // If the qualified name lookup yielded nothing, try typo correction
6917 } else if ((Correction = SemaRef.CorrectTypo(
6918 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6919 &ExtraArgs.D.getCXXScopeSpec(),
6920 llvm::make_unique<DifferentNameValidatorCCC>(
6921 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6922 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6923 // Set up everything for the call to ActOnFunctionDeclarator
6924 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6925 ExtraArgs.D.getIdentifierLoc());
6927 Previous.setLookupName(Correction.getCorrection());
6928 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6929 CDeclEnd = Correction.end();
6930 CDecl != CDeclEnd; ++CDecl) {
6931 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6932 if (FD && !FD->hasBody() &&
6933 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6934 Previous.addDecl(FD);
6937 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6940 // Retry building the function declaration with the new previous
6941 // declarations, and with errors suppressed.
6944 Sema::SFINAETrap Trap(SemaRef);
6946 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6947 // pieces need to verify the typo-corrected C++ declaration and hopefully
6948 // eliminate the need for the parameter pack ExtraArgs.
6949 Result = SemaRef.ActOnFunctionDeclarator(
6950 ExtraArgs.S, ExtraArgs.D,
6951 Correction.getCorrectionDecl()->getDeclContext(),
6952 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6953 ExtraArgs.AddToScope);
6955 if (Trap.hasErrorOccurred())
6960 // Determine which correction we picked.
6961 Decl *Canonical = Result->getCanonicalDecl();
6962 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6964 if ((*I)->getCanonicalDecl() == Canonical)
6965 Correction.setCorrectionDecl(*I);
6967 SemaRef.diagnoseTypo(
6969 SemaRef.PDiag(IsLocalFriend
6970 ? diag::err_no_matching_local_friend_suggest
6971 : diag::err_member_decl_does_not_match_suggest)
6972 << Name << NewDC << IsDefinition);
6976 // Pretend the typo correction never occurred
6977 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6978 ExtraArgs.D.getIdentifierLoc());
6979 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6981 Previous.setLookupName(Name);
6984 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6985 << Name << NewDC << IsDefinition << NewFD->getLocation();
6987 bool NewFDisConst = false;
6988 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6989 NewFDisConst = NewMD->isConst();
6991 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6992 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6993 NearMatch != NearMatchEnd; ++NearMatch) {
6994 FunctionDecl *FD = NearMatch->first;
6995 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6996 bool FDisConst = MD && MD->isConst();
6997 bool IsMember = MD || !IsLocalFriend;
6999 // FIXME: These notes are poorly worded for the local friend case.
7000 if (unsigned Idx = NearMatch->second) {
7001 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7002 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7003 if (Loc.isInvalid()) Loc = FD->getLocation();
7004 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7005 : diag::note_local_decl_close_param_match)
7006 << Idx << FDParam->getType()
7007 << NewFD->getParamDecl(Idx - 1)->getType();
7008 } else if (FDisConst != NewFDisConst) {
7009 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7010 << NewFDisConst << FD->getSourceRange().getEnd();
7012 SemaRef.Diag(FD->getLocation(),
7013 IsMember ? diag::note_member_def_close_match
7014 : diag::note_local_decl_close_match);
7019 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7020 switch (D.getDeclSpec().getStorageClassSpec()) {
7021 default: llvm_unreachable("Unknown storage class!");
7022 case DeclSpec::SCS_auto:
7023 case DeclSpec::SCS_register:
7024 case DeclSpec::SCS_mutable:
7025 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7026 diag::err_typecheck_sclass_func);
7029 case DeclSpec::SCS_unspecified: break;
7030 case DeclSpec::SCS_extern:
7031 if (D.getDeclSpec().isExternInLinkageSpec())
7034 case DeclSpec::SCS_static: {
7035 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7037 // The declaration of an identifier for a function that has
7038 // block scope shall have no explicit storage-class specifier
7039 // other than extern
7040 // See also (C++ [dcl.stc]p4).
7041 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7042 diag::err_static_block_func);
7047 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7050 // No explicit storage class has already been returned
7054 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7055 DeclContext *DC, QualType &R,
7056 TypeSourceInfo *TInfo,
7058 bool &IsVirtualOkay) {
7059 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7060 DeclarationName Name = NameInfo.getName();
7062 FunctionDecl *NewFD = nullptr;
7063 bool isInline = D.getDeclSpec().isInlineSpecified();
7065 if (!SemaRef.getLangOpts().CPlusPlus) {
7066 // Determine whether the function was written with a
7067 // prototype. This true when:
7068 // - there is a prototype in the declarator, or
7069 // - the type R of the function is some kind of typedef or other reference
7070 // to a type name (which eventually refers to a function type).
7072 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7073 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7075 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7076 D.getLocStart(), NameInfo, R,
7077 TInfo, SC, isInline,
7078 HasPrototype, false);
7079 if (D.isInvalidType())
7080 NewFD->setInvalidDecl();
7085 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7086 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7088 // Check that the return type is not an abstract class type.
7089 // For record types, this is done by the AbstractClassUsageDiagnoser once
7090 // the class has been completely parsed.
7091 if (!DC->isRecord() &&
7092 SemaRef.RequireNonAbstractType(
7093 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7094 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7097 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7098 // This is a C++ constructor declaration.
7099 assert(DC->isRecord() &&
7100 "Constructors can only be declared in a member context");
7102 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7103 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7104 D.getLocStart(), NameInfo,
7105 R, TInfo, isExplicit, isInline,
7106 /*isImplicitlyDeclared=*/false,
7109 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7110 // This is a C++ destructor declaration.
7111 if (DC->isRecord()) {
7112 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7113 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7114 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7115 SemaRef.Context, Record,
7117 NameInfo, R, TInfo, isInline,
7118 /*isImplicitlyDeclared=*/false);
7120 // If the class is complete, then we now create the implicit exception
7121 // specification. If the class is incomplete or dependent, we can't do
7123 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7124 Record->getDefinition() && !Record->isBeingDefined() &&
7125 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7126 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7129 IsVirtualOkay = true;
7133 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7136 // Create a FunctionDecl to satisfy the function definition parsing
7138 return FunctionDecl::Create(SemaRef.Context, DC,
7140 D.getIdentifierLoc(), Name, R, TInfo,
7142 /*hasPrototype=*/true, isConstexpr);
7145 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7146 if (!DC->isRecord()) {
7147 SemaRef.Diag(D.getIdentifierLoc(),
7148 diag::err_conv_function_not_member);
7152 SemaRef.CheckConversionDeclarator(D, R, SC);
7153 IsVirtualOkay = true;
7154 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7155 D.getLocStart(), NameInfo,
7156 R, TInfo, isInline, isExplicit,
7157 isConstexpr, SourceLocation());
7159 } else if (DC->isRecord()) {
7160 // If the name of the function is the same as the name of the record,
7161 // then this must be an invalid constructor that has a return type.
7162 // (The parser checks for a return type and makes the declarator a
7163 // constructor if it has no return type).
7164 if (Name.getAsIdentifierInfo() &&
7165 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7166 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7167 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7168 << SourceRange(D.getIdentifierLoc());
7172 // This is a C++ method declaration.
7173 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7174 cast<CXXRecordDecl>(DC),
7175 D.getLocStart(), NameInfo, R,
7176 TInfo, SC, isInline,
7177 isConstexpr, SourceLocation());
7178 IsVirtualOkay = !Ret->isStatic();
7182 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7183 if (!isFriend && SemaRef.CurContext->isRecord())
7186 // Determine whether the function was written with a
7187 // prototype. This true when:
7188 // - we're in C++ (where every function has a prototype),
7189 return FunctionDecl::Create(SemaRef.Context, DC,
7191 NameInfo, R, TInfo, SC, isInline,
7192 true/*HasPrototype*/, isConstexpr);
7196 enum OpenCLParamType {
7200 PrivatePtrKernelParam,
7205 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7206 if (PT->isPointerType()) {
7207 QualType PointeeType = PT->getPointeeType();
7208 if (PointeeType->isPointerType())
7209 return PtrPtrKernelParam;
7210 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7214 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7215 // be used as builtin types.
7217 if (PT->isImageType())
7218 return PtrKernelParam;
7220 if (PT->isBooleanType())
7221 return InvalidKernelParam;
7224 return InvalidKernelParam;
7226 if (PT->isHalfType())
7227 return InvalidKernelParam;
7229 if (PT->isRecordType())
7230 return RecordKernelParam;
7232 return ValidKernelParam;
7235 static void checkIsValidOpenCLKernelParameter(
7239 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7240 QualType PT = Param->getType();
7242 // Cache the valid types we encounter to avoid rechecking structs that are
7244 if (ValidTypes.count(PT.getTypePtr()))
7247 switch (getOpenCLKernelParameterType(PT)) {
7248 case PtrPtrKernelParam:
7249 // OpenCL v1.2 s6.9.a:
7250 // A kernel function argument cannot be declared as a
7251 // pointer to a pointer type.
7252 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7256 case PrivatePtrKernelParam:
7257 // OpenCL v1.2 s6.9.a:
7258 // A kernel function argument cannot be declared as a
7259 // pointer to the private address space.
7260 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7264 // OpenCL v1.2 s6.9.k:
7265 // Arguments to kernel functions in a program cannot be declared with the
7266 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7267 // uintptr_t or a struct and/or union that contain fields declared to be
7268 // one of these built-in scalar types.
7270 case InvalidKernelParam:
7271 // OpenCL v1.2 s6.8 n:
7272 // A kernel function argument cannot be declared
7274 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7278 case PtrKernelParam:
7279 case ValidKernelParam:
7280 ValidTypes.insert(PT.getTypePtr());
7283 case RecordKernelParam:
7287 // Track nested structs we will inspect
7288 SmallVector<const Decl *, 4> VisitStack;
7290 // Track where we are in the nested structs. Items will migrate from
7291 // VisitStack to HistoryStack as we do the DFS for bad field.
7292 SmallVector<const FieldDecl *, 4> HistoryStack;
7293 HistoryStack.push_back(nullptr);
7295 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7296 VisitStack.push_back(PD);
7298 assert(VisitStack.back() && "First decl null?");
7301 const Decl *Next = VisitStack.pop_back_val();
7303 assert(!HistoryStack.empty());
7304 // Found a marker, we have gone up a level
7305 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7306 ValidTypes.insert(Hist->getType().getTypePtr());
7311 // Adds everything except the original parameter declaration (which is not a
7312 // field itself) to the history stack.
7313 const RecordDecl *RD;
7314 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7315 HistoryStack.push_back(Field);
7316 RD = Field->getType()->castAs<RecordType>()->getDecl();
7318 RD = cast<RecordDecl>(Next);
7321 // Add a null marker so we know when we've gone back up a level
7322 VisitStack.push_back(nullptr);
7324 for (const auto *FD : RD->fields()) {
7325 QualType QT = FD->getType();
7327 if (ValidTypes.count(QT.getTypePtr()))
7330 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7331 if (ParamType == ValidKernelParam)
7334 if (ParamType == RecordKernelParam) {
7335 VisitStack.push_back(FD);
7339 // OpenCL v1.2 s6.9.p:
7340 // Arguments to kernel functions that are declared to be a struct or union
7341 // do not allow OpenCL objects to be passed as elements of the struct or
7343 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7344 ParamType == PrivatePtrKernelParam) {
7345 S.Diag(Param->getLocation(),
7346 diag::err_record_with_pointers_kernel_param)
7347 << PT->isUnionType()
7350 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7353 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7354 << PD->getDeclName();
7356 // We have an error, now let's go back up through history and show where
7357 // the offending field came from
7358 for (ArrayRef<const FieldDecl *>::const_iterator
7359 I = HistoryStack.begin() + 1,
7360 E = HistoryStack.end();
7362 const FieldDecl *OuterField = *I;
7363 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7364 << OuterField->getType();
7367 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7368 << QT->isPointerType()
7373 } while (!VisitStack.empty());
7377 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7378 TypeSourceInfo *TInfo, LookupResult &Previous,
7379 MultiTemplateParamsArg TemplateParamLists,
7381 QualType R = TInfo->getType();
7383 assert(R.getTypePtr()->isFunctionType());
7385 // TODO: consider using NameInfo for diagnostic.
7386 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7387 DeclarationName Name = NameInfo.getName();
7388 StorageClass SC = getFunctionStorageClass(*this, D);
7390 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7391 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7392 diag::err_invalid_thread)
7393 << DeclSpec::getSpecifierName(TSCS);
7395 if (D.isFirstDeclarationOfMember())
7396 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7397 D.getIdentifierLoc());
7399 bool isFriend = false;
7400 FunctionTemplateDecl *FunctionTemplate = nullptr;
7401 bool isExplicitSpecialization = false;
7402 bool isFunctionTemplateSpecialization = false;
7404 bool isDependentClassScopeExplicitSpecialization = false;
7405 bool HasExplicitTemplateArgs = false;
7406 TemplateArgumentListInfo TemplateArgs;
7408 bool isVirtualOkay = false;
7410 DeclContext *OriginalDC = DC;
7411 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7413 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7415 if (!NewFD) return nullptr;
7417 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7418 NewFD->setTopLevelDeclInObjCContainer();
7420 // Set the lexical context. If this is a function-scope declaration, or has a
7421 // C++ scope specifier, or is the object of a friend declaration, the lexical
7422 // context will be different from the semantic context.
7423 NewFD->setLexicalDeclContext(CurContext);
7425 if (IsLocalExternDecl)
7426 NewFD->setLocalExternDecl();
7428 if (getLangOpts().CPlusPlus) {
7429 bool isInline = D.getDeclSpec().isInlineSpecified();
7430 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7431 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7432 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7433 bool isConcept = D.getDeclSpec().isConceptSpecified();
7434 isFriend = D.getDeclSpec().isFriendSpecified();
7435 if (isFriend && !isInline && D.isFunctionDefinition()) {
7436 // C++ [class.friend]p5
7437 // A function can be defined in a friend declaration of a
7438 // class . . . . Such a function is implicitly inline.
7439 NewFD->setImplicitlyInline();
7442 // If this is a method defined in an __interface, and is not a constructor
7443 // or an overloaded operator, then set the pure flag (isVirtual will already
7445 if (const CXXRecordDecl *Parent =
7446 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7447 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7448 NewFD->setPure(true);
7450 // C++ [class.union]p2
7451 // A union can have member functions, but not virtual functions.
7452 if (isVirtual && Parent->isUnion())
7453 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7456 SetNestedNameSpecifier(NewFD, D);
7457 isExplicitSpecialization = false;
7458 isFunctionTemplateSpecialization = false;
7459 if (D.isInvalidType())
7460 NewFD->setInvalidDecl();
7462 // Match up the template parameter lists with the scope specifier, then
7463 // determine whether we have a template or a template specialization.
7464 bool Invalid = false;
7465 if (TemplateParameterList *TemplateParams =
7466 MatchTemplateParametersToScopeSpecifier(
7467 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7468 D.getCXXScopeSpec(),
7469 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7470 ? D.getName().TemplateId
7472 TemplateParamLists, isFriend, isExplicitSpecialization,
7474 if (TemplateParams->size() > 0) {
7475 // This is a function template
7477 // Check that we can declare a template here.
7478 if (CheckTemplateDeclScope(S, TemplateParams))
7479 NewFD->setInvalidDecl();
7481 // A destructor cannot be a template.
7482 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7483 Diag(NewFD->getLocation(), diag::err_destructor_template);
7484 NewFD->setInvalidDecl();
7487 // If we're adding a template to a dependent context, we may need to
7488 // rebuilding some of the types used within the template parameter list,
7489 // now that we know what the current instantiation is.
7490 if (DC->isDependentContext()) {
7491 ContextRAII SavedContext(*this, DC);
7492 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7497 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7498 NewFD->getLocation(),
7499 Name, TemplateParams,
7501 FunctionTemplate->setLexicalDeclContext(CurContext);
7502 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7504 // For source fidelity, store the other template param lists.
7505 if (TemplateParamLists.size() > 1) {
7506 NewFD->setTemplateParameterListsInfo(Context,
7507 TemplateParamLists.drop_back(1));
7510 // This is a function template specialization.
7511 isFunctionTemplateSpecialization = true;
7512 // For source fidelity, store all the template param lists.
7513 if (TemplateParamLists.size() > 0)
7514 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7516 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7518 // We want to remove the "template<>", found here.
7519 SourceRange RemoveRange = TemplateParams->getSourceRange();
7521 // If we remove the template<> and the name is not a
7522 // template-id, we're actually silently creating a problem:
7523 // the friend declaration will refer to an untemplated decl,
7524 // and clearly the user wants a template specialization. So
7525 // we need to insert '<>' after the name.
7526 SourceLocation InsertLoc;
7527 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7528 InsertLoc = D.getName().getSourceRange().getEnd();
7529 InsertLoc = getLocForEndOfToken(InsertLoc);
7532 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7533 << Name << RemoveRange
7534 << FixItHint::CreateRemoval(RemoveRange)
7535 << FixItHint::CreateInsertion(InsertLoc, "<>");
7540 // All template param lists were matched against the scope specifier:
7541 // this is NOT (an explicit specialization of) a template.
7542 if (TemplateParamLists.size() > 0)
7543 // For source fidelity, store all the template param lists.
7544 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7548 NewFD->setInvalidDecl();
7549 if (FunctionTemplate)
7550 FunctionTemplate->setInvalidDecl();
7553 // C++ [dcl.fct.spec]p5:
7554 // The virtual specifier shall only be used in declarations of
7555 // nonstatic class member functions that appear within a
7556 // member-specification of a class declaration; see 10.3.
7558 if (isVirtual && !NewFD->isInvalidDecl()) {
7559 if (!isVirtualOkay) {
7560 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7561 diag::err_virtual_non_function);
7562 } else if (!CurContext->isRecord()) {
7563 // 'virtual' was specified outside of the class.
7564 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7565 diag::err_virtual_out_of_class)
7566 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7567 } else if (NewFD->getDescribedFunctionTemplate()) {
7568 // C++ [temp.mem]p3:
7569 // A member function template shall not be virtual.
7570 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7571 diag::err_virtual_member_function_template)
7572 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7574 // Okay: Add virtual to the method.
7575 NewFD->setVirtualAsWritten(true);
7578 if (getLangOpts().CPlusPlus14 &&
7579 NewFD->getReturnType()->isUndeducedType())
7580 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7583 if (getLangOpts().CPlusPlus14 &&
7584 (NewFD->isDependentContext() ||
7585 (isFriend && CurContext->isDependentContext())) &&
7586 NewFD->getReturnType()->isUndeducedType()) {
7587 // If the function template is referenced directly (for instance, as a
7588 // member of the current instantiation), pretend it has a dependent type.
7589 // This is not really justified by the standard, but is the only sane
7591 // FIXME: For a friend function, we have not marked the function as being
7592 // a friend yet, so 'isDependentContext' on the FD doesn't work.
7593 const FunctionProtoType *FPT =
7594 NewFD->getType()->castAs<FunctionProtoType>();
7596 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7597 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7598 FPT->getExtProtoInfo()));
7601 // C++ [dcl.fct.spec]p3:
7602 // The inline specifier shall not appear on a block scope function
7604 if (isInline && !NewFD->isInvalidDecl()) {
7605 if (CurContext->isFunctionOrMethod()) {
7606 // 'inline' is not allowed on block scope function declaration.
7607 Diag(D.getDeclSpec().getInlineSpecLoc(),
7608 diag::err_inline_declaration_block_scope) << Name
7609 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7613 // C++ [dcl.fct.spec]p6:
7614 // The explicit specifier shall be used only in the declaration of a
7615 // constructor or conversion function within its class definition;
7616 // see 12.3.1 and 12.3.2.
7617 if (isExplicit && !NewFD->isInvalidDecl()) {
7618 if (!CurContext->isRecord()) {
7619 // 'explicit' was specified outside of the class.
7620 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7621 diag::err_explicit_out_of_class)
7622 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7623 } else if (!isa<CXXConstructorDecl>(NewFD) &&
7624 !isa<CXXConversionDecl>(NewFD)) {
7625 // 'explicit' was specified on a function that wasn't a constructor
7626 // or conversion function.
7627 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7628 diag::err_explicit_non_ctor_or_conv_function)
7629 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7634 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7635 // are implicitly inline.
7636 NewFD->setImplicitlyInline();
7638 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7639 // be either constructors or to return a literal type. Therefore,
7640 // destructors cannot be declared constexpr.
7641 if (isa<CXXDestructorDecl>(NewFD))
7642 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7646 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7647 // applied only to the definition of a function template [...]
7648 if (!D.isFunctionDefinition()) {
7649 Diag(D.getDeclSpec().getConceptSpecLoc(),
7650 diag::err_function_concept_not_defined);
7651 NewFD->setInvalidDecl();
7654 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7655 // have no exception-specification and is treated as if it were specified
7656 // with noexcept(true) (15.4). [...]
7657 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7658 if (FPT->hasExceptionSpec()) {
7660 if (D.isFunctionDeclarator())
7661 Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7662 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7663 << FixItHint::CreateRemoval(Range);
7664 NewFD->setInvalidDecl();
7666 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7669 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7670 // following restrictions:
7671 // - The declaration's parameter list shall be equivalent to an empty
7673 if (FPT->getNumParams() > 0 || FPT->isVariadic())
7674 Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7677 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7678 // implicity defined to be a constexpr declaration (implicitly inline)
7679 NewFD->setImplicitlyInline();
7681 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7682 // be declared with the thread_local, inline, friend, or constexpr
7683 // specifiers, [...]
7685 Diag(D.getDeclSpec().getInlineSpecLoc(),
7686 diag::err_concept_decl_invalid_specifiers)
7688 NewFD->setInvalidDecl(true);
7692 Diag(D.getDeclSpec().getFriendSpecLoc(),
7693 diag::err_concept_decl_invalid_specifiers)
7695 NewFD->setInvalidDecl(true);
7699 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7700 diag::err_concept_decl_invalid_specifiers)
7702 NewFD->setInvalidDecl(true);
7706 // If __module_private__ was specified, mark the function accordingly.
7707 if (D.getDeclSpec().isModulePrivateSpecified()) {
7708 if (isFunctionTemplateSpecialization) {
7709 SourceLocation ModulePrivateLoc
7710 = D.getDeclSpec().getModulePrivateSpecLoc();
7711 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7713 << FixItHint::CreateRemoval(ModulePrivateLoc);
7715 NewFD->setModulePrivate();
7716 if (FunctionTemplate)
7717 FunctionTemplate->setModulePrivate();
7722 if (FunctionTemplate) {
7723 FunctionTemplate->setObjectOfFriendDecl();
7724 FunctionTemplate->setAccess(AS_public);
7726 NewFD->setObjectOfFriendDecl();
7727 NewFD->setAccess(AS_public);
7730 // If a function is defined as defaulted or deleted, mark it as such now.
7731 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7732 // definition kind to FDK_Definition.
7733 switch (D.getFunctionDefinitionKind()) {
7734 case FDK_Declaration:
7735 case FDK_Definition:
7739 NewFD->setDefaulted();
7743 NewFD->setDeletedAsWritten();
7747 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7748 D.isFunctionDefinition()) {
7749 // C++ [class.mfct]p2:
7750 // A member function may be defined (8.4) in its class definition, in
7751 // which case it is an inline member function (7.1.2)
7752 NewFD->setImplicitlyInline();
7755 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7756 !CurContext->isRecord()) {
7757 // C++ [class.static]p1:
7758 // A data or function member of a class may be declared static
7759 // in a class definition, in which case it is a static member of
7762 // Complain about the 'static' specifier if it's on an out-of-line
7763 // member function definition.
7764 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7765 diag::err_static_out_of_line)
7766 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7769 // C++11 [except.spec]p15:
7770 // A deallocation function with no exception-specification is treated
7771 // as if it were specified with noexcept(true).
7772 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7773 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7774 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7775 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7776 NewFD->setType(Context.getFunctionType(
7777 FPT->getReturnType(), FPT->getParamTypes(),
7778 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7781 // Filter out previous declarations that don't match the scope.
7782 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7783 D.getCXXScopeSpec().isNotEmpty() ||
7784 isExplicitSpecialization ||
7785 isFunctionTemplateSpecialization);
7787 // Handle GNU asm-label extension (encoded as an attribute).
7788 if (Expr *E = (Expr*) D.getAsmLabel()) {
7789 // The parser guarantees this is a string.
7790 StringLiteral *SE = cast<StringLiteral>(E);
7791 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7792 SE->getString(), 0));
7793 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7794 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7795 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7796 if (I != ExtnameUndeclaredIdentifiers.end()) {
7797 if (isDeclExternC(NewFD)) {
7798 NewFD->addAttr(I->second);
7799 ExtnameUndeclaredIdentifiers.erase(I);
7801 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7802 << /*Variable*/0 << NewFD;
7806 // Copy the parameter declarations from the declarator D to the function
7807 // declaration NewFD, if they are available. First scavenge them into Params.
7808 SmallVector<ParmVarDecl*, 16> Params;
7809 if (D.isFunctionDeclarator()) {
7810 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7812 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7813 // function that takes no arguments, not a function that takes a
7814 // single void argument.
7815 // We let through "const void" here because Sema::GetTypeForDeclarator
7816 // already checks for that case.
7817 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7818 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7819 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7820 assert(Param->getDeclContext() != NewFD && "Was set before ?");
7821 Param->setDeclContext(NewFD);
7822 Params.push_back(Param);
7824 if (Param->isInvalidDecl())
7825 NewFD->setInvalidDecl();
7829 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7830 // When we're declaring a function with a typedef, typeof, etc as in the
7831 // following example, we'll need to synthesize (unnamed)
7832 // parameters for use in the declaration.
7835 // typedef void fn(int);
7839 // Synthesize a parameter for each argument type.
7840 for (const auto &AI : FT->param_types()) {
7841 ParmVarDecl *Param =
7842 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7843 Param->setScopeInfo(0, Params.size());
7844 Params.push_back(Param);
7847 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7848 "Should not need args for typedef of non-prototype fn");
7851 // Finally, we know we have the right number of parameters, install them.
7852 NewFD->setParams(Params);
7854 // Find all anonymous symbols defined during the declaration of this function
7855 // and add to NewFD. This lets us track decls such 'enum Y' in:
7857 // void f(enum Y {AA} x) {}
7859 // which would otherwise incorrectly end up in the translation unit scope.
7860 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7861 DeclsInPrototypeScope.clear();
7863 if (D.getDeclSpec().isNoreturnSpecified())
7865 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7868 // Functions returning a variably modified type violate C99 6.7.5.2p2
7869 // because all functions have linkage.
7870 if (!NewFD->isInvalidDecl() &&
7871 NewFD->getReturnType()->isVariablyModifiedType()) {
7872 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7873 NewFD->setInvalidDecl();
7876 // Apply an implicit SectionAttr if #pragma code_seg is active.
7877 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7878 !NewFD->hasAttr<SectionAttr>()) {
7880 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7881 CodeSegStack.CurrentValue->getString(),
7882 CodeSegStack.CurrentPragmaLocation));
7883 if (UnifySection(CodeSegStack.CurrentValue->getString(),
7884 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7885 ASTContext::PSF_Read,
7887 NewFD->dropAttr<SectionAttr>();
7890 // Handle attributes.
7891 ProcessDeclAttributes(S, NewFD, D);
7893 if (getLangOpts().OpenCL) {
7894 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7895 // type declaration will generate a compilation error.
7896 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
7897 if (AddressSpace == LangAS::opencl_local ||
7898 AddressSpace == LangAS::opencl_global ||
7899 AddressSpace == LangAS::opencl_constant) {
7900 Diag(NewFD->getLocation(),
7901 diag::err_opencl_return_value_with_address_space);
7902 NewFD->setInvalidDecl();
7906 if (!getLangOpts().CPlusPlus) {
7907 // Perform semantic checking on the function declaration.
7908 bool isExplicitSpecialization=false;
7909 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7910 CheckMain(NewFD, D.getDeclSpec());
7912 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7913 CheckMSVCRTEntryPoint(NewFD);
7915 if (!NewFD->isInvalidDecl())
7916 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7917 isExplicitSpecialization));
7918 else if (!Previous.empty())
7919 // Recover gracefully from an invalid redeclaration.
7920 D.setRedeclaration(true);
7921 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7922 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7923 "previous declaration set still overloaded");
7925 // Diagnose no-prototype function declarations with calling conventions that
7926 // don't support variadic calls. Only do this in C and do it after merging
7927 // possibly prototyped redeclarations.
7928 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7929 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7930 CallingConv CC = FT->getExtInfo().getCC();
7931 if (!supportsVariadicCall(CC)) {
7932 // Windows system headers sometimes accidentally use stdcall without
7933 // (void) parameters, so we relax this to a warning.
7935 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7936 Diag(NewFD->getLocation(), DiagID)
7937 << FunctionType::getNameForCallConv(CC);
7941 // C++11 [replacement.functions]p3:
7942 // The program's definitions shall not be specified as inline.
7944 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7946 // Suppress the diagnostic if the function is __attribute__((used)), since
7947 // that forces an external definition to be emitted.
7948 if (D.getDeclSpec().isInlineSpecified() &&
7949 NewFD->isReplaceableGlobalAllocationFunction() &&
7950 !NewFD->hasAttr<UsedAttr>())
7951 Diag(D.getDeclSpec().getInlineSpecLoc(),
7952 diag::ext_operator_new_delete_declared_inline)
7953 << NewFD->getDeclName();
7955 // If the declarator is a template-id, translate the parser's template
7956 // argument list into our AST format.
7957 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7958 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7959 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7960 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7961 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7962 TemplateId->NumArgs);
7963 translateTemplateArguments(TemplateArgsPtr,
7966 HasExplicitTemplateArgs = true;
7968 if (NewFD->isInvalidDecl()) {
7969 HasExplicitTemplateArgs = false;
7970 } else if (FunctionTemplate) {
7971 // Function template with explicit template arguments.
7972 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7973 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7975 HasExplicitTemplateArgs = false;
7977 assert((isFunctionTemplateSpecialization ||
7978 D.getDeclSpec().isFriendSpecified()) &&
7979 "should have a 'template<>' for this decl");
7980 // "friend void foo<>(int);" is an implicit specialization decl.
7981 isFunctionTemplateSpecialization = true;
7983 } else if (isFriend && isFunctionTemplateSpecialization) {
7984 // This combination is only possible in a recovery case; the user
7985 // wrote something like:
7986 // template <> friend void foo(int);
7987 // which we're recovering from as if the user had written:
7988 // friend void foo<>(int);
7989 // Go ahead and fake up a template id.
7990 HasExplicitTemplateArgs = true;
7991 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7992 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7995 // If it's a friend (and only if it's a friend), it's possible
7996 // that either the specialized function type or the specialized
7997 // template is dependent, and therefore matching will fail. In
7998 // this case, don't check the specialization yet.
7999 bool InstantiationDependent = false;
8000 if (isFunctionTemplateSpecialization && isFriend &&
8001 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8002 TemplateSpecializationType::anyDependentTemplateArguments(
8003 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8004 InstantiationDependent))) {
8005 assert(HasExplicitTemplateArgs &&
8006 "friend function specialization without template args");
8007 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8009 NewFD->setInvalidDecl();
8010 } else if (isFunctionTemplateSpecialization) {
8011 if (CurContext->isDependentContext() && CurContext->isRecord()
8013 isDependentClassScopeExplicitSpecialization = true;
8014 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8015 diag::ext_function_specialization_in_class :
8016 diag::err_function_specialization_in_class)
8017 << NewFD->getDeclName();
8018 } else if (CheckFunctionTemplateSpecialization(NewFD,
8019 (HasExplicitTemplateArgs ? &TemplateArgs
8022 NewFD->setInvalidDecl();
8025 // A storage-class-specifier shall not be specified in an explicit
8026 // specialization (14.7.3)
8027 FunctionTemplateSpecializationInfo *Info =
8028 NewFD->getTemplateSpecializationInfo();
8029 if (Info && SC != SC_None) {
8030 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8031 Diag(NewFD->getLocation(),
8032 diag::err_explicit_specialization_inconsistent_storage_class)
8034 << FixItHint::CreateRemoval(
8035 D.getDeclSpec().getStorageClassSpecLoc());
8038 Diag(NewFD->getLocation(),
8039 diag::ext_explicit_specialization_storage_class)
8040 << FixItHint::CreateRemoval(
8041 D.getDeclSpec().getStorageClassSpecLoc());
8044 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8045 if (CheckMemberSpecialization(NewFD, Previous))
8046 NewFD->setInvalidDecl();
8049 // Perform semantic checking on the function declaration.
8050 if (!isDependentClassScopeExplicitSpecialization) {
8051 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8052 CheckMain(NewFD, D.getDeclSpec());
8054 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8055 CheckMSVCRTEntryPoint(NewFD);
8057 if (!NewFD->isInvalidDecl())
8058 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8059 isExplicitSpecialization));
8060 else if (!Previous.empty())
8061 // Recover gracefully from an invalid redeclaration.
8062 D.setRedeclaration(true);
8065 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8066 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8067 "previous declaration set still overloaded");
8069 NamedDecl *PrincipalDecl = (FunctionTemplate
8070 ? cast<NamedDecl>(FunctionTemplate)
8073 if (isFriend && D.isRedeclaration()) {
8074 AccessSpecifier Access = AS_public;
8075 if (!NewFD->isInvalidDecl())
8076 Access = NewFD->getPreviousDecl()->getAccess();
8078 NewFD->setAccess(Access);
8079 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8082 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8083 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8084 PrincipalDecl->setNonMemberOperator();
8086 // If we have a function template, check the template parameter
8087 // list. This will check and merge default template arguments.
8088 if (FunctionTemplate) {
8089 FunctionTemplateDecl *PrevTemplate =
8090 FunctionTemplate->getPreviousDecl();
8091 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8092 PrevTemplate ? PrevTemplate->getTemplateParameters()
8094 D.getDeclSpec().isFriendSpecified()
8095 ? (D.isFunctionDefinition()
8096 ? TPC_FriendFunctionTemplateDefinition
8097 : TPC_FriendFunctionTemplate)
8098 : (D.getCXXScopeSpec().isSet() &&
8099 DC && DC->isRecord() &&
8100 DC->isDependentContext())
8101 ? TPC_ClassTemplateMember
8102 : TPC_FunctionTemplate);
8105 if (NewFD->isInvalidDecl()) {
8106 // Ignore all the rest of this.
8107 } else if (!D.isRedeclaration()) {
8108 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8110 // Fake up an access specifier if it's supposed to be a class member.
8111 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8112 NewFD->setAccess(AS_public);
8114 // Qualified decls generally require a previous declaration.
8115 if (D.getCXXScopeSpec().isSet()) {
8116 // ...with the major exception of templated-scope or
8117 // dependent-scope friend declarations.
8119 // TODO: we currently also suppress this check in dependent
8120 // contexts because (1) the parameter depth will be off when
8121 // matching friend templates and (2) we might actually be
8122 // selecting a friend based on a dependent factor. But there
8123 // are situations where these conditions don't apply and we
8124 // can actually do this check immediately.
8126 (TemplateParamLists.size() ||
8127 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8128 CurContext->isDependentContext())) {
8131 // The user tried to provide an out-of-line definition for a
8132 // function that is a member of a class or namespace, but there
8133 // was no such member function declared (C++ [class.mfct]p2,
8134 // C++ [namespace.memdef]p2). For example:
8140 // void X::f() { } // ill-formed
8142 // Complain about this problem, and attempt to suggest close
8143 // matches (e.g., those that differ only in cv-qualifiers and
8144 // whether the parameter types are references).
8146 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8147 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8148 AddToScope = ExtraArgs.AddToScope;
8153 // Unqualified local friend declarations are required to resolve
8155 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8156 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8157 *this, Previous, NewFD, ExtraArgs, true, S)) {
8158 AddToScope = ExtraArgs.AddToScope;
8163 } else if (!D.isFunctionDefinition() &&
8164 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8165 !isFriend && !isFunctionTemplateSpecialization &&
8166 !isExplicitSpecialization) {
8167 // An out-of-line member function declaration must also be a
8168 // definition (C++ [class.mfct]p2).
8169 // Note that this is not the case for explicit specializations of
8170 // function templates or member functions of class templates, per
8171 // C++ [temp.expl.spec]p2. We also allow these declarations as an
8172 // extension for compatibility with old SWIG code which likes to
8174 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8175 << D.getCXXScopeSpec().getRange();
8179 ProcessPragmaWeak(S, NewFD);
8180 checkAttributesAfterMerging(*this, *NewFD);
8182 AddKnownFunctionAttributes(NewFD);
8184 if (NewFD->hasAttr<OverloadableAttr>() &&
8185 !NewFD->getType()->getAs<FunctionProtoType>()) {
8186 Diag(NewFD->getLocation(),
8187 diag::err_attribute_overloadable_no_prototype)
8190 // Turn this into a variadic function with no parameters.
8191 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8192 FunctionProtoType::ExtProtoInfo EPI(
8193 Context.getDefaultCallingConvention(true, false));
8194 EPI.Variadic = true;
8195 EPI.ExtInfo = FT->getExtInfo();
8197 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8201 // If there's a #pragma GCC visibility in scope, and this isn't a class
8202 // member, set the visibility of this function.
8203 if (!DC->isRecord() && NewFD->isExternallyVisible())
8204 AddPushedVisibilityAttribute(NewFD);
8206 // If there's a #pragma clang arc_cf_code_audited in scope, consider
8207 // marking the function.
8208 AddCFAuditedAttribute(NewFD);
8210 // If this is a function definition, check if we have to apply optnone due to
8212 if(D.isFunctionDefinition())
8213 AddRangeBasedOptnone(NewFD);
8215 // If this is the first declaration of an extern C variable, update
8216 // the map of such variables.
8217 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8218 isIncompleteDeclExternC(*this, NewFD))
8219 RegisterLocallyScopedExternCDecl(NewFD, S);
8221 // Set this FunctionDecl's range up to the right paren.
8222 NewFD->setRangeEnd(D.getSourceRange().getEnd());
8224 if (D.isRedeclaration() && !Previous.empty()) {
8225 checkDLLAttributeRedeclaration(
8226 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8227 isExplicitSpecialization || isFunctionTemplateSpecialization);
8230 if (getLangOpts().CPlusPlus) {
8231 if (FunctionTemplate) {
8232 if (NewFD->isInvalidDecl())
8233 FunctionTemplate->setInvalidDecl();
8234 return FunctionTemplate;
8238 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8239 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8240 if ((getLangOpts().OpenCLVersion >= 120)
8241 && (SC == SC_Static)) {
8242 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8246 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8247 if (!NewFD->getReturnType()->isVoidType()) {
8248 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8249 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8250 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8255 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8256 for (auto Param : NewFD->params())
8257 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8259 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
8260 PE = NewFD->param_end(); PI != PE; ++PI) {
8261 ParmVarDecl *Param = *PI;
8262 QualType PT = Param->getType();
8264 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8266 if (getLangOpts().OpenCLVersion >= 200) {
8267 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8268 QualType ElemTy = PipeTy->getElementType();
8269 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8270 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8277 MarkUnusedFileScopedDecl(NewFD);
8279 if (getLangOpts().CUDA)
8280 if (IdentifierInfo *II = NewFD->getIdentifier())
8281 if (!NewFD->isInvalidDecl() &&
8282 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8283 if (II->isStr("cudaConfigureCall")) {
8284 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8285 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8287 Context.setcudaConfigureCallDecl(NewFD);
8291 // Here we have an function template explicit specialization at class scope.
8292 // The actually specialization will be postponed to template instatiation
8293 // time via the ClassScopeFunctionSpecializationDecl node.
8294 if (isDependentClassScopeExplicitSpecialization) {
8295 ClassScopeFunctionSpecializationDecl *NewSpec =
8296 ClassScopeFunctionSpecializationDecl::Create(
8297 Context, CurContext, SourceLocation(),
8298 cast<CXXMethodDecl>(NewFD),
8299 HasExplicitTemplateArgs, TemplateArgs);
8300 CurContext->addDecl(NewSpec);
8307 /// \brief Perform semantic checking of a new function declaration.
8309 /// Performs semantic analysis of the new function declaration
8310 /// NewFD. This routine performs all semantic checking that does not
8311 /// require the actual declarator involved in the declaration, and is
8312 /// used both for the declaration of functions as they are parsed
8313 /// (called via ActOnDeclarator) and for the declaration of functions
8314 /// that have been instantiated via C++ template instantiation (called
8315 /// via InstantiateDecl).
8317 /// \param IsExplicitSpecialization whether this new function declaration is
8318 /// an explicit specialization of the previous declaration.
8320 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8322 /// \returns true if the function declaration is a redeclaration.
8323 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8324 LookupResult &Previous,
8325 bool IsExplicitSpecialization) {
8326 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8327 "Variably modified return types are not handled here");
8329 // Determine whether the type of this function should be merged with
8330 // a previous visible declaration. This never happens for functions in C++,
8331 // and always happens in C if the previous declaration was visible.
8332 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8333 !Previous.isShadowed();
8335 bool Redeclaration = false;
8336 NamedDecl *OldDecl = nullptr;
8338 // Merge or overload the declaration with an existing declaration of
8339 // the same name, if appropriate.
8340 if (!Previous.empty()) {
8341 // Determine whether NewFD is an overload of PrevDecl or
8342 // a declaration that requires merging. If it's an overload,
8343 // there's no more work to do here; we'll just add the new
8344 // function to the scope.
8345 if (!AllowOverloadingOfFunction(Previous, Context)) {
8346 NamedDecl *Candidate = Previous.getRepresentativeDecl();
8347 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8348 Redeclaration = true;
8349 OldDecl = Candidate;
8352 switch (CheckOverload(S, NewFD, Previous, OldDecl,
8353 /*NewIsUsingDecl*/ false)) {
8355 Redeclaration = true;
8358 case Ovl_NonFunction:
8359 Redeclaration = true;
8363 Redeclaration = false;
8367 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8368 // If a function name is overloadable in C, then every function
8369 // with that name must be marked "overloadable".
8370 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8371 << Redeclaration << NewFD;
8372 NamedDecl *OverloadedDecl = nullptr;
8374 OverloadedDecl = OldDecl;
8375 else if (!Previous.empty())
8376 OverloadedDecl = Previous.getRepresentativeDecl();
8378 Diag(OverloadedDecl->getLocation(),
8379 diag::note_attribute_overloadable_prev_overload);
8380 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8385 // Check for a previous extern "C" declaration with this name.
8386 if (!Redeclaration &&
8387 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8388 if (!Previous.empty()) {
8389 // This is an extern "C" declaration with the same name as a previous
8390 // declaration, and thus redeclares that entity...
8391 Redeclaration = true;
8392 OldDecl = Previous.getFoundDecl();
8393 MergeTypeWithPrevious = false;
8395 // ... except in the presence of __attribute__((overloadable)).
8396 if (OldDecl->hasAttr<OverloadableAttr>()) {
8397 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8398 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8399 << Redeclaration << NewFD;
8400 Diag(Previous.getFoundDecl()->getLocation(),
8401 diag::note_attribute_overloadable_prev_overload);
8402 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8404 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8405 Redeclaration = false;
8412 // C++11 [dcl.constexpr]p8:
8413 // A constexpr specifier for a non-static member function that is not
8414 // a constructor declares that member function to be const.
8416 // This needs to be delayed until we know whether this is an out-of-line
8417 // definition of a static member function.
8419 // This rule is not present in C++1y, so we produce a backwards
8420 // compatibility warning whenever it happens in C++11.
8421 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8422 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8423 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8424 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8425 CXXMethodDecl *OldMD = nullptr;
8427 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8428 if (!OldMD || !OldMD->isStatic()) {
8429 const FunctionProtoType *FPT =
8430 MD->getType()->castAs<FunctionProtoType>();
8431 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8432 EPI.TypeQuals |= Qualifiers::Const;
8433 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8434 FPT->getParamTypes(), EPI));
8436 // Warn that we did this, if we're not performing template instantiation.
8437 // In that case, we'll have warned already when the template was defined.
8438 if (ActiveTemplateInstantiations.empty()) {
8439 SourceLocation AddConstLoc;
8440 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8441 .IgnoreParens().getAs<FunctionTypeLoc>())
8442 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8444 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8445 << FixItHint::CreateInsertion(AddConstLoc, " const");
8450 if (Redeclaration) {
8451 // NewFD and OldDecl represent declarations that need to be
8453 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8454 NewFD->setInvalidDecl();
8455 return Redeclaration;
8459 Previous.addDecl(OldDecl);
8461 if (FunctionTemplateDecl *OldTemplateDecl
8462 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8463 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8464 FunctionTemplateDecl *NewTemplateDecl
8465 = NewFD->getDescribedFunctionTemplate();
8466 assert(NewTemplateDecl && "Template/non-template mismatch");
8467 if (CXXMethodDecl *Method
8468 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8469 Method->setAccess(OldTemplateDecl->getAccess());
8470 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8473 // If this is an explicit specialization of a member that is a function
8474 // template, mark it as a member specialization.
8475 if (IsExplicitSpecialization &&
8476 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8477 NewTemplateDecl->setMemberSpecialization();
8478 assert(OldTemplateDecl->isMemberSpecialization());
8482 // This needs to happen first so that 'inline' propagates.
8483 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8485 if (isa<CXXMethodDecl>(NewFD))
8486 NewFD->setAccess(OldDecl->getAccess());
8490 // Semantic checking for this function declaration (in isolation).
8492 if (getLangOpts().CPlusPlus) {
8493 // C++-specific checks.
8494 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8495 CheckConstructor(Constructor);
8496 } else if (CXXDestructorDecl *Destructor =
8497 dyn_cast<CXXDestructorDecl>(NewFD)) {
8498 CXXRecordDecl *Record = Destructor->getParent();
8499 QualType ClassType = Context.getTypeDeclType(Record);
8501 // FIXME: Shouldn't we be able to perform this check even when the class
8502 // type is dependent? Both gcc and edg can handle that.
8503 if (!ClassType->isDependentType()) {
8504 DeclarationName Name
8505 = Context.DeclarationNames.getCXXDestructorName(
8506 Context.getCanonicalType(ClassType));
8507 if (NewFD->getDeclName() != Name) {
8508 Diag(NewFD->getLocation(), diag::err_destructor_name);
8509 NewFD->setInvalidDecl();
8510 return Redeclaration;
8513 } else if (CXXConversionDecl *Conversion
8514 = dyn_cast<CXXConversionDecl>(NewFD)) {
8515 ActOnConversionDeclarator(Conversion);
8518 // Find any virtual functions that this function overrides.
8519 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8520 if (!Method->isFunctionTemplateSpecialization() &&
8521 !Method->getDescribedFunctionTemplate() &&
8522 Method->isCanonicalDecl()) {
8523 if (AddOverriddenMethods(Method->getParent(), Method)) {
8524 // If the function was marked as "static", we have a problem.
8525 if (NewFD->getStorageClass() == SC_Static) {
8526 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8531 if (Method->isStatic())
8532 checkThisInStaticMemberFunctionType(Method);
8535 // Extra checking for C++ overloaded operators (C++ [over.oper]).
8536 if (NewFD->isOverloadedOperator() &&
8537 CheckOverloadedOperatorDeclaration(NewFD)) {
8538 NewFD->setInvalidDecl();
8539 return Redeclaration;
8542 // Extra checking for C++0x literal operators (C++0x [over.literal]).
8543 if (NewFD->getLiteralIdentifier() &&
8544 CheckLiteralOperatorDeclaration(NewFD)) {
8545 NewFD->setInvalidDecl();
8546 return Redeclaration;
8549 // In C++, check default arguments now that we have merged decls. Unless
8550 // the lexical context is the class, because in this case this is done
8551 // during delayed parsing anyway.
8552 if (!CurContext->isRecord())
8553 CheckCXXDefaultArguments(NewFD);
8555 // If this function declares a builtin function, check the type of this
8556 // declaration against the expected type for the builtin.
8557 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8558 ASTContext::GetBuiltinTypeError Error;
8559 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8560 QualType T = Context.GetBuiltinType(BuiltinID, Error);
8561 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8562 // The type of this function differs from the type of the builtin,
8563 // so forget about the builtin entirely.
8564 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8568 // If this function is declared as being extern "C", then check to see if
8569 // the function returns a UDT (class, struct, or union type) that is not C
8570 // compatible, and if it does, warn the user.
8571 // But, issue any diagnostic on the first declaration only.
8572 if (Previous.empty() && NewFD->isExternC()) {
8573 QualType R = NewFD->getReturnType();
8574 if (R->isIncompleteType() && !R->isVoidType())
8575 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8577 else if (!R.isPODType(Context) && !R->isVoidType() &&
8578 !R->isObjCObjectPointerType())
8579 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8582 return Redeclaration;
8585 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8586 // C++11 [basic.start.main]p3:
8587 // A program that [...] declares main to be inline, static or
8588 // constexpr is ill-formed.
8589 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
8590 // appear in a declaration of main.
8591 // static main is not an error under C99, but we should warn about it.
8592 // We accept _Noreturn main as an extension.
8593 if (FD->getStorageClass() == SC_Static)
8594 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8595 ? diag::err_static_main : diag::warn_static_main)
8596 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8597 if (FD->isInlineSpecified())
8598 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8599 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8600 if (DS.isNoreturnSpecified()) {
8601 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8602 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8603 Diag(NoreturnLoc, diag::ext_noreturn_main);
8604 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8605 << FixItHint::CreateRemoval(NoreturnRange);
8607 if (FD->isConstexpr()) {
8608 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8609 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8610 FD->setConstexpr(false);
8613 if (getLangOpts().OpenCL) {
8614 Diag(FD->getLocation(), diag::err_opencl_no_main)
8615 << FD->hasAttr<OpenCLKernelAttr>();
8616 FD->setInvalidDecl();
8620 QualType T = FD->getType();
8621 assert(T->isFunctionType() && "function decl is not of function type");
8622 const FunctionType* FT = T->castAs<FunctionType>();
8624 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8625 // In C with GNU extensions we allow main() to have non-integer return
8626 // type, but we should warn about the extension, and we disable the
8627 // implicit-return-zero rule.
8629 // GCC in C mode accepts qualified 'int'.
8630 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8631 FD->setHasImplicitReturnZero(true);
8633 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8634 SourceRange RTRange = FD->getReturnTypeSourceRange();
8635 if (RTRange.isValid())
8636 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8637 << FixItHint::CreateReplacement(RTRange, "int");
8640 // In C and C++, main magically returns 0 if you fall off the end;
8641 // set the flag which tells us that.
8642 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8644 // All the standards say that main() should return 'int'.
8645 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8646 FD->setHasImplicitReturnZero(true);
8648 // Otherwise, this is just a flat-out error.
8649 SourceRange RTRange = FD->getReturnTypeSourceRange();
8650 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8651 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8653 FD->setInvalidDecl(true);
8657 // Treat protoless main() as nullary.
8658 if (isa<FunctionNoProtoType>(FT)) return;
8660 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8661 unsigned nparams = FTP->getNumParams();
8662 assert(FD->getNumParams() == nparams);
8664 bool HasExtraParameters = (nparams > 3);
8666 if (FTP->isVariadic()) {
8667 Diag(FD->getLocation(), diag::ext_variadic_main);
8668 // FIXME: if we had information about the location of the ellipsis, we
8669 // could add a FixIt hint to remove it as a parameter.
8672 // Darwin passes an undocumented fourth argument of type char**. If
8673 // other platforms start sprouting these, the logic below will start
8675 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8676 HasExtraParameters = false;
8678 if (HasExtraParameters) {
8679 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8680 FD->setInvalidDecl(true);
8684 // FIXME: a lot of the following diagnostics would be improved
8685 // if we had some location information about types.
8688 Context.getPointerType(Context.getPointerType(Context.CharTy));
8689 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8691 for (unsigned i = 0; i < nparams; ++i) {
8692 QualType AT = FTP->getParamType(i);
8694 bool mismatch = true;
8696 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8698 else if (Expected[i] == CharPP) {
8699 // As an extension, the following forms are okay:
8701 // char const * const *
8704 QualifierCollector qs;
8705 const PointerType* PT;
8706 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8707 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8708 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8711 mismatch = !qs.empty();
8716 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8717 // TODO: suggest replacing given type with expected type
8718 FD->setInvalidDecl(true);
8722 if (nparams == 1 && !FD->isInvalidDecl()) {
8723 Diag(FD->getLocation(), diag::warn_main_one_arg);
8726 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8727 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8728 FD->setInvalidDecl();
8732 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8733 QualType T = FD->getType();
8734 assert(T->isFunctionType() && "function decl is not of function type");
8735 const FunctionType *FT = T->castAs<FunctionType>();
8737 // Set an implicit return of 'zero' if the function can return some integral,
8738 // enumeration, pointer or nullptr type.
8739 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8740 FT->getReturnType()->isAnyPointerType() ||
8741 FT->getReturnType()->isNullPtrType())
8742 // DllMain is exempt because a return value of zero means it failed.
8743 if (FD->getName() != "DllMain")
8744 FD->setHasImplicitReturnZero(true);
8746 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8747 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8748 FD->setInvalidDecl();
8752 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8753 // FIXME: Need strict checking. In C89, we need to check for
8754 // any assignment, increment, decrement, function-calls, or
8755 // commas outside of a sizeof. In C99, it's the same list,
8756 // except that the aforementioned are allowed in unevaluated
8757 // expressions. Everything else falls under the
8758 // "may accept other forms of constant expressions" exception.
8759 // (We never end up here for C++, so the constant expression
8760 // rules there don't matter.)
8761 const Expr *Culprit;
8762 if (Init->isConstantInitializer(Context, false, &Culprit))
8764 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8765 << Culprit->getSourceRange();
8770 // Visits an initialization expression to see if OrigDecl is evaluated in
8771 // its own initialization and throws a warning if it does.
8772 class SelfReferenceChecker
8773 : public EvaluatedExprVisitor<SelfReferenceChecker> {
8778 bool isReferenceType;
8781 llvm::SmallVector<unsigned, 4> InitFieldIndex;
8783 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8785 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8786 S(S), OrigDecl(OrigDecl) {
8788 isRecordType = false;
8789 isReferenceType = false;
8791 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8792 isPODType = VD->getType().isPODType(S.Context);
8793 isRecordType = VD->getType()->isRecordType();
8794 isReferenceType = VD->getType()->isReferenceType();
8798 // For most expressions, just call the visitor. For initializer lists,
8799 // track the index of the field being initialized since fields are
8800 // initialized in order allowing use of previously initialized fields.
8801 void CheckExpr(Expr *E) {
8802 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8808 // Track and increment the index here.
8810 InitFieldIndex.push_back(0);
8811 for (auto Child : InitList->children()) {
8812 CheckExpr(cast<Expr>(Child));
8813 ++InitFieldIndex.back();
8815 InitFieldIndex.pop_back();
8818 // Returns true if MemberExpr is checked and no futher checking is needed.
8819 // Returns false if additional checking is required.
8820 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8821 llvm::SmallVector<FieldDecl*, 4> Fields;
8823 bool ReferenceField = false;
8825 // Get the field memebers used.
8826 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8827 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8830 Fields.push_back(FD);
8831 if (FD->getType()->isReferenceType())
8832 ReferenceField = true;
8833 Base = ME->getBase()->IgnoreParenImpCasts();
8836 // Keep checking only if the base Decl is the same.
8837 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8838 if (!DRE || DRE->getDecl() != OrigDecl)
8841 // A reference field can be bound to an unininitialized field.
8842 if (CheckReference && !ReferenceField)
8845 // Convert FieldDecls to their index number.
8846 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8847 for (const FieldDecl *I : llvm::reverse(Fields))
8848 UsedFieldIndex.push_back(I->getFieldIndex());
8850 // See if a warning is needed by checking the first difference in index
8851 // numbers. If field being used has index less than the field being
8852 // initialized, then the use is safe.
8853 for (auto UsedIter = UsedFieldIndex.begin(),
8854 UsedEnd = UsedFieldIndex.end(),
8855 OrigIter = InitFieldIndex.begin(),
8856 OrigEnd = InitFieldIndex.end();
8857 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8858 if (*UsedIter < *OrigIter)
8860 if (*UsedIter > *OrigIter)
8864 // TODO: Add a different warning which will print the field names.
8865 HandleDeclRefExpr(DRE);
8869 // For most expressions, the cast is directly above the DeclRefExpr.
8870 // For conditional operators, the cast can be outside the conditional
8871 // operator if both expressions are DeclRefExpr's.
8872 void HandleValue(Expr *E) {
8873 E = E->IgnoreParens();
8874 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8875 HandleDeclRefExpr(DRE);
8879 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8880 Visit(CO->getCond());
8881 HandleValue(CO->getTrueExpr());
8882 HandleValue(CO->getFalseExpr());
8886 if (BinaryConditionalOperator *BCO =
8887 dyn_cast<BinaryConditionalOperator>(E)) {
8888 Visit(BCO->getCond());
8889 HandleValue(BCO->getFalseExpr());
8893 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8894 HandleValue(OVE->getSourceExpr());
8898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8899 if (BO->getOpcode() == BO_Comma) {
8900 Visit(BO->getLHS());
8901 HandleValue(BO->getRHS());
8906 if (isa<MemberExpr>(E)) {
8908 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8909 false /*CheckReference*/))
8913 Expr *Base = E->IgnoreParenImpCasts();
8914 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8915 // Check for static member variables and don't warn on them.
8916 if (!isa<FieldDecl>(ME->getMemberDecl()))
8918 Base = ME->getBase()->IgnoreParenImpCasts();
8920 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8921 HandleDeclRefExpr(DRE);
8928 // Reference types not handled in HandleValue are handled here since all
8929 // uses of references are bad, not just r-value uses.
8930 void VisitDeclRefExpr(DeclRefExpr *E) {
8931 if (isReferenceType)
8932 HandleDeclRefExpr(E);
8935 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8936 if (E->getCastKind() == CK_LValueToRValue) {
8937 HandleValue(E->getSubExpr());
8941 Inherited::VisitImplicitCastExpr(E);
8944 void VisitMemberExpr(MemberExpr *E) {
8946 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8950 // Don't warn on arrays since they can be treated as pointers.
8951 if (E->getType()->canDecayToPointerType()) return;
8953 // Warn when a non-static method call is followed by non-static member
8954 // field accesses, which is followed by a DeclRefExpr.
8955 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8956 bool Warn = (MD && !MD->isStatic());
8957 Expr *Base = E->getBase()->IgnoreParenImpCasts();
8958 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8959 if (!isa<FieldDecl>(ME->getMemberDecl()))
8961 Base = ME->getBase()->IgnoreParenImpCasts();
8964 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8966 HandleDeclRefExpr(DRE);
8970 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8971 // Visit that expression.
8975 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8976 Expr *Callee = E->getCallee();
8978 if (isa<UnresolvedLookupExpr>(Callee))
8979 return Inherited::VisitCXXOperatorCallExpr(E);
8982 for (auto Arg: E->arguments())
8983 HandleValue(Arg->IgnoreParenImpCasts());
8986 void VisitUnaryOperator(UnaryOperator *E) {
8987 // For POD record types, addresses of its own members are well-defined.
8988 if (E->getOpcode() == UO_AddrOf && isRecordType &&
8989 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8991 HandleValue(E->getSubExpr());
8995 if (E->isIncrementDecrementOp()) {
8996 HandleValue(E->getSubExpr());
9000 Inherited::VisitUnaryOperator(E);
9003 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
9005 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9006 if (E->getConstructor()->isCopyConstructor()) {
9007 Expr *ArgExpr = E->getArg(0);
9008 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9009 if (ILE->getNumInits() == 1)
9010 ArgExpr = ILE->getInit(0);
9011 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9012 if (ICE->getCastKind() == CK_NoOp)
9013 ArgExpr = ICE->getSubExpr();
9014 HandleValue(ArgExpr);
9017 Inherited::VisitCXXConstructExpr(E);
9020 void VisitCallExpr(CallExpr *E) {
9021 // Treat std::move as a use.
9022 if (E->getNumArgs() == 1) {
9023 if (FunctionDecl *FD = E->getDirectCallee()) {
9024 if (FD->isInStdNamespace() && FD->getIdentifier() &&
9025 FD->getIdentifier()->isStr("move")) {
9026 HandleValue(E->getArg(0));
9032 Inherited::VisitCallExpr(E);
9035 void VisitBinaryOperator(BinaryOperator *E) {
9036 if (E->isCompoundAssignmentOp()) {
9037 HandleValue(E->getLHS());
9042 Inherited::VisitBinaryOperator(E);
9045 // A custom visitor for BinaryConditionalOperator is needed because the
9046 // regular visitor would check the condition and true expression separately
9047 // but both point to the same place giving duplicate diagnostics.
9048 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9049 Visit(E->getCond());
9050 Visit(E->getFalseExpr());
9053 void HandleDeclRefExpr(DeclRefExpr *DRE) {
9054 Decl* ReferenceDecl = DRE->getDecl();
9055 if (OrigDecl != ReferenceDecl) return;
9057 if (isReferenceType) {
9058 diag = diag::warn_uninit_self_reference_in_reference_init;
9059 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9060 diag = diag::warn_static_self_reference_in_init;
9061 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9062 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9063 DRE->getDecl()->getType()->isRecordType()) {
9064 diag = diag::warn_uninit_self_reference_in_init;
9066 // Local variables will be handled by the CFG analysis.
9070 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9072 << DRE->getNameInfo().getName()
9073 << OrigDecl->getLocation()
9074 << DRE->getSourceRange());
9078 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9079 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9081 // Parameters arguments are occassionially constructed with itself,
9082 // for instance, in recursive functions. Skip them.
9083 if (isa<ParmVarDecl>(OrigDecl))
9086 E = E->IgnoreParens();
9088 // Skip checking T a = a where T is not a record or reference type.
9089 // Doing so is a way to silence uninitialized warnings.
9090 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9091 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9092 if (ICE->getCastKind() == CK_LValueToRValue)
9093 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9094 if (DRE->getDecl() == OrigDecl)
9097 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9101 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9102 DeclarationName Name, QualType Type,
9103 TypeSourceInfo *TSI,
9104 SourceRange Range, bool DirectInit,
9106 bool IsInitCapture = !VDecl;
9107 assert((!VDecl || !VDecl->isInitCapture()) &&
9108 "init captures are expected to be deduced prior to initialization");
9110 ArrayRef<Expr *> DeduceInits = Init;
9112 if (auto *PL = dyn_cast<ParenListExpr>(Init))
9113 DeduceInits = PL->exprs();
9114 else if (auto *IL = dyn_cast<InitListExpr>(Init))
9115 DeduceInits = IL->inits();
9118 // Deduction only works if we have exactly one source expression.
9119 if (DeduceInits.empty()) {
9120 // It isn't possible to write this directly, but it is possible to
9121 // end up in this situation with "auto x(some_pack...);"
9122 Diag(Init->getLocStart(), IsInitCapture
9123 ? diag::err_init_capture_no_expression
9124 : diag::err_auto_var_init_no_expression)
9125 << Name << Type << Range;
9129 if (DeduceInits.size() > 1) {
9130 Diag(DeduceInits[1]->getLocStart(),
9131 IsInitCapture ? diag::err_init_capture_multiple_expressions
9132 : diag::err_auto_var_init_multiple_expressions)
9133 << Name << Type << Range;
9137 Expr *DeduceInit = DeduceInits[0];
9138 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9139 Diag(Init->getLocStart(), IsInitCapture
9140 ? diag::err_init_capture_paren_braces
9141 : diag::err_auto_var_init_paren_braces)
9142 << isa<InitListExpr>(Init) << Name << Type << Range;
9146 // Expressions default to 'id' when we're in a debugger.
9147 bool DefaultedAnyToId = false;
9148 if (getLangOpts().DebuggerCastResultToId &&
9149 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9150 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9151 if (Result.isInvalid()) {
9154 Init = Result.get();
9155 DefaultedAnyToId = true;
9158 QualType DeducedType;
9159 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9161 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9162 else if (isa<InitListExpr>(Init))
9163 Diag(Range.getBegin(),
9164 diag::err_init_capture_deduction_failure_from_init_list)
9166 << (DeduceInit->getType().isNull() ? TSI->getType()
9167 : DeduceInit->getType())
9168 << DeduceInit->getSourceRange();
9170 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9171 << Name << TSI->getType()
9172 << (DeduceInit->getType().isNull() ? TSI->getType()
9173 : DeduceInit->getType())
9174 << DeduceInit->getSourceRange();
9177 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9178 // 'id' instead of a specific object type prevents most of our usual
9180 // We only want to warn outside of template instantiations, though:
9181 // inside a template, the 'id' could have come from a parameter.
9182 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9183 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9184 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9185 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9191 /// AddInitializerToDecl - Adds the initializer Init to the
9192 /// declaration dcl. If DirectInit is true, this is C++ direct
9193 /// initialization rather than copy initialization.
9194 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9195 bool DirectInit, bool TypeMayContainAuto) {
9196 // If there is no declaration, there was an error parsing it. Just ignore
9198 if (!RealDecl || RealDecl->isInvalidDecl()) {
9199 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9203 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9204 // Pure-specifiers are handled in ActOnPureSpecifier.
9205 Diag(Method->getLocation(), diag::err_member_function_initialization)
9206 << Method->getDeclName() << Init->getSourceRange();
9207 Method->setInvalidDecl();
9211 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9213 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9214 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9215 RealDecl->setInvalidDecl();
9219 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9220 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9221 // Attempt typo correction early so that the type of the init expression can
9222 // be deduced based on the chosen correction if the original init contains a
9224 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9225 if (!Res.isUsable()) {
9226 RealDecl->setInvalidDecl();
9231 QualType DeducedType = deduceVarTypeFromInitializer(
9232 VDecl, VDecl->getDeclName(), VDecl->getType(),
9233 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9234 if (DeducedType.isNull()) {
9235 RealDecl->setInvalidDecl();
9239 VDecl->setType(DeducedType);
9240 assert(VDecl->isLinkageValid());
9242 // In ARC, infer lifetime.
9243 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9244 VDecl->setInvalidDecl();
9246 // If this is a redeclaration, check that the type we just deduced matches
9247 // the previously declared type.
9248 if (VarDecl *Old = VDecl->getPreviousDecl()) {
9249 // We never need to merge the type, because we cannot form an incomplete
9250 // array of auto, nor deduce such a type.
9251 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9254 // Check the deduced type is valid for a variable declaration.
9255 CheckVariableDeclarationType(VDecl);
9256 if (VDecl->isInvalidDecl())
9260 // dllimport cannot be used on variable definitions.
9261 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9262 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9263 VDecl->setInvalidDecl();
9267 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9268 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9269 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9270 VDecl->setInvalidDecl();
9274 if (!VDecl->getType()->isDependentType()) {
9275 // A definition must end up with a complete type, which means it must be
9276 // complete with the restriction that an array type might be completed by
9277 // the initializer; note that later code assumes this restriction.
9278 QualType BaseDeclType = VDecl->getType();
9279 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9280 BaseDeclType = Array->getElementType();
9281 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9282 diag::err_typecheck_decl_incomplete_type)) {
9283 RealDecl->setInvalidDecl();
9287 // The variable can not have an abstract class type.
9288 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9289 diag::err_abstract_type_in_decl,
9290 AbstractVariableType))
9291 VDecl->setInvalidDecl();
9295 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9296 NamedDecl *Hidden = nullptr;
9297 if (!hasVisibleDefinition(Def, &Hidden) &&
9298 (VDecl->getFormalLinkage() == InternalLinkage ||
9299 VDecl->getDescribedVarTemplate() ||
9300 VDecl->getNumTemplateParameterLists() ||
9301 VDecl->getDeclContext()->isDependentContext())) {
9302 // The previous definition is hidden, and multiple definitions are
9303 // permitted (in separate TUs). Form another definition of it.
9305 Diag(VDecl->getLocation(), diag::err_redefinition)
9306 << VDecl->getDeclName();
9307 Diag(Def->getLocation(), diag::note_previous_definition);
9308 VDecl->setInvalidDecl();
9313 if (getLangOpts().CPlusPlus) {
9314 // C++ [class.static.data]p4
9315 // If a static data member is of const integral or const
9316 // enumeration type, its declaration in the class definition can
9317 // specify a constant-initializer which shall be an integral
9318 // constant expression (5.19). In that case, the member can appear
9319 // in integral constant expressions. The member shall still be
9320 // defined in a namespace scope if it is used in the program and the
9321 // namespace scope definition shall not contain an initializer.
9323 // We already performed a redefinition check above, but for static
9324 // data members we also need to check whether there was an in-class
9325 // declaration with an initializer.
9326 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9327 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9328 << VDecl->getDeclName();
9329 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9330 diag::note_previous_initializer)
9335 if (VDecl->hasLocalStorage())
9336 getCurFunction()->setHasBranchProtectedScope();
9338 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9339 VDecl->setInvalidDecl();
9344 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9345 // a kernel function cannot be initialized."
9346 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9347 Diag(VDecl->getLocation(), diag::err_local_cant_init);
9348 VDecl->setInvalidDecl();
9352 // Get the decls type and save a reference for later, since
9353 // CheckInitializerTypes may change it.
9354 QualType DclT = VDecl->getType(), SavT = DclT;
9356 // Expressions default to 'id' when we're in a debugger
9357 // and we are assigning it to a variable of Objective-C pointer type.
9358 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9359 Init->getType() == Context.UnknownAnyTy) {
9360 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9361 if (Result.isInvalid()) {
9362 VDecl->setInvalidDecl();
9365 Init = Result.get();
9368 // Perform the initialization.
9369 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9370 if (!VDecl->isInvalidDecl()) {
9371 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9372 InitializationKind Kind =
9375 ? InitializationKind::CreateDirect(VDecl->getLocation(),
9376 Init->getLocStart(),
9378 : InitializationKind::CreateDirectList(VDecl->getLocation())
9379 : InitializationKind::CreateCopy(VDecl->getLocation(),
9380 Init->getLocStart());
9382 MultiExprArg Args = Init;
9384 Args = MultiExprArg(CXXDirectInit->getExprs(),
9385 CXXDirectInit->getNumExprs());
9387 // Try to correct any TypoExprs in the initialization arguments.
9388 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9389 ExprResult Res = CorrectDelayedTyposInExpr(
9390 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9391 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9392 return Init.Failed() ? ExprError() : E;
9394 if (Res.isInvalid()) {
9395 VDecl->setInvalidDecl();
9396 } else if (Res.get() != Args[Idx]) {
9397 Args[Idx] = Res.get();
9400 if (VDecl->isInvalidDecl())
9403 InitializationSequence InitSeq(*this, Entity, Kind, Args);
9404 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9405 if (Result.isInvalid()) {
9406 VDecl->setInvalidDecl();
9410 Init = Result.getAs<Expr>();
9413 // Check for self-references within variable initializers.
9414 // Variables declared within a function/method body (except for references)
9415 // are handled by a dataflow analysis.
9416 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9417 VDecl->getType()->isReferenceType()) {
9418 CheckSelfReference(*this, RealDecl, Init, DirectInit);
9421 // If the type changed, it means we had an incomplete type that was
9422 // completed by the initializer. For example:
9423 // int ary[] = { 1, 3, 5 };
9424 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9425 if (!VDecl->isInvalidDecl() && (DclT != SavT))
9426 VDecl->setType(DclT);
9428 if (!VDecl->isInvalidDecl()) {
9429 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9431 if (VDecl->hasAttr<BlocksAttr>())
9432 checkRetainCycles(VDecl, Init);
9434 // It is safe to assign a weak reference into a strong variable.
9435 // Although this code can still have problems:
9436 // id x = self.weakProp;
9437 // id y = self.weakProp;
9438 // we do not warn to warn spuriously when 'x' and 'y' are on separate
9439 // paths through the function. This should be revisited if
9440 // -Wrepeated-use-of-weak is made flow-sensitive.
9441 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9442 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9443 Init->getLocStart()))
9444 getCurFunction()->markSafeWeakUse(Init);
9447 // The initialization is usually a full-expression.
9449 // FIXME: If this is a braced initialization of an aggregate, it is not
9450 // an expression, and each individual field initializer is a separate
9451 // full-expression. For instance, in:
9453 // struct Temp { ~Temp(); };
9454 // struct S { S(Temp); };
9455 // struct T { S a, b; } t = { Temp(), Temp() }
9457 // we should destroy the first Temp before constructing the second.
9458 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9460 VDecl->isConstexpr());
9461 if (Result.isInvalid()) {
9462 VDecl->setInvalidDecl();
9465 Init = Result.get();
9467 // Attach the initializer to the decl.
9468 VDecl->setInit(Init);
9470 if (VDecl->isLocalVarDecl()) {
9471 // C99 6.7.8p4: All the expressions in an initializer for an object that has
9472 // static storage duration shall be constant expressions or string literals.
9473 // C++ does not have this restriction.
9474 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9475 const Expr *Culprit;
9476 if (VDecl->getStorageClass() == SC_Static)
9477 CheckForConstantInitializer(Init, DclT);
9478 // C89 is stricter than C99 for non-static aggregate types.
9479 // C89 6.5.7p3: All the expressions [...] in an initializer list
9480 // for an object that has aggregate or union type shall be
9481 // constant expressions.
9482 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9483 isa<InitListExpr>(Init) &&
9484 !Init->isConstantInitializer(Context, false, &Culprit))
9485 Diag(Culprit->getExprLoc(),
9486 diag::ext_aggregate_init_not_constant)
9487 << Culprit->getSourceRange();
9489 } else if (VDecl->isStaticDataMember() &&
9490 VDecl->getLexicalDeclContext()->isRecord()) {
9491 // This is an in-class initialization for a static data member, e.g.,
9494 // static const int value = 17;
9497 // C++ [class.mem]p4:
9498 // A member-declarator can contain a constant-initializer only
9499 // if it declares a static member (9.4) of const integral or
9500 // const enumeration type, see 9.4.2.
9502 // C++11 [class.static.data]p3:
9503 // If a non-volatile const static data member is of integral or
9504 // enumeration type, its declaration in the class definition can
9505 // specify a brace-or-equal-initializer in which every initalizer-clause
9506 // that is an assignment-expression is a constant expression. A static
9507 // data member of literal type can be declared in the class definition
9508 // with the constexpr specifier; if so, its declaration shall specify a
9509 // brace-or-equal-initializer in which every initializer-clause that is
9510 // an assignment-expression is a constant expression.
9512 // Do nothing on dependent types.
9513 if (DclT->isDependentType()) {
9515 // Allow any 'static constexpr' members, whether or not they are of literal
9516 // type. We separately check that every constexpr variable is of literal
9518 } else if (VDecl->isConstexpr()) {
9520 // Require constness.
9521 } else if (!DclT.isConstQualified()) {
9522 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9523 << Init->getSourceRange();
9524 VDecl->setInvalidDecl();
9526 // We allow integer constant expressions in all cases.
9527 } else if (DclT->isIntegralOrEnumerationType()) {
9528 // Check whether the expression is a constant expression.
9530 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9531 // In C++11, a non-constexpr const static data member with an
9532 // in-class initializer cannot be volatile.
9533 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9534 else if (Init->isValueDependent())
9535 ; // Nothing to check.
9536 else if (Init->isIntegerConstantExpr(Context, &Loc))
9537 ; // Ok, it's an ICE!
9538 else if (Init->isEvaluatable(Context)) {
9539 // If we can constant fold the initializer through heroics, accept it,
9540 // but report this as a use of an extension for -pedantic.
9541 Diag(Loc, diag::ext_in_class_initializer_non_constant)
9542 << Init->getSourceRange();
9544 // Otherwise, this is some crazy unknown case. Report the issue at the
9545 // location provided by the isIntegerConstantExpr failed check.
9546 Diag(Loc, diag::err_in_class_initializer_non_constant)
9547 << Init->getSourceRange();
9548 VDecl->setInvalidDecl();
9551 // We allow foldable floating-point constants as an extension.
9552 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9553 // In C++98, this is a GNU extension. In C++11, it is not, but we support
9554 // it anyway and provide a fixit to add the 'constexpr'.
9555 if (getLangOpts().CPlusPlus11) {
9556 Diag(VDecl->getLocation(),
9557 diag::ext_in_class_initializer_float_type_cxx11)
9558 << DclT << Init->getSourceRange();
9559 Diag(VDecl->getLocStart(),
9560 diag::note_in_class_initializer_float_type_cxx11)
9561 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9563 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9564 << DclT << Init->getSourceRange();
9566 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9567 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9568 << Init->getSourceRange();
9569 VDecl->setInvalidDecl();
9573 // Suggest adding 'constexpr' in C++11 for literal types.
9574 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9575 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9576 << DclT << Init->getSourceRange()
9577 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9578 VDecl->setConstexpr(true);
9581 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9582 << DclT << Init->getSourceRange();
9583 VDecl->setInvalidDecl();
9585 } else if (VDecl->isFileVarDecl()) {
9586 if (VDecl->getStorageClass() == SC_Extern &&
9587 (!getLangOpts().CPlusPlus ||
9588 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9589 VDecl->isExternC())) &&
9590 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9591 Diag(VDecl->getLocation(), diag::warn_extern_init);
9593 // C99 6.7.8p4. All file scoped initializers need to be constant.
9594 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9595 CheckForConstantInitializer(Init, DclT);
9598 // We will represent direct-initialization similarly to copy-initialization:
9599 // int x(1); -as-> int x = 1;
9600 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9602 // Clients that want to distinguish between the two forms, can check for
9603 // direct initializer using VarDecl::getInitStyle().
9604 // A major benefit is that clients that don't particularly care about which
9605 // exactly form was it (like the CodeGen) can handle both cases without
9606 // special case code.
9609 // The form of initialization (using parentheses or '=') is generally
9610 // insignificant, but does matter when the entity being initialized has a
9612 if (CXXDirectInit) {
9613 assert(DirectInit && "Call-style initializer must be direct init.");
9614 VDecl->setInitStyle(VarDecl::CallInit);
9615 } else if (DirectInit) {
9616 // This must be list-initialization. No other way is direct-initialization.
9617 VDecl->setInitStyle(VarDecl::ListInit);
9620 CheckCompleteVariableDeclaration(VDecl);
9623 /// ActOnInitializerError - Given that there was an error parsing an
9624 /// initializer for the given declaration, try to return to some form
9626 void Sema::ActOnInitializerError(Decl *D) {
9627 // Our main concern here is re-establishing invariants like "a
9628 // variable's type is either dependent or complete".
9629 if (!D || D->isInvalidDecl()) return;
9631 VarDecl *VD = dyn_cast<VarDecl>(D);
9634 // Auto types are meaningless if we can't make sense of the initializer.
9635 if (ParsingInitForAutoVars.count(D)) {
9636 D->setInvalidDecl();
9640 QualType Ty = VD->getType();
9641 if (Ty->isDependentType()) return;
9643 // Require a complete type.
9644 if (RequireCompleteType(VD->getLocation(),
9645 Context.getBaseElementType(Ty),
9646 diag::err_typecheck_decl_incomplete_type)) {
9647 VD->setInvalidDecl();
9651 // Require a non-abstract type.
9652 if (RequireNonAbstractType(VD->getLocation(), Ty,
9653 diag::err_abstract_type_in_decl,
9654 AbstractVariableType)) {
9655 VD->setInvalidDecl();
9659 // Don't bother complaining about constructors or destructors,
9663 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9664 bool TypeMayContainAuto) {
9665 // If there is no declaration, there was an error parsing it. Just ignore it.
9669 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9670 QualType Type = Var->getType();
9672 // C++11 [dcl.spec.auto]p3
9673 if (TypeMayContainAuto && Type->getContainedAutoType()) {
9674 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9675 << Var->getDeclName() << Type;
9676 Var->setInvalidDecl();
9680 // C++11 [class.static.data]p3: A static data member can be declared with
9681 // the constexpr specifier; if so, its declaration shall specify
9682 // a brace-or-equal-initializer.
9683 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9684 // the definition of a variable [...] or the declaration of a static data
9686 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9687 if (Var->isStaticDataMember())
9688 Diag(Var->getLocation(),
9689 diag::err_constexpr_static_mem_var_requires_init)
9690 << Var->getDeclName();
9692 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9693 Var->setInvalidDecl();
9697 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
9698 // definition having the concept specifier is called a variable concept. A
9699 // concept definition refers to [...] a variable concept and its initializer.
9700 if (Var->isConcept()) {
9701 Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9702 Var->setInvalidDecl();
9706 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9708 if (!Var->isInvalidDecl() &&
9709 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9710 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9711 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9712 Var->setInvalidDecl();
9716 switch (Var->isThisDeclarationADefinition()) {
9717 case VarDecl::Definition:
9718 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9721 // We have an out-of-line definition of a static data member
9722 // that has an in-class initializer, so we type-check this like
9727 case VarDecl::DeclarationOnly:
9728 // It's only a declaration.
9730 // Block scope. C99 6.7p7: If an identifier for an object is
9731 // declared with no linkage (C99 6.2.2p6), the type for the
9732 // object shall be complete.
9733 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9734 !Var->hasLinkage() && !Var->isInvalidDecl() &&
9735 RequireCompleteType(Var->getLocation(), Type,
9736 diag::err_typecheck_decl_incomplete_type))
9737 Var->setInvalidDecl();
9739 // Make sure that the type is not abstract.
9740 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9741 RequireNonAbstractType(Var->getLocation(), Type,
9742 diag::err_abstract_type_in_decl,
9743 AbstractVariableType))
9744 Var->setInvalidDecl();
9745 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9746 Var->getStorageClass() == SC_PrivateExtern) {
9747 Diag(Var->getLocation(), diag::warn_private_extern);
9748 Diag(Var->getLocation(), diag::note_private_extern);
9753 case VarDecl::TentativeDefinition:
9754 // File scope. C99 6.9.2p2: A declaration of an identifier for an
9755 // object that has file scope without an initializer, and without a
9756 // storage-class specifier or with the storage-class specifier "static",
9757 // constitutes a tentative definition. Note: A tentative definition with
9758 // external linkage is valid (C99 6.2.2p5).
9759 if (!Var->isInvalidDecl()) {
9760 if (const IncompleteArrayType *ArrayT
9761 = Context.getAsIncompleteArrayType(Type)) {
9762 if (RequireCompleteType(Var->getLocation(),
9763 ArrayT->getElementType(),
9764 diag::err_illegal_decl_array_incomplete_type))
9765 Var->setInvalidDecl();
9766 } else if (Var->getStorageClass() == SC_Static) {
9767 // C99 6.9.2p3: If the declaration of an identifier for an object is
9768 // a tentative definition and has internal linkage (C99 6.2.2p3), the
9769 // declared type shall not be an incomplete type.
9770 // NOTE: code such as the following
9772 // struct s { int a; };
9773 // is accepted by gcc. Hence here we issue a warning instead of
9774 // an error and we do not invalidate the static declaration.
9775 // NOTE: to avoid multiple warnings, only check the first declaration.
9776 if (Var->isFirstDecl())
9777 RequireCompleteType(Var->getLocation(), Type,
9778 diag::ext_typecheck_decl_incomplete_type);
9782 // Record the tentative definition; we're done.
9783 if (!Var->isInvalidDecl())
9784 TentativeDefinitions.push_back(Var);
9788 // Provide a specific diagnostic for uninitialized variable
9789 // definitions with incomplete array type.
9790 if (Type->isIncompleteArrayType()) {
9791 Diag(Var->getLocation(),
9792 diag::err_typecheck_incomplete_array_needs_initializer);
9793 Var->setInvalidDecl();
9797 // Provide a specific diagnostic for uninitialized variable
9798 // definitions with reference type.
9799 if (Type->isReferenceType()) {
9800 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9801 << Var->getDeclName()
9802 << SourceRange(Var->getLocation(), Var->getLocation());
9803 Var->setInvalidDecl();
9807 // Do not attempt to type-check the default initializer for a
9808 // variable with dependent type.
9809 if (Type->isDependentType())
9812 if (Var->isInvalidDecl())
9815 if (!Var->hasAttr<AliasAttr>()) {
9816 if (RequireCompleteType(Var->getLocation(),
9817 Context.getBaseElementType(Type),
9818 diag::err_typecheck_decl_incomplete_type)) {
9819 Var->setInvalidDecl();
9826 // The variable can not have an abstract class type.
9827 if (RequireNonAbstractType(Var->getLocation(), Type,
9828 diag::err_abstract_type_in_decl,
9829 AbstractVariableType)) {
9830 Var->setInvalidDecl();
9834 // Check for jumps past the implicit initializer. C++0x
9835 // clarifies that this applies to a "variable with automatic
9836 // storage duration", not a "local variable".
9837 // C++11 [stmt.dcl]p3
9838 // A program that jumps from a point where a variable with automatic
9839 // storage duration is not in scope to a point where it is in scope is
9840 // ill-formed unless the variable has scalar type, class type with a
9841 // trivial default constructor and a trivial destructor, a cv-qualified
9842 // version of one of these types, or an array of one of the preceding
9843 // types and is declared without an initializer.
9844 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9845 if (const RecordType *Record
9846 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9847 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9848 // Mark the function for further checking even if the looser rules of
9849 // C++11 do not require such checks, so that we can diagnose
9850 // incompatibilities with C++98.
9851 if (!CXXRecord->isPOD())
9852 getCurFunction()->setHasBranchProtectedScope();
9856 // C++03 [dcl.init]p9:
9857 // If no initializer is specified for an object, and the
9858 // object is of (possibly cv-qualified) non-POD class type (or
9859 // array thereof), the object shall be default-initialized; if
9860 // the object is of const-qualified type, the underlying class
9861 // type shall have a user-declared default
9862 // constructor. Otherwise, if no initializer is specified for
9863 // a non- static object, the object and its subobjects, if
9864 // any, have an indeterminate initial value); if the object
9865 // or any of its subobjects are of const-qualified type, the
9866 // program is ill-formed.
9867 // C++0x [dcl.init]p11:
9868 // If no initializer is specified for an object, the object is
9869 // default-initialized; [...].
9870 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9871 InitializationKind Kind
9872 = InitializationKind::CreateDefault(Var->getLocation());
9874 InitializationSequence InitSeq(*this, Entity, Kind, None);
9875 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9876 if (Init.isInvalid())
9877 Var->setInvalidDecl();
9878 else if (Init.get()) {
9879 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9880 // This is important for template substitution.
9881 Var->setInitStyle(VarDecl::CallInit);
9884 CheckCompleteVariableDeclaration(Var);
9888 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9889 VarDecl *VD = dyn_cast<VarDecl>(D);
9891 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9892 D->setInvalidDecl();
9896 VD->setCXXForRangeDecl(true);
9898 // for-range-declaration cannot be given a storage class specifier.
9900 switch (VD->getStorageClass()) {
9909 case SC_PrivateExtern:
9920 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9921 << VD->getDeclName() << Error;
9922 D->setInvalidDecl();
9927 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9928 IdentifierInfo *Ident,
9929 ParsedAttributes &Attrs,
9930 SourceLocation AttrEnd) {
9931 // C++1y [stmt.iter]p1:
9932 // A range-based for statement of the form
9933 // for ( for-range-identifier : for-range-initializer ) statement
9935 // for ( auto&& for-range-identifier : for-range-initializer ) statement
9936 DeclSpec DS(Attrs.getPool().getFactory());
9938 const char *PrevSpec;
9940 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9941 getPrintingPolicy());
9943 Declarator D(DS, Declarator::ForContext);
9944 D.SetIdentifier(Ident, IdentLoc);
9945 D.takeAttributes(Attrs, AttrEnd);
9947 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9948 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9949 EmptyAttrs, IdentLoc);
9950 Decl *Var = ActOnDeclarator(S, D);
9951 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9952 FinalizeDeclaration(Var);
9953 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9954 AttrEnd.isValid() ? AttrEnd : IdentLoc);
9957 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9958 if (var->isInvalidDecl()) return;
9960 // In Objective-C, don't allow jumps past the implicit initialization of a
9961 // local retaining variable.
9962 if (getLangOpts().ObjC1 &&
9963 var->hasLocalStorage()) {
9964 switch (var->getType().getObjCLifetime()) {
9965 case Qualifiers::OCL_None:
9966 case Qualifiers::OCL_ExplicitNone:
9967 case Qualifiers::OCL_Autoreleasing:
9970 case Qualifiers::OCL_Weak:
9971 case Qualifiers::OCL_Strong:
9972 getCurFunction()->setHasBranchProtectedScope();
9977 // Warn about externally-visible variables being defined without a
9978 // prior declaration. We only want to do this for global
9979 // declarations, but we also specifically need to avoid doing it for
9980 // class members because the linkage of an anonymous class can
9981 // change if it's later given a typedef name.
9982 if (var->isThisDeclarationADefinition() &&
9983 var->getDeclContext()->getRedeclContext()->isFileContext() &&
9984 var->isExternallyVisible() && var->hasLinkage() &&
9985 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9986 var->getLocation())) {
9987 // Find a previous declaration that's not a definition.
9988 VarDecl *prev = var->getPreviousDecl();
9989 while (prev && prev->isThisDeclarationADefinition())
9990 prev = prev->getPreviousDecl();
9993 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9996 if (var->getTLSKind() == VarDecl::TLS_Static) {
9997 const Expr *Culprit;
9998 if (var->getType().isDestructedType()) {
9999 // GNU C++98 edits for __thread, [basic.start.term]p3:
10000 // The type of an object with thread storage duration shall not
10001 // have a non-trivial destructor.
10002 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10003 if (getLangOpts().CPlusPlus11)
10004 Diag(var->getLocation(), diag::note_use_thread_local);
10005 } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10006 !var->getInit()->isConstantInitializer(
10007 Context, var->getType()->isReferenceType(), &Culprit)) {
10008 // GNU C++98 edits for __thread, [basic.start.init]p4:
10009 // An object of thread storage duration shall not require dynamic
10011 // FIXME: Need strict checking here.
10012 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10013 << Culprit->getSourceRange();
10014 if (getLangOpts().CPlusPlus11)
10015 Diag(var->getLocation(), diag::note_use_thread_local);
10020 // Apply section attributes and pragmas to global variables.
10021 bool GlobalStorage = var->hasGlobalStorage();
10022 if (GlobalStorage && var->isThisDeclarationADefinition() &&
10023 ActiveTemplateInstantiations.empty()) {
10024 PragmaStack<StringLiteral *> *Stack = nullptr;
10025 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10026 if (var->getType().isConstQualified())
10027 Stack = &ConstSegStack;
10028 else if (!var->getInit()) {
10029 Stack = &BSSSegStack;
10030 SectionFlags |= ASTContext::PSF_Write;
10032 Stack = &DataSegStack;
10033 SectionFlags |= ASTContext::PSF_Write;
10035 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10036 var->addAttr(SectionAttr::CreateImplicit(
10037 Context, SectionAttr::Declspec_allocate,
10038 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10040 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10041 if (UnifySection(SA->getName(), SectionFlags, var))
10042 var->dropAttr<SectionAttr>();
10044 // Apply the init_seg attribute if this has an initializer. If the
10045 // initializer turns out to not be dynamic, we'll end up ignoring this
10047 if (CurInitSeg && var->getInit())
10048 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10052 // All the following checks are C++ only.
10053 if (!getLangOpts().CPlusPlus) return;
10055 QualType type = var->getType();
10056 if (type->isDependentType()) return;
10058 // __block variables might require us to capture a copy-initializer.
10059 if (var->hasAttr<BlocksAttr>()) {
10060 // It's currently invalid to ever have a __block variable with an
10061 // array type; should we diagnose that here?
10063 // Regardless, we don't want to ignore array nesting when
10064 // constructing this copy.
10065 if (type->isStructureOrClassType()) {
10066 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10067 SourceLocation poi = var->getLocation();
10068 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10070 = PerformMoveOrCopyInitialization(
10071 InitializedEntity::InitializeBlock(poi, type, false),
10072 var, var->getType(), varRef, /*AllowNRVO=*/true);
10073 if (!result.isInvalid()) {
10074 result = MaybeCreateExprWithCleanups(result);
10075 Expr *init = result.getAs<Expr>();
10076 Context.setBlockVarCopyInits(var, init);
10081 Expr *Init = var->getInit();
10082 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10083 QualType baseType = Context.getBaseElementType(type);
10085 if (!var->getDeclContext()->isDependentContext() &&
10086 Init && !Init->isValueDependent()) {
10087 if (IsGlobal && !var->isConstexpr() &&
10088 !getDiagnostics().isIgnored(diag::warn_global_constructor,
10089 var->getLocation())) {
10090 // Warn about globals which don't have a constant initializer. Don't
10091 // warn about globals with a non-trivial destructor because we already
10092 // warned about them.
10093 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10094 if (!(RD && !RD->hasTrivialDestructor()) &&
10095 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10096 Diag(var->getLocation(), diag::warn_global_constructor)
10097 << Init->getSourceRange();
10100 if (var->isConstexpr()) {
10101 SmallVector<PartialDiagnosticAt, 8> Notes;
10102 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10103 SourceLocation DiagLoc = var->getLocation();
10104 // If the note doesn't add any useful information other than a source
10105 // location, fold it into the primary diagnostic.
10106 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10107 diag::note_invalid_subexpr_in_const_expr) {
10108 DiagLoc = Notes[0].first;
10111 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10112 << var << Init->getSourceRange();
10113 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10114 Diag(Notes[I].first, Notes[I].second);
10116 } else if (var->isUsableInConstantExpressions(Context)) {
10117 // Check whether the initializer of a const variable of integral or
10118 // enumeration type is an ICE now, since we can't tell whether it was
10119 // initialized by a constant expression if we check later.
10120 var->checkInitIsICE();
10124 // Require the destructor.
10125 if (const RecordType *recordType = baseType->getAs<RecordType>())
10126 FinalizeVarWithDestructor(var, recordType);
10129 /// \brief Determines if a variable's alignment is dependent.
10130 static bool hasDependentAlignment(VarDecl *VD) {
10131 if (VD->getType()->isDependentType())
10133 for (auto *I : VD->specific_attrs<AlignedAttr>())
10134 if (I->isAlignmentDependent())
10139 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10140 /// any semantic actions necessary after any initializer has been attached.
10142 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10143 // Note that we are no longer parsing the initializer for this declaration.
10144 ParsingInitForAutoVars.erase(ThisDecl);
10146 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10150 checkAttributesAfterMerging(*this, *VD);
10152 // Perform TLS alignment check here after attributes attached to the variable
10153 // which may affect the alignment have been processed. Only perform the check
10154 // if the target has a maximum TLS alignment (zero means no constraints).
10155 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10156 // Protect the check so that it's not performed on dependent types and
10157 // dependent alignments (we can't determine the alignment in that case).
10158 if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10159 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10160 if (Context.getDeclAlign(VD) > MaxAlignChars) {
10161 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10162 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10163 << (unsigned)MaxAlignChars.getQuantity();
10168 // Static locals inherit dll attributes from their function.
10169 if (VD->isStaticLocal()) {
10170 if (FunctionDecl *FD =
10171 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10172 if (Attr *A = getDLLAttr(FD)) {
10173 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10174 NewAttr->setInherited(true);
10175 VD->addAttr(NewAttr);
10180 // Grab the dllimport or dllexport attribute off of the VarDecl.
10181 const InheritableAttr *DLLAttr = getDLLAttr(VD);
10183 // Imported static data members cannot be defined out-of-line.
10184 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10185 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10186 VD->isThisDeclarationADefinition()) {
10187 // We allow definitions of dllimport class template static data members
10189 CXXRecordDecl *Context =
10190 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10191 bool IsClassTemplateMember =
10192 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10193 Context->getDescribedClassTemplate();
10195 Diag(VD->getLocation(),
10196 IsClassTemplateMember
10197 ? diag::warn_attribute_dllimport_static_field_definition
10198 : diag::err_attribute_dllimport_static_field_definition);
10199 Diag(IA->getLocation(), diag::note_attribute);
10200 if (!IsClassTemplateMember)
10201 VD->setInvalidDecl();
10205 // dllimport/dllexport variables cannot be thread local, their TLS index
10206 // isn't exported with the variable.
10207 if (DLLAttr && VD->getTLSKind()) {
10208 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10209 if (F && getDLLAttr(F)) {
10210 assert(VD->isStaticLocal());
10211 // But if this is a static local in a dlimport/dllexport function, the
10212 // function will never be inlined, which means the var would never be
10213 // imported, so having it marked import/export is safe.
10215 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10217 VD->setInvalidDecl();
10221 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10222 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10223 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10224 VD->dropAttr<UsedAttr>();
10228 const DeclContext *DC = VD->getDeclContext();
10229 // If there's a #pragma GCC visibility in scope, and this isn't a class
10230 // member, set the visibility of this variable.
10231 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10232 AddPushedVisibilityAttribute(VD);
10234 // FIXME: Warn on unused templates.
10235 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10236 !isa<VarTemplatePartialSpecializationDecl>(VD))
10237 MarkUnusedFileScopedDecl(VD);
10239 // Now we have parsed the initializer and can update the table of magic
10241 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10242 !VD->getType()->isIntegralOrEnumerationType())
10245 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10246 const Expr *MagicValueExpr = VD->getInit();
10247 if (!MagicValueExpr) {
10250 llvm::APSInt MagicValueInt;
10251 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10252 Diag(I->getRange().getBegin(),
10253 diag::err_type_tag_for_datatype_not_ice)
10254 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10257 if (MagicValueInt.getActiveBits() > 64) {
10258 Diag(I->getRange().getBegin(),
10259 diag::err_type_tag_for_datatype_too_large)
10260 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10263 uint64_t MagicValue = MagicValueInt.getZExtValue();
10264 RegisterTypeTagForDatatype(I->getArgumentKind(),
10266 I->getMatchingCType(),
10267 I->getLayoutCompatible(),
10268 I->getMustBeNull());
10272 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10273 ArrayRef<Decl *> Group) {
10274 SmallVector<Decl*, 8> Decls;
10276 if (DS.isTypeSpecOwned())
10277 Decls.push_back(DS.getRepAsDecl());
10279 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10280 for (unsigned i = 0, e = Group.size(); i != e; ++i)
10281 if (Decl *D = Group[i]) {
10282 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10283 if (!FirstDeclaratorInGroup)
10284 FirstDeclaratorInGroup = DD;
10285 Decls.push_back(D);
10288 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10289 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10290 handleTagNumbering(Tag, S);
10291 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10292 getLangOpts().CPlusPlus)
10293 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10297 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10300 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10301 /// group, performing any necessary semantic checking.
10302 Sema::DeclGroupPtrTy
10303 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10304 bool TypeMayContainAuto) {
10305 // C++0x [dcl.spec.auto]p7:
10306 // If the type deduced for the template parameter U is not the same in each
10307 // deduction, the program is ill-formed.
10308 // FIXME: When initializer-list support is added, a distinction is needed
10309 // between the deduced type U and the deduced type which 'auto' stands for.
10310 // auto a = 0, b = { 1, 2, 3 };
10311 // is legal because the deduced type U is 'int' in both cases.
10312 if (TypeMayContainAuto && Group.size() > 1) {
10314 CanQualType DeducedCanon;
10315 VarDecl *DeducedDecl = nullptr;
10316 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10317 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10318 AutoType *AT = D->getType()->getContainedAutoType();
10319 // Don't reissue diagnostics when instantiating a template.
10320 if (AT && D->isInvalidDecl())
10322 QualType U = AT ? AT->getDeducedType() : QualType();
10324 CanQualType UCanon = Context.getCanonicalType(U);
10325 if (Deduced.isNull()) {
10327 DeducedCanon = UCanon;
10329 } else if (DeducedCanon != UCanon) {
10330 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10331 diag::err_auto_different_deductions)
10332 << (unsigned)AT->getKeyword()
10333 << Deduced << DeducedDecl->getDeclName()
10334 << U << D->getDeclName()
10335 << DeducedDecl->getInit()->getSourceRange()
10336 << D->getInit()->getSourceRange();
10337 D->setInvalidDecl();
10345 ActOnDocumentableDecls(Group);
10347 return DeclGroupPtrTy::make(
10348 DeclGroupRef::Create(Context, Group.data(), Group.size()));
10351 void Sema::ActOnDocumentableDecl(Decl *D) {
10352 ActOnDocumentableDecls(D);
10355 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10356 // Don't parse the comment if Doxygen diagnostics are ignored.
10357 if (Group.empty() || !Group[0])
10360 if (Diags.isIgnored(diag::warn_doc_param_not_found,
10361 Group[0]->getLocation()) &&
10362 Diags.isIgnored(diag::warn_unknown_comment_command_name,
10363 Group[0]->getLocation()))
10366 if (Group.size() >= 2) {
10367 // This is a decl group. Normally it will contain only declarations
10368 // produced from declarator list. But in case we have any definitions or
10369 // additional declaration references:
10370 // 'typedef struct S {} S;'
10371 // 'typedef struct S *S;'
10373 // FinalizeDeclaratorGroup adds these as separate declarations.
10374 Decl *MaybeTagDecl = Group[0];
10375 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10376 Group = Group.slice(1);
10380 // See if there are any new comments that are not attached to a decl.
10381 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10382 if (!Comments.empty() &&
10383 !Comments.back()->isAttached()) {
10384 // There is at least one comment that not attached to a decl.
10385 // Maybe it should be attached to one of these decls?
10387 // Note that this way we pick up not only comments that precede the
10388 // declaration, but also comments that *follow* the declaration -- thanks to
10389 // the lookahead in the lexer: we've consumed the semicolon and looked
10390 // ahead through comments.
10391 for (unsigned i = 0, e = Group.size(); i != e; ++i)
10392 Context.getCommentForDecl(Group[i], &PP);
10396 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10397 /// to introduce parameters into function prototype scope.
10398 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10399 const DeclSpec &DS = D.getDeclSpec();
10401 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10403 // C++03 [dcl.stc]p2 also permits 'auto'.
10404 StorageClass SC = SC_None;
10405 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10407 } else if (getLangOpts().CPlusPlus &&
10408 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10410 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10411 Diag(DS.getStorageClassSpecLoc(),
10412 diag::err_invalid_storage_class_in_func_decl);
10413 D.getMutableDeclSpec().ClearStorageClassSpecs();
10416 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10417 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10418 << DeclSpec::getSpecifierName(TSCS);
10419 if (DS.isConstexprSpecified())
10420 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10422 if (DS.isConceptSpecified())
10423 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10425 DiagnoseFunctionSpecifiers(DS);
10427 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10428 QualType parmDeclType = TInfo->getType();
10430 if (getLangOpts().CPlusPlus) {
10431 // Check that there are no default arguments inside the type of this
10433 CheckExtraCXXDefaultArguments(D);
10435 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10436 if (D.getCXXScopeSpec().isSet()) {
10437 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10438 << D.getCXXScopeSpec().getRange();
10439 D.getCXXScopeSpec().clear();
10443 // Ensure we have a valid name
10444 IdentifierInfo *II = nullptr;
10446 II = D.getIdentifier();
10448 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10449 << GetNameForDeclarator(D).getName();
10450 D.setInvalidType(true);
10454 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10456 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10459 if (R.isSingleResult()) {
10460 NamedDecl *PrevDecl = R.getFoundDecl();
10461 if (PrevDecl->isTemplateParameter()) {
10462 // Maybe we will complain about the shadowed template parameter.
10463 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10464 // Just pretend that we didn't see the previous declaration.
10465 PrevDecl = nullptr;
10466 } else if (S->isDeclScope(PrevDecl)) {
10467 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10468 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10470 // Recover by removing the name
10472 D.SetIdentifier(nullptr, D.getIdentifierLoc());
10473 D.setInvalidType(true);
10478 // Temporarily put parameter variables in the translation unit, not
10479 // the enclosing context. This prevents them from accidentally
10480 // looking like class members in C++.
10481 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10483 D.getIdentifierLoc(), II,
10484 parmDeclType, TInfo,
10487 if (D.isInvalidType())
10488 New->setInvalidDecl();
10490 assert(S->isFunctionPrototypeScope());
10491 assert(S->getFunctionPrototypeDepth() >= 1);
10492 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10493 S->getNextFunctionPrototypeIndex());
10495 // Add the parameter declaration into this scope.
10498 IdResolver.AddDecl(New);
10500 ProcessDeclAttributes(S, New, D);
10502 if (D.getDeclSpec().isModulePrivateSpecified())
10503 Diag(New->getLocation(), diag::err_module_private_local)
10504 << 1 << New->getDeclName()
10505 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10506 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10508 if (New->hasAttr<BlocksAttr>()) {
10509 Diag(New->getLocation(), diag::err_block_on_nonlocal);
10514 /// \brief Synthesizes a variable for a parameter arising from a
10516 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10517 SourceLocation Loc,
10519 /* FIXME: setting StartLoc == Loc.
10520 Would it be worth to modify callers so as to provide proper source
10521 location for the unnamed parameters, embedding the parameter's type? */
10522 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10523 T, Context.getTrivialTypeSourceInfo(T, Loc),
10525 Param->setImplicit();
10529 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10530 ParmVarDecl * const *ParamEnd) {
10531 // Don't diagnose unused-parameter errors in template instantiations; we
10532 // will already have done so in the template itself.
10533 if (!ActiveTemplateInstantiations.empty())
10536 for (; Param != ParamEnd; ++Param) {
10537 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10538 !(*Param)->hasAttr<UnusedAttr>()) {
10539 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10540 << (*Param)->getDeclName();
10545 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10546 ParmVarDecl * const *ParamEnd,
10549 if (LangOpts.NumLargeByValueCopy == 0) // No check.
10552 // Warn if the return value is pass-by-value and larger than the specified
10554 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10555 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10556 if (Size > LangOpts.NumLargeByValueCopy)
10557 Diag(D->getLocation(), diag::warn_return_value_size)
10558 << D->getDeclName() << Size;
10561 // Warn if any parameter is pass-by-value and larger than the specified
10563 for (; Param != ParamEnd; ++Param) {
10564 QualType T = (*Param)->getType();
10565 if (T->isDependentType() || !T.isPODType(Context))
10567 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10568 if (Size > LangOpts.NumLargeByValueCopy)
10569 Diag((*Param)->getLocation(), diag::warn_parameter_size)
10570 << (*Param)->getDeclName() << Size;
10574 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10575 SourceLocation NameLoc, IdentifierInfo *Name,
10576 QualType T, TypeSourceInfo *TSInfo,
10578 // In ARC, infer a lifetime qualifier for appropriate parameter types.
10579 if (getLangOpts().ObjCAutoRefCount &&
10580 T.getObjCLifetime() == Qualifiers::OCL_None &&
10581 T->isObjCLifetimeType()) {
10583 Qualifiers::ObjCLifetime lifetime;
10585 // Special cases for arrays:
10586 // - if it's const, use __unsafe_unretained
10587 // - otherwise, it's an error
10588 if (T->isArrayType()) {
10589 if (!T.isConstQualified()) {
10590 DelayedDiagnostics.add(
10591 sema::DelayedDiagnostic::makeForbiddenType(
10592 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10594 lifetime = Qualifiers::OCL_ExplicitNone;
10596 lifetime = T->getObjCARCImplicitLifetime();
10598 T = Context.getLifetimeQualifiedType(T, lifetime);
10601 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10602 Context.getAdjustedParameterType(T),
10603 TSInfo, SC, nullptr);
10605 // Parameters can not be abstract class types.
10606 // For record types, this is done by the AbstractClassUsageDiagnoser once
10607 // the class has been completely parsed.
10608 if (!CurContext->isRecord() &&
10609 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10610 AbstractParamType))
10611 New->setInvalidDecl();
10613 // Parameter declarators cannot be interface types. All ObjC objects are
10614 // passed by reference.
10615 if (T->isObjCObjectType()) {
10616 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10618 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10619 << FixItHint::CreateInsertion(TypeEndLoc, "*");
10620 T = Context.getObjCObjectPointerType(T);
10624 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10625 // duration shall not be qualified by an address-space qualifier."
10626 // Since all parameters have automatic store duration, they can not have
10627 // an address space.
10628 if (T.getAddressSpace() != 0) {
10629 // OpenCL allows function arguments declared to be an array of a type
10630 // to be qualified with an address space.
10631 if (!(getLangOpts().OpenCL && T->isArrayType())) {
10632 Diag(NameLoc, diag::err_arg_with_address_space);
10633 New->setInvalidDecl();
10640 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10641 SourceLocation LocAfterDecls) {
10642 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10644 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10645 // for a K&R function.
10646 if (!FTI.hasPrototype) {
10647 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10649 if (FTI.Params[i].Param == nullptr) {
10650 SmallString<256> Code;
10651 llvm::raw_svector_ostream(Code)
10652 << " int " << FTI.Params[i].Ident->getName() << ";\n";
10653 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10654 << FTI.Params[i].Ident
10655 << FixItHint::CreateInsertion(LocAfterDecls, Code);
10657 // Implicitly declare the argument as type 'int' for lack of a better
10659 AttributeFactory attrs;
10660 DeclSpec DS(attrs);
10661 const char* PrevSpec; // unused
10662 unsigned DiagID; // unused
10663 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10664 DiagID, Context.getPrintingPolicy());
10665 // Use the identifier location for the type source range.
10666 DS.SetRangeStart(FTI.Params[i].IdentLoc);
10667 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10668 Declarator ParamD(DS, Declarator::KNRTypeListContext);
10669 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10670 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10677 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10678 MultiTemplateParamsArg TemplateParameterLists,
10679 SkipBodyInfo *SkipBody) {
10680 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10681 assert(D.isFunctionDeclarator() && "Not a function declarator!");
10682 Scope *ParentScope = FnBodyScope->getParent();
10684 D.setFunctionDefinitionKind(FDK_Definition);
10685 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10686 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10689 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10690 Consumer.HandleInlineMethodDefinition(D);
10693 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10694 const FunctionDecl*& PossibleZeroParamPrototype) {
10695 // Don't warn about invalid declarations.
10696 if (FD->isInvalidDecl())
10699 // Or declarations that aren't global.
10700 if (!FD->isGlobal())
10703 // Don't warn about C++ member functions.
10704 if (isa<CXXMethodDecl>(FD))
10707 // Don't warn about 'main'.
10711 // Don't warn about inline functions.
10712 if (FD->isInlined())
10715 // Don't warn about function templates.
10716 if (FD->getDescribedFunctionTemplate())
10719 // Don't warn about function template specializations.
10720 if (FD->isFunctionTemplateSpecialization())
10723 // Don't warn for OpenCL kernels.
10724 if (FD->hasAttr<OpenCLKernelAttr>())
10727 // Don't warn on explicitly deleted functions.
10728 if (FD->isDeleted())
10731 bool MissingPrototype = true;
10732 for (const FunctionDecl *Prev = FD->getPreviousDecl();
10733 Prev; Prev = Prev->getPreviousDecl()) {
10734 // Ignore any declarations that occur in function or method
10735 // scope, because they aren't visible from the header.
10736 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10739 MissingPrototype = !Prev->getType()->isFunctionProtoType();
10740 if (FD->getNumParams() == 0)
10741 PossibleZeroParamPrototype = Prev;
10745 return MissingPrototype;
10749 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10750 const FunctionDecl *EffectiveDefinition,
10751 SkipBodyInfo *SkipBody) {
10752 // Don't complain if we're in GNU89 mode and the previous definition
10753 // was an extern inline function.
10754 const FunctionDecl *Definition = EffectiveDefinition;
10756 if (!FD->isDefined(Definition))
10759 if (canRedefineFunction(Definition, getLangOpts()))
10762 // If we don't have a visible definition of the function, and it's inline or
10763 // a template, skip the new definition.
10764 if (SkipBody && !hasVisibleDefinition(Definition) &&
10765 (Definition->getFormalLinkage() == InternalLinkage ||
10766 Definition->isInlined() ||
10767 Definition->getDescribedFunctionTemplate() ||
10768 Definition->getNumTemplateParameterLists())) {
10769 SkipBody->ShouldSkip = true;
10770 if (auto *TD = Definition->getDescribedFunctionTemplate())
10771 makeMergedDefinitionVisible(TD, FD->getLocation());
10773 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
10774 FD->getLocation());
10778 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10779 Definition->getStorageClass() == SC_Extern)
10780 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10781 << FD->getDeclName() << getLangOpts().CPlusPlus;
10783 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10785 Diag(Definition->getLocation(), diag::note_previous_definition);
10786 FD->setInvalidDecl();
10790 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10792 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10794 LambdaScopeInfo *LSI = S.PushLambdaScope();
10795 LSI->CallOperator = CallOperator;
10796 LSI->Lambda = LambdaClass;
10797 LSI->ReturnType = CallOperator->getReturnType();
10798 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10800 if (LCD == LCD_None)
10801 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10802 else if (LCD == LCD_ByCopy)
10803 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10804 else if (LCD == LCD_ByRef)
10805 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10806 DeclarationNameInfo DNI = CallOperator->getNameInfo();
10808 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10809 LSI->Mutable = !CallOperator->isConst();
10811 // Add the captures to the LSI so they can be noted as already
10812 // captured within tryCaptureVar.
10813 auto I = LambdaClass->field_begin();
10814 for (const auto &C : LambdaClass->captures()) {
10815 if (C.capturesVariable()) {
10816 VarDecl *VD = C.getCapturedVar();
10817 if (VD->isInitCapture())
10818 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10819 QualType CaptureType = VD->getType();
10820 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10821 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10822 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10823 /*EllipsisLoc*/C.isPackExpansion()
10824 ? C.getEllipsisLoc() : SourceLocation(),
10825 CaptureType, /*Expr*/ nullptr);
10827 } else if (C.capturesThis()) {
10828 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10829 S.getCurrentThisType(), /*Expr*/ nullptr);
10831 LSI->addVLATypeCapture(C.getLocation(), I->getType());
10837 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
10838 SkipBodyInfo *SkipBody) {
10839 // Clear the last template instantiation error context.
10840 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10844 FunctionDecl *FD = nullptr;
10846 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10847 FD = FunTmpl->getTemplatedDecl();
10849 FD = cast<FunctionDecl>(D);
10851 // See if this is a redefinition.
10852 if (!FD->isLateTemplateParsed()) {
10853 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
10855 // If we're skipping the body, we're done. Don't enter the scope.
10856 if (SkipBody && SkipBody->ShouldSkip)
10860 // If we are instantiating a generic lambda call operator, push
10861 // a LambdaScopeInfo onto the function stack. But use the information
10862 // that's already been calculated (ActOnLambdaExpr) to prime the current
10863 // LambdaScopeInfo.
10864 // When the template operator is being specialized, the LambdaScopeInfo,
10865 // has to be properly restored so that tryCaptureVariable doesn't try
10866 // and capture any new variables. In addition when calculating potential
10867 // captures during transformation of nested lambdas, it is necessary to
10868 // have the LSI properly restored.
10869 if (isGenericLambdaCallOperatorSpecialization(FD)) {
10870 assert(ActiveTemplateInstantiations.size() &&
10871 "There should be an active template instantiation on the stack "
10872 "when instantiating a generic lambda!");
10873 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10876 // Enter a new function scope
10877 PushFunctionScope();
10879 // Builtin functions cannot be defined.
10880 if (unsigned BuiltinID = FD->getBuiltinID()) {
10881 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10882 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10883 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10884 FD->setInvalidDecl();
10888 // The return type of a function definition must be complete
10889 // (C99 6.9.1p3, C++ [dcl.fct]p6).
10890 QualType ResultType = FD->getReturnType();
10891 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10892 !FD->isInvalidDecl() &&
10893 RequireCompleteType(FD->getLocation(), ResultType,
10894 diag::err_func_def_incomplete_result))
10895 FD->setInvalidDecl();
10898 PushDeclContext(FnBodyScope, FD);
10900 // Check the validity of our function parameters
10901 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10902 /*CheckParameterNames=*/true);
10904 // Introduce our parameters into the function scope
10905 for (auto Param : FD->params()) {
10906 Param->setOwningFunction(FD);
10908 // If this has an identifier, add it to the scope stack.
10909 if (Param->getIdentifier() && FnBodyScope) {
10910 CheckShadow(FnBodyScope, Param);
10912 PushOnScopeChains(Param, FnBodyScope);
10916 // If we had any tags defined in the function prototype,
10917 // introduce them into the function scope.
10919 for (ArrayRef<NamedDecl *>::iterator
10920 I = FD->getDeclsInPrototypeScope().begin(),
10921 E = FD->getDeclsInPrototypeScope().end();
10925 // Some of these decls (like enums) may have been pinned to the
10926 // translation unit for lack of a real context earlier. If so, remove
10927 // from the translation unit and reattach to the current context.
10928 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10929 // Is the decl actually in the context?
10930 if (Context.getTranslationUnitDecl()->containsDecl(D))
10931 Context.getTranslationUnitDecl()->removeDecl(D);
10932 // Either way, reassign the lexical decl context to our FunctionDecl.
10933 D->setLexicalDeclContext(CurContext);
10936 // If the decl has a non-null name, make accessible in the current scope.
10937 if (!D->getName().empty())
10938 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10940 // Similarly, dive into enums and fish their constants out, making them
10941 // accessible in this scope.
10942 if (auto *ED = dyn_cast<EnumDecl>(D)) {
10943 for (auto *EI : ED->enumerators())
10944 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10949 // Ensure that the function's exception specification is instantiated.
10950 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10951 ResolveExceptionSpec(D->getLocation(), FPT);
10953 // dllimport cannot be applied to non-inline function definitions.
10954 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10955 !FD->isTemplateInstantiation()) {
10956 assert(!FD->hasAttr<DLLExportAttr>());
10957 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10958 FD->setInvalidDecl();
10961 // We want to attach documentation to original Decl (which might be
10962 // a function template).
10963 ActOnDocumentableDecl(D);
10964 if (getCurLexicalContext()->isObjCContainer() &&
10965 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10966 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10967 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10972 /// \brief Given the set of return statements within a function body,
10973 /// compute the variables that are subject to the named return value
10976 /// Each of the variables that is subject to the named return value
10977 /// optimization will be marked as NRVO variables in the AST, and any
10978 /// return statement that has a marked NRVO variable as its NRVO candidate can
10979 /// use the named return value optimization.
10981 /// This function applies a very simplistic algorithm for NRVO: if every return
10982 /// statement in the scope of a variable has the same NRVO candidate, that
10983 /// candidate is an NRVO variable.
10984 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10985 ReturnStmt **Returns = Scope->Returns.data();
10987 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10988 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10989 if (!NRVOCandidate->isNRVOVariable())
10990 Returns[I]->setNRVOCandidate(nullptr);
10995 bool Sema::canDelayFunctionBody(const Declarator &D) {
10996 // We can't delay parsing the body of a constexpr function template (yet).
10997 if (D.getDeclSpec().isConstexprSpecified())
11000 // We can't delay parsing the body of a function template with a deduced
11001 // return type (yet).
11002 if (D.getDeclSpec().containsPlaceholderType()) {
11003 // If the placeholder introduces a non-deduced trailing return type,
11004 // we can still delay parsing it.
11005 if (D.getNumTypeObjects()) {
11006 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11007 if (Outer.Kind == DeclaratorChunk::Function &&
11008 Outer.Fun.hasTrailingReturnType()) {
11009 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11010 return Ty.isNull() || !Ty->isUndeducedType();
11019 bool Sema::canSkipFunctionBody(Decl *D) {
11020 // We cannot skip the body of a function (or function template) which is
11021 // constexpr, since we may need to evaluate its body in order to parse the
11022 // rest of the file.
11023 // We cannot skip the body of a function with an undeduced return type,
11024 // because any callers of that function need to know the type.
11025 if (const FunctionDecl *FD = D->getAsFunction())
11026 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11028 return Consumer.shouldSkipFunctionBody(D);
11031 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11032 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11033 FD->setHasSkippedBody();
11034 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11035 MD->setHasSkippedBody();
11036 return ActOnFinishFunctionBody(Decl, nullptr);
11039 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11040 return ActOnFinishFunctionBody(D, BodyArg, false);
11043 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11044 bool IsInstantiation) {
11045 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11047 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11048 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11050 if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11051 CheckCompletedCoroutineBody(FD, Body);
11056 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
11057 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
11058 // If the function has a deduced result type but contains no 'return'
11059 // statements, the result type as written must be exactly 'auto', and
11060 // the deduced result type is 'void'.
11061 if (!FD->getReturnType()->getAs<AutoType>()) {
11062 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11063 << FD->getReturnType();
11064 FD->setInvalidDecl();
11066 // Substitute 'void' for the 'auto' in the type.
11067 TypeLoc ResultType = getReturnTypeLoc(FD);
11068 Context.adjustDeducedFunctionResultType(
11069 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11071 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11072 auto *LSI = getCurLambda();
11073 if (LSI->HasImplicitReturnType) {
11074 deduceClosureReturnType(*LSI);
11076 // C++11 [expr.prim.lambda]p4:
11077 // [...] if there are no return statements in the compound-statement
11078 // [the deduced type is] the type void
11080 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11082 // Update the return type to the deduced type.
11083 const FunctionProtoType *Proto =
11084 FD->getType()->getAs<FunctionProtoType>();
11085 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11086 Proto->getExtProtoInfo()));
11090 // The only way to be included in UndefinedButUsed is if there is an
11091 // ODR use before the definition. Avoid the expensive map lookup if this
11092 // is the first declaration.
11093 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11094 if (!FD->isExternallyVisible())
11095 UndefinedButUsed.erase(FD);
11096 else if (FD->isInlined() &&
11097 !LangOpts.GNUInline &&
11098 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11099 UndefinedButUsed.erase(FD);
11102 // If the function implicitly returns zero (like 'main') or is naked,
11103 // don't complain about missing return statements.
11104 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11105 WP.disableCheckFallThrough();
11107 // MSVC permits the use of pure specifier (=0) on function definition,
11108 // defined at class scope, warn about this non-standard construct.
11109 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11110 Diag(FD->getLocation(), diag::ext_pure_function_definition);
11112 if (!FD->isInvalidDecl()) {
11113 // Don't diagnose unused parameters of defaulted or deleted functions.
11114 if (!FD->isDeleted() && !FD->isDefaulted())
11115 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11116 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11117 FD->getReturnType(), FD);
11119 // If this is a structor, we need a vtable.
11120 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11121 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11122 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11123 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11125 // Try to apply the named return value optimization. We have to check
11126 // if we can do this here because lambdas keep return statements around
11127 // to deduce an implicit return type.
11128 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11129 !FD->isDependentContext())
11130 computeNRVO(Body, getCurFunction());
11133 // GNU warning -Wmissing-prototypes:
11134 // Warn if a global function is defined without a previous
11135 // prototype declaration. This warning is issued even if the
11136 // definition itself provides a prototype. The aim is to detect
11137 // global functions that fail to be declared in header files.
11138 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11139 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11140 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11142 if (PossibleZeroParamPrototype) {
11143 // We found a declaration that is not a prototype,
11144 // but that could be a zero-parameter prototype
11145 if (TypeSourceInfo *TI =
11146 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11147 TypeLoc TL = TI->getTypeLoc();
11148 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11149 Diag(PossibleZeroParamPrototype->getLocation(),
11150 diag::note_declaration_not_a_prototype)
11151 << PossibleZeroParamPrototype
11152 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11157 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11158 const CXXMethodDecl *KeyFunction;
11159 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11161 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11162 MD == KeyFunction->getCanonicalDecl()) {
11163 // Update the key-function state if necessary for this ABI.
11164 if (FD->isInlined() &&
11165 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11166 Context.setNonKeyFunction(MD);
11168 // If the newly-chosen key function is already defined, then we
11169 // need to mark the vtable as used retroactively.
11170 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11171 const FunctionDecl *Definition;
11172 if (KeyFunction && KeyFunction->isDefined(Definition))
11173 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11175 // We just defined they key function; mark the vtable as used.
11176 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11181 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11182 "Function parsing confused");
11183 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11184 assert(MD == getCurMethodDecl() && "Method parsing confused");
11186 if (!MD->isInvalidDecl()) {
11187 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11188 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11189 MD->getReturnType(), MD);
11192 computeNRVO(Body, getCurFunction());
11194 if (getCurFunction()->ObjCShouldCallSuper) {
11195 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11196 << MD->getSelector().getAsString();
11197 getCurFunction()->ObjCShouldCallSuper = false;
11199 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11200 const ObjCMethodDecl *InitMethod = nullptr;
11201 bool isDesignated =
11202 MD->isDesignatedInitializerForTheInterface(&InitMethod);
11203 assert(isDesignated && InitMethod);
11204 (void)isDesignated;
11206 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11207 auto IFace = MD->getClassInterface();
11210 auto SuperD = IFace->getSuperClass();
11213 return SuperD->getIdentifier() ==
11214 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11216 // Don't issue this warning for unavailable inits or direct subclasses
11218 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11219 Diag(MD->getLocation(),
11220 diag::warn_objc_designated_init_missing_super_call);
11221 Diag(InitMethod->getLocation(),
11222 diag::note_objc_designated_init_marked_here);
11224 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11226 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11227 // Don't issue this warning for unavaialable inits.
11228 if (!MD->isUnavailable())
11229 Diag(MD->getLocation(),
11230 diag::warn_objc_secondary_init_missing_init_call);
11231 getCurFunction()->ObjCWarnForNoInitDelegation = false;
11237 assert(!getCurFunction()->ObjCShouldCallSuper &&
11238 "This should only be set for ObjC methods, which should have been "
11239 "handled in the block above.");
11241 // Verify and clean out per-function state.
11242 if (Body && (!FD || !FD->isDefaulted())) {
11243 // C++ constructors that have function-try-blocks can't have return
11244 // statements in the handlers of that block. (C++ [except.handle]p14)
11246 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11247 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11249 // Verify that gotos and switch cases don't jump into scopes illegally.
11250 if (getCurFunction()->NeedsScopeChecking() &&
11251 !PP.isCodeCompletionEnabled())
11252 DiagnoseInvalidJumps(Body);
11254 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11255 if (!Destructor->getParent()->isDependentType())
11256 CheckDestructor(Destructor);
11258 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11259 Destructor->getParent());
11262 // If any errors have occurred, clear out any temporaries that may have
11263 // been leftover. This ensures that these temporaries won't be picked up for
11264 // deletion in some later function.
11265 if (getDiagnostics().hasErrorOccurred() ||
11266 getDiagnostics().getSuppressAllDiagnostics()) {
11267 DiscardCleanupsInEvaluationContext();
11269 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11270 !isa<FunctionTemplateDecl>(dcl)) {
11271 // Since the body is valid, issue any analysis-based warnings that are
11273 ActivePolicy = &WP;
11276 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11277 (!CheckConstexprFunctionDecl(FD) ||
11278 !CheckConstexprFunctionBody(FD, Body)))
11279 FD->setInvalidDecl();
11281 if (FD && FD->hasAttr<NakedAttr>()) {
11282 for (const Stmt *S : Body->children()) {
11283 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11284 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11285 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11286 FD->setInvalidDecl();
11292 assert(ExprCleanupObjects.size() ==
11293 ExprEvalContexts.back().NumCleanupObjects &&
11294 "Leftover temporaries in function");
11295 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11296 assert(MaybeODRUseExprs.empty() &&
11297 "Leftover expressions for odr-use checking");
11300 if (!IsInstantiation)
11303 PopFunctionScopeInfo(ActivePolicy, dcl);
11304 // If any errors have occurred, clear out any temporaries that may have
11305 // been leftover. This ensures that these temporaries won't be picked up for
11306 // deletion in some later function.
11307 if (getDiagnostics().hasErrorOccurred()) {
11308 DiscardCleanupsInEvaluationContext();
11315 /// When we finish delayed parsing of an attribute, we must attach it to the
11317 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11318 ParsedAttributes &Attrs) {
11319 // Always attach attributes to the underlying decl.
11320 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11321 D = TD->getTemplatedDecl();
11322 ProcessDeclAttributeList(S, D, Attrs.getList());
11324 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11325 if (Method->isStatic())
11326 checkThisInStaticMemberFunctionAttributes(Method);
11330 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11331 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11332 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11333 IdentifierInfo &II, Scope *S) {
11334 // Before we produce a declaration for an implicitly defined
11335 // function, see whether there was a locally-scoped declaration of
11336 // this name as a function or variable. If so, use that
11337 // (non-visible) declaration, and complain about it.
11338 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11339 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11340 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11341 return ExternCPrev;
11344 // Extension in C99. Legal in C90, but warn about it.
11346 if (II.getName().startswith("__builtin_"))
11347 diag_id = diag::warn_builtin_unknown;
11348 else if (getLangOpts().C99)
11349 diag_id = diag::ext_implicit_function_decl;
11351 diag_id = diag::warn_implicit_function_decl;
11352 Diag(Loc, diag_id) << &II;
11354 // Because typo correction is expensive, only do it if the implicit
11355 // function declaration is going to be treated as an error.
11356 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11357 TypoCorrection Corrected;
11359 (Corrected = CorrectTypo(
11360 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11361 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11362 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11363 /*ErrorRecovery*/false);
11366 // Set a Declarator for the implicit definition: int foo();
11368 AttributeFactory attrFactory;
11369 DeclSpec DS(attrFactory);
11371 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11372 Context.getPrintingPolicy());
11373 (void)Error; // Silence warning.
11374 assert(!Error && "Error setting up implicit decl!");
11375 SourceLocation NoLoc;
11376 Declarator D(DS, Declarator::BlockContext);
11377 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11378 /*IsAmbiguous=*/false,
11379 /*LParenLoc=*/NoLoc,
11380 /*Params=*/nullptr,
11382 /*EllipsisLoc=*/NoLoc,
11383 /*RParenLoc=*/NoLoc,
11385 /*RefQualifierIsLvalueRef=*/true,
11386 /*RefQualifierLoc=*/NoLoc,
11387 /*ConstQualifierLoc=*/NoLoc,
11388 /*VolatileQualifierLoc=*/NoLoc,
11389 /*RestrictQualifierLoc=*/NoLoc,
11390 /*MutableLoc=*/NoLoc,
11392 /*ESpecRange=*/SourceRange(),
11393 /*Exceptions=*/nullptr,
11394 /*ExceptionRanges=*/nullptr,
11395 /*NumExceptions=*/0,
11396 /*NoexceptExpr=*/nullptr,
11397 /*ExceptionSpecTokens=*/nullptr,
11399 DS.getAttributes(),
11401 D.SetIdentifier(&II, Loc);
11403 // Insert this function into translation-unit scope.
11405 DeclContext *PrevDC = CurContext;
11406 CurContext = Context.getTranslationUnitDecl();
11408 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11411 CurContext = PrevDC;
11413 AddKnownFunctionAttributes(FD);
11418 /// \brief Adds any function attributes that we know a priori based on
11419 /// the declaration of this function.
11421 /// These attributes can apply both to implicitly-declared builtins
11422 /// (like __builtin___printf_chk) or to library-declared functions
11423 /// like NSLog or printf.
11425 /// We need to check for duplicate attributes both here and where user-written
11426 /// attributes are applied to declarations.
11427 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11428 if (FD->isInvalidDecl())
11431 // If this is a built-in function, map its builtin attributes to
11432 // actual attributes.
11433 if (unsigned BuiltinID = FD->getBuiltinID()) {
11434 // Handle printf-formatting attributes.
11435 unsigned FormatIdx;
11437 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11438 if (!FD->hasAttr<FormatAttr>()) {
11439 const char *fmt = "printf";
11440 unsigned int NumParams = FD->getNumParams();
11441 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11442 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11444 FD->addAttr(FormatAttr::CreateImplicit(Context,
11445 &Context.Idents.get(fmt),
11447 HasVAListArg ? 0 : FormatIdx+2,
11448 FD->getLocation()));
11451 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11453 if (!FD->hasAttr<FormatAttr>())
11454 FD->addAttr(FormatAttr::CreateImplicit(Context,
11455 &Context.Idents.get("scanf"),
11457 HasVAListArg ? 0 : FormatIdx+2,
11458 FD->getLocation()));
11461 // Mark const if we don't care about errno and that is the only
11462 // thing preventing the function from being const. This allows
11463 // IRgen to use LLVM intrinsics for such functions.
11464 if (!getLangOpts().MathErrno &&
11465 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11466 if (!FD->hasAttr<ConstAttr>())
11467 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11470 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11471 !FD->hasAttr<ReturnsTwiceAttr>())
11472 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11473 FD->getLocation()));
11474 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11475 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11476 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11477 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11478 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads &&
11479 Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11480 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11481 // Assign appropriate attribute depending on CUDA compilation
11482 // mode and the target builtin belongs to. E.g. during host
11483 // compilation, aux builtins are __device__, the rest are __host__.
11484 if (getLangOpts().CUDAIsDevice !=
11485 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11486 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11488 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11492 IdentifierInfo *Name = FD->getIdentifier();
11495 if ((!getLangOpts().CPlusPlus &&
11496 FD->getDeclContext()->isTranslationUnit()) ||
11497 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11498 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11499 LinkageSpecDecl::lang_c)) {
11500 // Okay: this could be a libc/libm/Objective-C function we know
11505 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11506 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11507 // target-specific builtins, perhaps?
11508 if (!FD->hasAttr<FormatAttr>())
11509 FD->addAttr(FormatAttr::CreateImplicit(Context,
11510 &Context.Idents.get("printf"), 2,
11511 Name->isStr("vasprintf") ? 0 : 3,
11512 FD->getLocation()));
11515 if (Name->isStr("__CFStringMakeConstantString")) {
11516 // We already have a __builtin___CFStringMakeConstantString,
11517 // but builds that use -fno-constant-cfstrings don't go through that.
11518 if (!FD->hasAttr<FormatArgAttr>())
11519 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11520 FD->getLocation()));
11524 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11525 TypeSourceInfo *TInfo) {
11526 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11527 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11530 assert(D.isInvalidType() && "no declarator info for valid type");
11531 TInfo = Context.getTrivialTypeSourceInfo(T);
11534 // Scope manipulation handled by caller.
11535 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11537 D.getIdentifierLoc(),
11541 // Bail out immediately if we have an invalid declaration.
11542 if (D.isInvalidType()) {
11543 NewTD->setInvalidDecl();
11547 if (D.getDeclSpec().isModulePrivateSpecified()) {
11548 if (CurContext->isFunctionOrMethod())
11549 Diag(NewTD->getLocation(), diag::err_module_private_local)
11550 << 2 << NewTD->getDeclName()
11551 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11552 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11554 NewTD->setModulePrivate();
11557 // C++ [dcl.typedef]p8:
11558 // If the typedef declaration defines an unnamed class (or
11559 // enum), the first typedef-name declared by the declaration
11560 // to be that class type (or enum type) is used to denote the
11561 // class type (or enum type) for linkage purposes only.
11562 // We need to check whether the type was declared in the declaration.
11563 switch (D.getDeclSpec().getTypeSpecType()) {
11566 case TST_interface:
11569 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11570 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11582 /// \brief Check that this is a valid underlying type for an enum declaration.
11583 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11584 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11585 QualType T = TI->getType();
11587 if (T->isDependentType())
11590 if (const BuiltinType *BT = T->getAs<BuiltinType>())
11591 if (BT->isInteger())
11594 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11598 /// Check whether this is a valid redeclaration of a previous enumeration.
11599 /// \return true if the redeclaration was invalid.
11600 bool Sema::CheckEnumRedeclaration(
11601 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11602 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11603 bool IsFixed = !EnumUnderlyingTy.isNull();
11605 if (IsScoped != Prev->isScoped()) {
11606 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11607 << Prev->isScoped();
11608 Diag(Prev->getLocation(), diag::note_previous_declaration);
11612 if (IsFixed && Prev->isFixed()) {
11613 if (!EnumUnderlyingTy->isDependentType() &&
11614 !Prev->getIntegerType()->isDependentType() &&
11615 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11616 Prev->getIntegerType())) {
11617 // TODO: Highlight the underlying type of the redeclaration.
11618 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11619 << EnumUnderlyingTy << Prev->getIntegerType();
11620 Diag(Prev->getLocation(), diag::note_previous_declaration)
11621 << Prev->getIntegerTypeRange();
11624 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11626 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11628 } else if (IsFixed != Prev->isFixed()) {
11629 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11630 << Prev->isFixed();
11631 Diag(Prev->getLocation(), diag::note_previous_declaration);
11638 /// \brief Get diagnostic %select index for tag kind for
11639 /// redeclaration diagnostic message.
11640 /// WARNING: Indexes apply to particular diagnostics only!
11642 /// \returns diagnostic %select index.
11643 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11645 case TTK_Struct: return 0;
11646 case TTK_Interface: return 1;
11647 case TTK_Class: return 2;
11648 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11652 /// \brief Determine if tag kind is a class-key compatible with
11653 /// class for redeclaration (class, struct, or __interface).
11655 /// \returns true iff the tag kind is compatible.
11656 static bool isClassCompatTagKind(TagTypeKind Tag)
11658 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11661 /// \brief Determine whether a tag with a given kind is acceptable
11662 /// as a redeclaration of the given tag declaration.
11664 /// \returns true if the new tag kind is acceptable, false otherwise.
11665 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11666 TagTypeKind NewTag, bool isDefinition,
11667 SourceLocation NewTagLoc,
11668 const IdentifierInfo *Name) {
11669 // C++ [dcl.type.elab]p3:
11670 // The class-key or enum keyword present in the
11671 // elaborated-type-specifier shall agree in kind with the
11672 // declaration to which the name in the elaborated-type-specifier
11673 // refers. This rule also applies to the form of
11674 // elaborated-type-specifier that declares a class-name or
11675 // friend class since it can be construed as referring to the
11676 // definition of the class. Thus, in any
11677 // elaborated-type-specifier, the enum keyword shall be used to
11678 // refer to an enumeration (7.2), the union class-key shall be
11679 // used to refer to a union (clause 9), and either the class or
11680 // struct class-key shall be used to refer to a class (clause 9)
11681 // declared using the class or struct class-key.
11682 TagTypeKind OldTag = Previous->getTagKind();
11683 if (!isDefinition || !isClassCompatTagKind(NewTag))
11684 if (OldTag == NewTag)
11687 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11688 // Warn about the struct/class tag mismatch.
11689 bool isTemplate = false;
11690 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11691 isTemplate = Record->getDescribedClassTemplate();
11693 if (!ActiveTemplateInstantiations.empty()) {
11694 // In a template instantiation, do not offer fix-its for tag mismatches
11695 // since they usually mess up the template instead of fixing the problem.
11696 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11697 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11698 << getRedeclDiagFromTagKind(OldTag);
11702 if (isDefinition) {
11703 // On definitions, check previous tags and issue a fix-it for each
11704 // one that doesn't match the current tag.
11705 if (Previous->getDefinition()) {
11706 // Don't suggest fix-its for redefinitions.
11710 bool previousMismatch = false;
11711 for (auto I : Previous->redecls()) {
11712 if (I->getTagKind() != NewTag) {
11713 if (!previousMismatch) {
11714 previousMismatch = true;
11715 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11716 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11717 << getRedeclDiagFromTagKind(I->getTagKind());
11719 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11720 << getRedeclDiagFromTagKind(NewTag)
11721 << FixItHint::CreateReplacement(I->getInnerLocStart(),
11722 TypeWithKeyword::getTagTypeKindName(NewTag));
11728 // Check for a previous definition. If current tag and definition
11729 // are same type, do nothing. If no definition, but disagree with
11730 // with previous tag type, give a warning, but no fix-it.
11731 const TagDecl *Redecl = Previous->getDefinition() ?
11732 Previous->getDefinition() : Previous;
11733 if (Redecl->getTagKind() == NewTag) {
11737 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11738 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11739 << getRedeclDiagFromTagKind(OldTag);
11740 Diag(Redecl->getLocation(), diag::note_previous_use);
11742 // If there is a previous definition, suggest a fix-it.
11743 if (Previous->getDefinition()) {
11744 Diag(NewTagLoc, diag::note_struct_class_suggestion)
11745 << getRedeclDiagFromTagKind(Redecl->getTagKind())
11746 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11747 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11755 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11756 /// from an outer enclosing namespace or file scope inside a friend declaration.
11757 /// This should provide the commented out code in the following snippet:
11761 /// struct Y { friend struct /*N::*/ X; };
11764 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11765 SourceLocation NameLoc) {
11766 // While the decl is in a namespace, do repeated lookup of that name and see
11767 // if we get the same namespace back. If we do not, continue until
11768 // translation unit scope, at which point we have a fully qualified NNS.
11769 SmallVector<IdentifierInfo *, 4> Namespaces;
11770 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11771 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11772 // This tag should be declared in a namespace, which can only be enclosed by
11773 // other namespaces. Bail if there's an anonymous namespace in the chain.
11774 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11775 if (!Namespace || Namespace->isAnonymousNamespace())
11776 return FixItHint();
11777 IdentifierInfo *II = Namespace->getIdentifier();
11778 Namespaces.push_back(II);
11779 NamedDecl *Lookup = SemaRef.LookupSingleName(
11780 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11781 if (Lookup == Namespace)
11785 // Once we have all the namespaces, reverse them to go outermost first, and
11787 SmallString<64> Insertion;
11788 llvm::raw_svector_ostream OS(Insertion);
11789 if (DC->isTranslationUnit())
11791 std::reverse(Namespaces.begin(), Namespaces.end());
11792 for (auto *II : Namespaces)
11793 OS << II->getName() << "::";
11794 return FixItHint::CreateInsertion(NameLoc, Insertion);
11797 /// \brief Determine whether a tag originally declared in context \p OldDC can
11798 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
11799 /// found a declaration in \p OldDC as a previous decl, perhaps through a
11800 /// using-declaration).
11801 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
11802 DeclContext *NewDC) {
11803 OldDC = OldDC->getRedeclContext();
11804 NewDC = NewDC->getRedeclContext();
11806 if (OldDC->Equals(NewDC))
11809 // In MSVC mode, we allow a redeclaration if the contexts are related (either
11810 // encloses the other).
11811 if (S.getLangOpts().MSVCCompat &&
11812 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
11818 /// Find the DeclContext in which a tag is implicitly declared if we see an
11819 /// elaborated type specifier in the specified context, and lookup finds
11821 static DeclContext *getTagInjectionContext(DeclContext *DC) {
11822 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
11823 DC = DC->getParent();
11827 /// Find the Scope in which a tag is implicitly declared if we see an
11828 /// elaborated type specifier in the specified context, and lookup finds
11830 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
11831 while (S->isClassScope() ||
11832 (LangOpts.CPlusPlus &&
11833 S->isFunctionPrototypeScope()) ||
11834 ((S->getFlags() & Scope::DeclScope) == 0) ||
11835 (S->getEntity() && S->getEntity()->isTransparentContext()))
11836 S = S->getParent();
11840 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
11841 /// former case, Name will be non-null. In the later case, Name will be null.
11842 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11843 /// reference/declaration/definition of a tag.
11845 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
11846 /// trailing-type-specifier) other than one in an alias-declaration.
11848 /// \param SkipBody If non-null, will be set to indicate if the caller should
11849 /// skip the definition of this tag and treat it as if it were a declaration.
11850 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11851 SourceLocation KWLoc, CXXScopeSpec &SS,
11852 IdentifierInfo *Name, SourceLocation NameLoc,
11853 AttributeList *Attr, AccessSpecifier AS,
11854 SourceLocation ModulePrivateLoc,
11855 MultiTemplateParamsArg TemplateParameterLists,
11856 bool &OwnedDecl, bool &IsDependent,
11857 SourceLocation ScopedEnumKWLoc,
11858 bool ScopedEnumUsesClassTag,
11859 TypeResult UnderlyingType,
11860 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
11861 // If this is not a definition, it must have a name.
11862 IdentifierInfo *OrigName = Name;
11863 assert((Name != nullptr || TUK == TUK_Definition) &&
11864 "Nameless record must be a definition!");
11865 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11868 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11869 bool ScopedEnum = ScopedEnumKWLoc.isValid();
11871 // FIXME: Check explicit specializations more carefully.
11872 bool isExplicitSpecialization = false;
11873 bool Invalid = false;
11875 // We only need to do this matching if we have template parameters
11876 // or a scope specifier, which also conveniently avoids this work
11877 // for non-C++ cases.
11878 if (TemplateParameterLists.size() > 0 ||
11879 (SS.isNotEmpty() && TUK != TUK_Reference)) {
11880 if (TemplateParameterList *TemplateParams =
11881 MatchTemplateParametersToScopeSpecifier(
11882 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11883 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11884 if (Kind == TTK_Enum) {
11885 Diag(KWLoc, diag::err_enum_template);
11889 if (TemplateParams->size() > 0) {
11890 // This is a declaration or definition of a class template (which may
11891 // be a member of another template).
11897 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11898 SS, Name, NameLoc, Attr,
11899 TemplateParams, AS,
11901 /*FriendLoc*/SourceLocation(),
11902 TemplateParameterLists.size()-1,
11903 TemplateParameterLists.data(),
11905 return Result.get();
11907 // The "template<>" header is extraneous.
11908 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11909 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11910 isExplicitSpecialization = true;
11915 // Figure out the underlying type if this a enum declaration. We need to do
11916 // this early, because it's needed to detect if this is an incompatible
11918 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11919 bool EnumUnderlyingIsImplicit = false;
11921 if (Kind == TTK_Enum) {
11922 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11923 // No underlying type explicitly specified, or we failed to parse the
11924 // type, default to int.
11925 EnumUnderlying = Context.IntTy.getTypePtr();
11926 else if (UnderlyingType.get()) {
11927 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11928 // integral type; any cv-qualification is ignored.
11929 TypeSourceInfo *TI = nullptr;
11930 GetTypeFromParser(UnderlyingType.get(), &TI);
11931 EnumUnderlying = TI;
11933 if (CheckEnumUnderlyingType(TI))
11934 // Recover by falling back to int.
11935 EnumUnderlying = Context.IntTy.getTypePtr();
11937 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11938 UPPC_FixedUnderlyingType))
11939 EnumUnderlying = Context.IntTy.getTypePtr();
11941 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11942 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
11943 // Microsoft enums are always of int type.
11944 EnumUnderlying = Context.IntTy.getTypePtr();
11945 EnumUnderlyingIsImplicit = true;
11950 DeclContext *SearchDC = CurContext;
11951 DeclContext *DC = CurContext;
11952 bool isStdBadAlloc = false;
11954 RedeclarationKind Redecl = ForRedeclaration;
11955 if (TUK == TUK_Friend || TUK == TUK_Reference)
11956 Redecl = NotForRedeclaration;
11958 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11959 if (Name && SS.isNotEmpty()) {
11960 // We have a nested-name tag ('struct foo::bar').
11962 // Check for invalid 'foo::'.
11963 if (SS.isInvalid()) {
11965 goto CreateNewDecl;
11968 // If this is a friend or a reference to a class in a dependent
11969 // context, don't try to make a decl for it.
11970 if (TUK == TUK_Friend || TUK == TUK_Reference) {
11971 DC = computeDeclContext(SS, false);
11973 IsDependent = true;
11977 DC = computeDeclContext(SS, true);
11979 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11985 if (RequireCompleteDeclContext(SS, DC))
11989 // Look-up name inside 'foo::'.
11990 LookupQualifiedName(Previous, DC);
11992 if (Previous.isAmbiguous())
11995 if (Previous.empty()) {
11996 // Name lookup did not find anything. However, if the
11997 // nested-name-specifier refers to the current instantiation,
11998 // and that current instantiation has any dependent base
11999 // classes, we might find something at instantiation time: treat
12000 // this as a dependent elaborated-type-specifier.
12001 // But this only makes any sense for reference-like lookups.
12002 if (Previous.wasNotFoundInCurrentInstantiation() &&
12003 (TUK == TUK_Reference || TUK == TUK_Friend)) {
12004 IsDependent = true;
12008 // A tag 'foo::bar' must already exist.
12009 Diag(NameLoc, diag::err_not_tag_in_scope)
12010 << Kind << Name << DC << SS.getRange();
12013 goto CreateNewDecl;
12016 // C++14 [class.mem]p14:
12017 // If T is the name of a class, then each of the following shall have a
12018 // name different from T:
12019 // -- every member of class T that is itself a type
12020 if (TUK != TUK_Reference && TUK != TUK_Friend &&
12021 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12024 // If this is a named struct, check to see if there was a previous forward
12025 // declaration or definition.
12026 // FIXME: We're looking into outer scopes here, even when we
12027 // shouldn't be. Doing so can result in ambiguities that we
12028 // shouldn't be diagnosing.
12029 LookupName(Previous, S);
12031 // When declaring or defining a tag, ignore ambiguities introduced
12032 // by types using'ed into this scope.
12033 if (Previous.isAmbiguous() &&
12034 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12035 LookupResult::Filter F = Previous.makeFilter();
12036 while (F.hasNext()) {
12037 NamedDecl *ND = F.next();
12038 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
12044 // C++11 [namespace.memdef]p3:
12045 // If the name in a friend declaration is neither qualified nor
12046 // a template-id and the declaration is a function or an
12047 // elaborated-type-specifier, the lookup to determine whether
12048 // the entity has been previously declared shall not consider
12049 // any scopes outside the innermost enclosing namespace.
12051 // MSVC doesn't implement the above rule for types, so a friend tag
12052 // declaration may be a redeclaration of a type declared in an enclosing
12053 // scope. They do implement this rule for friend functions.
12055 // Does it matter that this should be by scope instead of by
12056 // semantic context?
12057 if (!Previous.empty() && TUK == TUK_Friend) {
12058 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12059 LookupResult::Filter F = Previous.makeFilter();
12060 bool FriendSawTagOutsideEnclosingNamespace = false;
12061 while (F.hasNext()) {
12062 NamedDecl *ND = F.next();
12063 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12064 if (DC->isFileContext() &&
12065 !EnclosingNS->Encloses(ND->getDeclContext())) {
12066 if (getLangOpts().MSVCCompat)
12067 FriendSawTagOutsideEnclosingNamespace = true;
12074 // Diagnose this MSVC extension in the easy case where lookup would have
12075 // unambiguously found something outside the enclosing namespace.
12076 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12077 NamedDecl *ND = Previous.getFoundDecl();
12078 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12079 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12083 // Note: there used to be some attempt at recovery here.
12084 if (Previous.isAmbiguous())
12087 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12088 // FIXME: This makes sure that we ignore the contexts associated
12089 // with C structs, unions, and enums when looking for a matching
12090 // tag declaration or definition. See the similar lookup tweak
12091 // in Sema::LookupName; is there a better way to deal with this?
12092 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12093 SearchDC = SearchDC->getParent();
12097 if (Previous.isSingleResult() &&
12098 Previous.getFoundDecl()->isTemplateParameter()) {
12099 // Maybe we will complain about the shadowed template parameter.
12100 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12101 // Just pretend that we didn't see the previous declaration.
12105 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12106 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12107 // This is a declaration of or a reference to "std::bad_alloc".
12108 isStdBadAlloc = true;
12110 if (Previous.empty() && StdBadAlloc) {
12111 // std::bad_alloc has been implicitly declared (but made invisible to
12112 // name lookup). Fill in this implicit declaration as the previous
12113 // declaration, so that the declarations get chained appropriately.
12114 Previous.addDecl(getStdBadAlloc());
12118 // If we didn't find a previous declaration, and this is a reference
12119 // (or friend reference), move to the correct scope. In C++, we
12120 // also need to do a redeclaration lookup there, just in case
12121 // there's a shadow friend decl.
12122 if (Name && Previous.empty() &&
12123 (TUK == TUK_Reference || TUK == TUK_Friend)) {
12124 if (Invalid) goto CreateNewDecl;
12125 assert(SS.isEmpty());
12127 if (TUK == TUK_Reference) {
12128 // C++ [basic.scope.pdecl]p5:
12129 // -- for an elaborated-type-specifier of the form
12131 // class-key identifier
12133 // if the elaborated-type-specifier is used in the
12134 // decl-specifier-seq or parameter-declaration-clause of a
12135 // function defined in namespace scope, the identifier is
12136 // declared as a class-name in the namespace that contains
12137 // the declaration; otherwise, except as a friend
12138 // declaration, the identifier is declared in the smallest
12139 // non-class, non-function-prototype scope that contains the
12142 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12143 // C structs and unions.
12145 // It is an error in C++ to declare (rather than define) an enum
12146 // type, including via an elaborated type specifier. We'll
12147 // diagnose that later; for now, declare the enum in the same
12148 // scope as we would have picked for any other tag type.
12150 // GNU C also supports this behavior as part of its incomplete
12151 // enum types extension, while GNU C++ does not.
12153 // Find the context where we'll be declaring the tag.
12154 // FIXME: We would like to maintain the current DeclContext as the
12155 // lexical context,
12156 SearchDC = getTagInjectionContext(SearchDC);
12158 // Find the scope where we'll be declaring the tag.
12159 S = getTagInjectionScope(S, getLangOpts());
12161 assert(TUK == TUK_Friend);
12162 // C++ [namespace.memdef]p3:
12163 // If a friend declaration in a non-local class first declares a
12164 // class or function, the friend class or function is a member of
12165 // the innermost enclosing namespace.
12166 SearchDC = SearchDC->getEnclosingNamespaceContext();
12169 // In C++, we need to do a redeclaration lookup to properly
12170 // diagnose some problems.
12171 // FIXME: redeclaration lookup is also used (with and without C++) to find a
12172 // hidden declaration so that we don't get ambiguity errors when using a
12173 // type declared by an elaborated-type-specifier. In C that is not correct
12174 // and we should instead merge compatible types found by lookup.
12175 if (getLangOpts().CPlusPlus) {
12176 Previous.setRedeclarationKind(ForRedeclaration);
12177 LookupQualifiedName(Previous, SearchDC);
12179 Previous.setRedeclarationKind(ForRedeclaration);
12180 LookupName(Previous, S);
12184 // If we have a known previous declaration to use, then use it.
12185 if (Previous.empty() && SkipBody && SkipBody->Previous)
12186 Previous.addDecl(SkipBody->Previous);
12188 if (!Previous.empty()) {
12189 NamedDecl *PrevDecl = Previous.getFoundDecl();
12190 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12192 // It's okay to have a tag decl in the same scope as a typedef
12193 // which hides a tag decl in the same scope. Finding this
12194 // insanity with a redeclaration lookup can only actually happen
12197 // This is also okay for elaborated-type-specifiers, which is
12198 // technically forbidden by the current standard but which is
12199 // okay according to the likely resolution of an open issue;
12200 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12201 if (getLangOpts().CPlusPlus) {
12202 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12203 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12204 TagDecl *Tag = TT->getDecl();
12205 if (Tag->getDeclName() == Name &&
12206 Tag->getDeclContext()->getRedeclContext()
12207 ->Equals(TD->getDeclContext()->getRedeclContext())) {
12210 Previous.addDecl(Tag);
12211 Previous.resolveKind();
12217 // If this is a redeclaration of a using shadow declaration, it must
12218 // declare a tag in the same context. In MSVC mode, we allow a
12219 // redefinition if either context is within the other.
12220 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12221 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12222 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12223 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12224 !(OldTag && isAcceptableTagRedeclContext(
12225 *this, OldTag->getDeclContext(), SearchDC))) {
12226 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12227 Diag(Shadow->getTargetDecl()->getLocation(),
12228 diag::note_using_decl_target);
12229 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12231 // Recover by ignoring the old declaration.
12233 goto CreateNewDecl;
12237 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12238 // If this is a use of a previous tag, or if the tag is already declared
12239 // in the same scope (so that the definition/declaration completes or
12240 // rementions the tag), reuse the decl.
12241 if (TUK == TUK_Reference || TUK == TUK_Friend ||
12242 isDeclInScope(DirectPrevDecl, SearchDC, S,
12243 SS.isNotEmpty() || isExplicitSpecialization)) {
12244 // Make sure that this wasn't declared as an enum and now used as a
12245 // struct or something similar.
12246 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12247 TUK == TUK_Definition, KWLoc,
12249 bool SafeToContinue
12250 = (PrevTagDecl->getTagKind() != TTK_Enum &&
12252 if (SafeToContinue)
12253 Diag(KWLoc, diag::err_use_with_wrong_tag)
12255 << FixItHint::CreateReplacement(SourceRange(KWLoc),
12256 PrevTagDecl->getKindName());
12258 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12259 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12261 if (SafeToContinue)
12262 Kind = PrevTagDecl->getTagKind();
12264 // Recover by making this an anonymous redefinition.
12271 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12272 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12274 // If this is an elaborated-type-specifier for a scoped enumeration,
12275 // the 'class' keyword is not necessary and not permitted.
12276 if (TUK == TUK_Reference || TUK == TUK_Friend) {
12278 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12279 << PrevEnum->isScoped()
12280 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12281 return PrevTagDecl;
12284 QualType EnumUnderlyingTy;
12285 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12286 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12287 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12288 EnumUnderlyingTy = QualType(T, 0);
12290 // All conflicts with previous declarations are recovered by
12291 // returning the previous declaration, unless this is a definition,
12292 // in which case we want the caller to bail out.
12293 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12294 ScopedEnum, EnumUnderlyingTy,
12295 EnumUnderlyingIsImplicit, PrevEnum))
12296 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12299 // C++11 [class.mem]p1:
12300 // A member shall not be declared twice in the member-specification,
12301 // except that a nested class or member class template can be declared
12302 // and then later defined.
12303 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12304 S->isDeclScope(PrevDecl)) {
12305 Diag(NameLoc, diag::ext_member_redeclared);
12306 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12310 // If this is a use, just return the declaration we found, unless
12311 // we have attributes.
12312 if (TUK == TUK_Reference || TUK == TUK_Friend) {
12314 // FIXME: Diagnose these attributes. For now, we create a new
12315 // declaration to hold them.
12316 } else if (TUK == TUK_Reference &&
12317 (PrevTagDecl->getFriendObjectKind() ==
12318 Decl::FOK_Undeclared ||
12319 PP.getModuleContainingLocation(
12320 PrevDecl->getLocation()) !=
12321 PP.getModuleContainingLocation(KWLoc)) &&
12323 // This declaration is a reference to an existing entity, but
12324 // has different visibility from that entity: it either makes
12325 // a friend visible or it makes a type visible in a new module.
12326 // In either case, create a new declaration. We only do this if
12327 // the declaration would have meant the same thing if no prior
12328 // declaration were found, that is, if it was found in the same
12329 // scope where we would have injected a declaration.
12330 if (!getTagInjectionContext(CurContext)->getRedeclContext()
12331 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12332 return PrevTagDecl;
12333 // This is in the injected scope, create a new declaration in
12335 S = getTagInjectionScope(S, getLangOpts());
12337 return PrevTagDecl;
12341 // Diagnose attempts to redefine a tag.
12342 if (TUK == TUK_Definition) {
12343 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12344 // If we're defining a specialization and the previous definition
12345 // is from an implicit instantiation, don't emit an error
12346 // here; we'll catch this in the general case below.
12347 bool IsExplicitSpecializationAfterInstantiation = false;
12348 if (isExplicitSpecialization) {
12349 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12350 IsExplicitSpecializationAfterInstantiation =
12351 RD->getTemplateSpecializationKind() !=
12352 TSK_ExplicitSpecialization;
12353 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12354 IsExplicitSpecializationAfterInstantiation =
12355 ED->getTemplateSpecializationKind() !=
12356 TSK_ExplicitSpecialization;
12359 NamedDecl *Hidden = nullptr;
12360 if (SkipBody && getLangOpts().CPlusPlus &&
12361 !hasVisibleDefinition(Def, &Hidden)) {
12362 // There is a definition of this tag, but it is not visible. We
12363 // explicitly make use of C++'s one definition rule here, and
12364 // assume that this definition is identical to the hidden one
12365 // we already have. Make the existing definition visible and
12366 // use it in place of this one.
12367 SkipBody->ShouldSkip = true;
12368 makeMergedDefinitionVisible(Hidden, KWLoc);
12370 } else if (!IsExplicitSpecializationAfterInstantiation) {
12371 // A redeclaration in function prototype scope in C isn't
12372 // visible elsewhere, so merely issue a warning.
12373 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12374 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12376 Diag(NameLoc, diag::err_redefinition) << Name;
12377 Diag(Def->getLocation(), diag::note_previous_definition);
12378 // If this is a redefinition, recover by making this
12379 // struct be anonymous, which will make any later
12380 // references get the previous definition.
12386 // If the type is currently being defined, complain
12387 // about a nested redefinition.
12388 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12389 if (TD->isBeingDefined()) {
12390 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12391 Diag(PrevTagDecl->getLocation(),
12392 diag::note_previous_definition);
12399 // Okay, this is definition of a previously declared or referenced
12400 // tag. We're going to create a new Decl for it.
12403 // Okay, we're going to make a redeclaration. If this is some kind
12404 // of reference, make sure we build the redeclaration in the same DC
12405 // as the original, and ignore the current access specifier.
12406 if (TUK == TUK_Friend || TUK == TUK_Reference) {
12407 SearchDC = PrevTagDecl->getDeclContext();
12411 // If we get here we have (another) forward declaration or we
12412 // have a definition. Just create a new decl.
12415 // If we get here, this is a definition of a new tag type in a nested
12416 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12417 // new decl/type. We set PrevDecl to NULL so that the entities
12418 // have distinct types.
12421 // If we get here, we're going to create a new Decl. If PrevDecl
12422 // is non-NULL, it's a definition of the tag declared by
12423 // PrevDecl. If it's NULL, we have a new definition.
12426 // Otherwise, PrevDecl is not a tag, but was found with tag
12427 // lookup. This is only actually possible in C++, where a few
12428 // things like templates still live in the tag namespace.
12430 // Use a better diagnostic if an elaborated-type-specifier
12431 // found the wrong kind of type on the first
12432 // (non-redeclaration) lookup.
12433 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12434 !Previous.isForRedeclaration()) {
12436 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12437 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12438 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12439 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12440 Diag(PrevDecl->getLocation(), diag::note_declared_at);
12443 // Otherwise, only diagnose if the declaration is in scope.
12444 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12445 SS.isNotEmpty() || isExplicitSpecialization)) {
12448 // Diagnose implicit declarations introduced by elaborated types.
12449 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12451 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12452 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12453 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12454 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12455 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12458 // Otherwise it's a declaration. Call out a particularly common
12460 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12462 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12463 Diag(NameLoc, diag::err_tag_definition_of_typedef)
12464 << Name << Kind << TND->getUnderlyingType();
12465 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12468 // Otherwise, diagnose.
12470 // The tag name clashes with something else in the target scope,
12471 // issue an error and recover by making this tag be anonymous.
12472 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12473 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12478 // The existing declaration isn't relevant to us; we're in a
12479 // new scope, so clear out the previous declaration.
12486 TagDecl *PrevDecl = nullptr;
12487 if (Previous.isSingleResult())
12488 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12490 // If there is an identifier, use the location of the identifier as the
12491 // location of the decl, otherwise use the location of the struct/union
12493 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12495 // Otherwise, create a new declaration. If there is a previous
12496 // declaration of the same entity, the two will be linked via
12500 bool IsForwardReference = false;
12501 if (Kind == TTK_Enum) {
12502 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12503 // enum X { A, B, C } D; D should chain to X.
12504 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12505 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12506 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12507 // If this is an undefined enum, warn.
12508 if (TUK != TUK_Definition && !Invalid) {
12510 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12511 cast<EnumDecl>(New)->isFixed()) {
12512 // C++0x: 7.2p2: opaque-enum-declaration.
12513 // Conflicts are diagnosed above. Do nothing.
12515 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12516 Diag(Loc, diag::ext_forward_ref_enum_def)
12518 Diag(Def->getLocation(), diag::note_previous_definition);
12520 unsigned DiagID = diag::ext_forward_ref_enum;
12521 if (getLangOpts().MSVCCompat)
12522 DiagID = diag::ext_ms_forward_ref_enum;
12523 else if (getLangOpts().CPlusPlus)
12524 DiagID = diag::err_forward_ref_enum;
12527 // If this is a forward-declared reference to an enumeration, make a
12528 // note of it; we won't actually be introducing the declaration into
12529 // the declaration context.
12530 if (TUK == TUK_Reference)
12531 IsForwardReference = true;
12535 if (EnumUnderlying) {
12536 EnumDecl *ED = cast<EnumDecl>(New);
12537 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12538 ED->setIntegerTypeSourceInfo(TI);
12540 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12541 ED->setPromotionType(ED->getIntegerType());
12545 // struct/union/class
12547 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12548 // struct X { int A; } D; D should chain to X.
12549 if (getLangOpts().CPlusPlus) {
12550 // FIXME: Look for a way to use RecordDecl for simple structs.
12551 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12552 cast_or_null<CXXRecordDecl>(PrevDecl));
12554 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12555 StdBadAlloc = cast<CXXRecordDecl>(New);
12557 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12558 cast_or_null<RecordDecl>(PrevDecl));
12561 // C++11 [dcl.type]p3:
12562 // A type-specifier-seq shall not define a class or enumeration [...].
12563 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12564 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12565 << Context.getTagDeclType(New);
12569 // Maybe add qualifier info.
12570 if (SS.isNotEmpty()) {
12572 // If this is either a declaration or a definition, check the
12573 // nested-name-specifier against the current context. We don't do this
12574 // for explicit specializations, because they have similar checking
12575 // (with more specific diagnostics) in the call to
12576 // CheckMemberSpecialization, below.
12577 if (!isExplicitSpecialization &&
12578 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12579 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12582 New->setQualifierInfo(SS.getWithLocInContext(Context));
12583 if (TemplateParameterLists.size() > 0) {
12584 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12591 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12592 // Add alignment attributes if necessary; these attributes are checked when
12593 // the ASTContext lays out the structure.
12595 // It is important for implementing the correct semantics that this
12596 // happen here (in act on tag decl). The #pragma pack stack is
12597 // maintained as a result of parser callbacks which can occur at
12598 // many points during the parsing of a struct declaration (because
12599 // the #pragma tokens are effectively skipped over during the
12600 // parsing of the struct).
12601 if (TUK == TUK_Definition) {
12602 AddAlignmentAttributesForRecord(RD);
12603 AddMsStructLayoutForRecord(RD);
12607 if (ModulePrivateLoc.isValid()) {
12608 if (isExplicitSpecialization)
12609 Diag(New->getLocation(), diag::err_module_private_specialization)
12611 << FixItHint::CreateRemoval(ModulePrivateLoc);
12612 // __module_private__ does not apply to local classes. However, we only
12613 // diagnose this as an error when the declaration specifiers are
12614 // freestanding. Here, we just ignore the __module_private__.
12615 else if (!SearchDC->isFunctionOrMethod())
12616 New->setModulePrivate();
12619 // If this is a specialization of a member class (of a class template),
12620 // check the specialization.
12621 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12624 // If we're declaring or defining a tag in function prototype scope in C,
12625 // note that this type can only be used within the function and add it to
12626 // the list of decls to inject into the function definition scope.
12627 if ((Name || Kind == TTK_Enum) &&
12628 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12629 if (getLangOpts().CPlusPlus) {
12630 // C++ [dcl.fct]p6:
12631 // Types shall not be defined in return or parameter types.
12632 if (TUK == TUK_Definition && !IsTypeSpecifier) {
12633 Diag(Loc, diag::err_type_defined_in_param_type)
12637 } else if (!PrevDecl) {
12638 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12640 DeclsInPrototypeScope.push_back(New);
12644 New->setInvalidDecl();
12647 ProcessDeclAttributeList(S, New, Attr);
12649 // Set the lexical context. If the tag has a C++ scope specifier, the
12650 // lexical context will be different from the semantic context.
12651 New->setLexicalDeclContext(CurContext);
12653 // Mark this as a friend decl if applicable.
12654 // In Microsoft mode, a friend declaration also acts as a forward
12655 // declaration so we always pass true to setObjectOfFriendDecl to make
12656 // the tag name visible.
12657 if (TUK == TUK_Friend)
12658 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12660 // Set the access specifier.
12661 if (!Invalid && SearchDC->isRecord())
12662 SetMemberAccessSpecifier(New, PrevDecl, AS);
12664 if (TUK == TUK_Definition)
12665 New->startDefinition();
12667 // If this has an identifier, add it to the scope stack.
12668 if (TUK == TUK_Friend) {
12669 // We might be replacing an existing declaration in the lookup tables;
12670 // if so, borrow its access specifier.
12672 New->setAccess(PrevDecl->getAccess());
12674 DeclContext *DC = New->getDeclContext()->getRedeclContext();
12675 DC->makeDeclVisibleInContext(New);
12676 if (Name) // can be null along some error paths
12677 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12678 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12680 S = getNonFieldDeclScope(S);
12681 PushOnScopeChains(New, S, !IsForwardReference);
12682 if (IsForwardReference)
12683 SearchDC->makeDeclVisibleInContext(New);
12686 CurContext->addDecl(New);
12689 // If this is the C FILE type, notify the AST context.
12690 if (IdentifierInfo *II = New->getIdentifier())
12691 if (!New->isInvalidDecl() &&
12692 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12694 Context.setFILEDecl(New);
12697 mergeDeclAttributes(New, PrevDecl);
12699 // If there's a #pragma GCC visibility in scope, set the visibility of this
12701 AddPushedVisibilityAttribute(New);
12704 // In C++, don't return an invalid declaration. We can't recover well from
12705 // the cases where we make the type anonymous.
12706 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12709 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12710 AdjustDeclIfTemplate(TagD);
12711 TagDecl *Tag = cast<TagDecl>(TagD);
12713 // Enter the tag context.
12714 PushDeclContext(S, Tag);
12716 ActOnDocumentableDecl(TagD);
12718 // If there's a #pragma GCC visibility in scope, set the visibility of this
12720 AddPushedVisibilityAttribute(Tag);
12723 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12724 assert(isa<ObjCContainerDecl>(IDecl) &&
12725 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12726 DeclContext *OCD = cast<DeclContext>(IDecl);
12727 assert(getContainingDC(OCD) == CurContext &&
12728 "The next DeclContext should be lexically contained in the current one.");
12733 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12734 SourceLocation FinalLoc,
12735 bool IsFinalSpelledSealed,
12736 SourceLocation LBraceLoc) {
12737 AdjustDeclIfTemplate(TagD);
12738 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12740 FieldCollector->StartClass();
12742 if (!Record->getIdentifier())
12745 if (FinalLoc.isValid())
12746 Record->addAttr(new (Context)
12747 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12750 // [...] The class-name is also inserted into the scope of the
12751 // class itself; this is known as the injected-class-name. For
12752 // purposes of access checking, the injected-class-name is treated
12753 // as if it were a public member name.
12754 CXXRecordDecl *InjectedClassName
12755 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12756 Record->getLocStart(), Record->getLocation(),
12757 Record->getIdentifier(),
12758 /*PrevDecl=*/nullptr,
12759 /*DelayTypeCreation=*/true);
12760 Context.getTypeDeclType(InjectedClassName, Record);
12761 InjectedClassName->setImplicit();
12762 InjectedClassName->setAccess(AS_public);
12763 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12764 InjectedClassName->setDescribedClassTemplate(Template);
12765 PushOnScopeChains(InjectedClassName, S);
12766 assert(InjectedClassName->isInjectedClassName() &&
12767 "Broken injected-class-name");
12770 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12771 SourceLocation RBraceLoc) {
12772 AdjustDeclIfTemplate(TagD);
12773 TagDecl *Tag = cast<TagDecl>(TagD);
12774 Tag->setRBraceLoc(RBraceLoc);
12776 // Make sure we "complete" the definition even it is invalid.
12777 if (Tag->isBeingDefined()) {
12778 assert(Tag->isInvalidDecl() && "We should already have completed it");
12779 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12780 RD->completeDefinition();
12783 if (isa<CXXRecordDecl>(Tag))
12784 FieldCollector->FinishClass();
12786 // Exit this scope of this tag's definition.
12789 if (getCurLexicalContext()->isObjCContainer() &&
12790 Tag->getDeclContext()->isFileContext())
12791 Tag->setTopLevelDeclInObjCContainer();
12793 // Notify the consumer that we've defined a tag.
12794 if (!Tag->isInvalidDecl())
12795 Consumer.HandleTagDeclDefinition(Tag);
12798 void Sema::ActOnObjCContainerFinishDefinition() {
12799 // Exit this scope of this interface definition.
12803 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12804 assert(DC == CurContext && "Mismatch of container contexts");
12805 OriginalLexicalContext = DC;
12806 ActOnObjCContainerFinishDefinition();
12809 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12810 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12811 OriginalLexicalContext = nullptr;
12814 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12815 AdjustDeclIfTemplate(TagD);
12816 TagDecl *Tag = cast<TagDecl>(TagD);
12817 Tag->setInvalidDecl();
12819 // Make sure we "complete" the definition even it is invalid.
12820 if (Tag->isBeingDefined()) {
12821 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12822 RD->completeDefinition();
12825 // We're undoing ActOnTagStartDefinition here, not
12826 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12827 // the FieldCollector.
12832 // Note that FieldName may be null for anonymous bitfields.
12833 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12834 IdentifierInfo *FieldName,
12835 QualType FieldTy, bool IsMsStruct,
12836 Expr *BitWidth, bool *ZeroWidth) {
12837 // Default to true; that shouldn't confuse checks for emptiness
12841 // C99 6.7.2.1p4 - verify the field type.
12842 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12843 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12844 // Handle incomplete types with specific error.
12845 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12846 return ExprError();
12848 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12849 << FieldName << FieldTy << BitWidth->getSourceRange();
12850 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12851 << FieldTy << BitWidth->getSourceRange();
12852 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12853 UPPC_BitFieldWidth))
12854 return ExprError();
12856 // If the bit-width is type- or value-dependent, don't try to check
12858 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12861 llvm::APSInt Value;
12862 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12863 if (ICE.isInvalid())
12865 BitWidth = ICE.get();
12867 if (Value != 0 && ZeroWidth)
12868 *ZeroWidth = false;
12870 // Zero-width bitfield is ok for anonymous field.
12871 if (Value == 0 && FieldName)
12872 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12874 if (Value.isSigned() && Value.isNegative()) {
12876 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12877 << FieldName << Value.toString(10);
12878 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12879 << Value.toString(10);
12882 if (!FieldTy->isDependentType()) {
12883 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
12884 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
12885 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
12887 // Over-wide bitfields are an error in C or when using the MSVC bitfield
12889 bool CStdConstraintViolation =
12890 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
12891 bool MSBitfieldViolation =
12892 Value.ugt(TypeStorageSize) &&
12893 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
12894 if (CStdConstraintViolation || MSBitfieldViolation) {
12895 unsigned DiagWidth =
12896 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
12898 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
12899 << FieldName << (unsigned)Value.getZExtValue()
12900 << !CStdConstraintViolation << DiagWidth;
12902 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
12903 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
12907 // Warn on types where the user might conceivably expect to get all
12908 // specified bits as value bits: that's all integral types other than
12910 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
12912 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
12913 << FieldName << (unsigned)Value.getZExtValue()
12914 << (unsigned)TypeWidth;
12916 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
12917 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
12924 /// ActOnField - Each field of a C struct/union is passed into this in order
12925 /// to create a FieldDecl object for it.
12926 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12927 Declarator &D, Expr *BitfieldWidth) {
12928 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12929 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12930 /*InitStyle=*/ICIS_NoInit, AS_public);
12934 /// HandleField - Analyze a field of a C struct or a C++ data member.
12936 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12937 SourceLocation DeclStart,
12938 Declarator &D, Expr *BitWidth,
12939 InClassInitStyle InitStyle,
12940 AccessSpecifier AS) {
12941 IdentifierInfo *II = D.getIdentifier();
12942 SourceLocation Loc = DeclStart;
12943 if (II) Loc = D.getIdentifierLoc();
12945 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12946 QualType T = TInfo->getType();
12947 if (getLangOpts().CPlusPlus) {
12948 CheckExtraCXXDefaultArguments(D);
12950 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12951 UPPC_DataMemberType)) {
12952 D.setInvalidType();
12954 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12958 // TR 18037 does not allow fields to be declared with address spaces.
12959 if (T.getQualifiers().hasAddressSpace()) {
12960 Diag(Loc, diag::err_field_with_address_space);
12961 D.setInvalidType();
12964 // OpenCL 1.2 spec, s6.9 r:
12965 // The event type cannot be used to declare a structure or union field.
12966 if (LangOpts.OpenCL && T->isEventT()) {
12967 Diag(Loc, diag::err_event_t_struct_field);
12968 D.setInvalidType();
12971 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12973 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12974 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12975 diag::err_invalid_thread)
12976 << DeclSpec::getSpecifierName(TSCS);
12978 // Check to see if this name was declared as a member previously
12979 NamedDecl *PrevDecl = nullptr;
12980 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12981 LookupName(Previous, S);
12982 switch (Previous.getResultKind()) {
12983 case LookupResult::Found:
12984 case LookupResult::FoundUnresolvedValue:
12985 PrevDecl = Previous.getAsSingle<NamedDecl>();
12988 case LookupResult::FoundOverloaded:
12989 PrevDecl = Previous.getRepresentativeDecl();
12992 case LookupResult::NotFound:
12993 case LookupResult::NotFoundInCurrentInstantiation:
12994 case LookupResult::Ambiguous:
12997 Previous.suppressDiagnostics();
12999 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13000 // Maybe we will complain about the shadowed template parameter.
13001 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13002 // Just pretend that we didn't see the previous declaration.
13003 PrevDecl = nullptr;
13006 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13007 PrevDecl = nullptr;
13010 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13011 SourceLocation TSSL = D.getLocStart();
13013 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13014 TSSL, AS, PrevDecl, &D);
13016 if (NewFD->isInvalidDecl())
13017 Record->setInvalidDecl();
13019 if (D.getDeclSpec().isModulePrivateSpecified())
13020 NewFD->setModulePrivate();
13022 if (NewFD->isInvalidDecl() && PrevDecl) {
13023 // Don't introduce NewFD into scope; there's already something
13024 // with the same name in the same scope.
13026 PushOnScopeChains(NewFD, S);
13028 Record->addDecl(NewFD);
13033 /// \brief Build a new FieldDecl and check its well-formedness.
13035 /// This routine builds a new FieldDecl given the fields name, type,
13036 /// record, etc. \p PrevDecl should refer to any previous declaration
13037 /// with the same name and in the same scope as the field to be
13040 /// \returns a new FieldDecl.
13042 /// \todo The Declarator argument is a hack. It will be removed once
13043 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13044 TypeSourceInfo *TInfo,
13045 RecordDecl *Record, SourceLocation Loc,
13046 bool Mutable, Expr *BitWidth,
13047 InClassInitStyle InitStyle,
13048 SourceLocation TSSL,
13049 AccessSpecifier AS, NamedDecl *PrevDecl,
13051 IdentifierInfo *II = Name.getAsIdentifierInfo();
13052 bool InvalidDecl = false;
13053 if (D) InvalidDecl = D->isInvalidType();
13055 // If we receive a broken type, recover by assuming 'int' and
13056 // marking this declaration as invalid.
13058 InvalidDecl = true;
13062 QualType EltTy = Context.getBaseElementType(T);
13063 if (!EltTy->isDependentType()) {
13064 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13065 // Fields of incomplete type force their record to be invalid.
13066 Record->setInvalidDecl();
13067 InvalidDecl = true;
13070 EltTy->isIncompleteType(&Def);
13071 if (Def && Def->isInvalidDecl()) {
13072 Record->setInvalidDecl();
13073 InvalidDecl = true;
13078 // OpenCL v1.2 s6.9.c: bitfields are not supported.
13079 if (BitWidth && getLangOpts().OpenCL) {
13080 Diag(Loc, diag::err_opencl_bitfields);
13081 InvalidDecl = true;
13084 // C99 6.7.2.1p8: A member of a structure or union may have any type other
13085 // than a variably modified type.
13086 if (!InvalidDecl && T->isVariablyModifiedType()) {
13087 bool SizeIsNegative;
13088 llvm::APSInt Oversized;
13090 TypeSourceInfo *FixedTInfo =
13091 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13095 Diag(Loc, diag::warn_illegal_constant_array_size);
13096 TInfo = FixedTInfo;
13097 T = FixedTInfo->getType();
13099 if (SizeIsNegative)
13100 Diag(Loc, diag::err_typecheck_negative_array_size);
13101 else if (Oversized.getBoolValue())
13102 Diag(Loc, diag::err_array_too_large)
13103 << Oversized.toString(10);
13105 Diag(Loc, diag::err_typecheck_field_variable_size);
13106 InvalidDecl = true;
13110 // Fields can not have abstract class types
13111 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13112 diag::err_abstract_type_in_decl,
13113 AbstractFieldType))
13114 InvalidDecl = true;
13116 bool ZeroWidth = false;
13118 BitWidth = nullptr;
13119 // If this is declared as a bit-field, check the bit-field.
13121 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13124 InvalidDecl = true;
13125 BitWidth = nullptr;
13130 // Check that 'mutable' is consistent with the type of the declaration.
13131 if (!InvalidDecl && Mutable) {
13132 unsigned DiagID = 0;
13133 if (T->isReferenceType())
13134 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13135 : diag::err_mutable_reference;
13136 else if (T.isConstQualified())
13137 DiagID = diag::err_mutable_const;
13140 SourceLocation ErrLoc = Loc;
13141 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13142 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13143 Diag(ErrLoc, DiagID);
13144 if (DiagID != diag::ext_mutable_reference) {
13146 InvalidDecl = true;
13151 // C++11 [class.union]p8 (DR1460):
13152 // At most one variant member of a union may have a
13153 // brace-or-equal-initializer.
13154 if (InitStyle != ICIS_NoInit)
13155 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13157 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13158 BitWidth, Mutable, InitStyle);
13160 NewFD->setInvalidDecl();
13162 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13163 Diag(Loc, diag::err_duplicate_member) << II;
13164 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13165 NewFD->setInvalidDecl();
13168 if (!InvalidDecl && getLangOpts().CPlusPlus) {
13169 if (Record->isUnion()) {
13170 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13171 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13172 if (RDecl->getDefinition()) {
13173 // C++ [class.union]p1: An object of a class with a non-trivial
13174 // constructor, a non-trivial copy constructor, a non-trivial
13175 // destructor, or a non-trivial copy assignment operator
13176 // cannot be a member of a union, nor can an array of such
13178 if (CheckNontrivialField(NewFD))
13179 NewFD->setInvalidDecl();
13183 // C++ [class.union]p1: If a union contains a member of reference type,
13184 // the program is ill-formed, except when compiling with MSVC extensions
13186 if (EltTy->isReferenceType()) {
13187 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13188 diag::ext_union_member_of_reference_type :
13189 diag::err_union_member_of_reference_type)
13190 << NewFD->getDeclName() << EltTy;
13191 if (!getLangOpts().MicrosoftExt)
13192 NewFD->setInvalidDecl();
13197 // FIXME: We need to pass in the attributes given an AST
13198 // representation, not a parser representation.
13200 // FIXME: The current scope is almost... but not entirely... correct here.
13201 ProcessDeclAttributes(getCurScope(), NewFD, *D);
13203 if (NewFD->hasAttrs())
13204 CheckAlignasUnderalignment(NewFD);
13207 // In auto-retain/release, infer strong retension for fields of
13208 // retainable type.
13209 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13210 NewFD->setInvalidDecl();
13212 if (T.isObjCGCWeak())
13213 Diag(Loc, diag::warn_attribute_weak_on_field);
13215 NewFD->setAccess(AS);
13219 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13221 assert(getLangOpts().CPlusPlus && "valid check only for C++");
13223 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13226 QualType EltTy = Context.getBaseElementType(FD->getType());
13227 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13228 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13229 if (RDecl->getDefinition()) {
13230 // We check for copy constructors before constructors
13231 // because otherwise we'll never get complaints about
13232 // copy constructors.
13234 CXXSpecialMember member = CXXInvalid;
13235 // We're required to check for any non-trivial constructors. Since the
13236 // implicit default constructor is suppressed if there are any
13237 // user-declared constructors, we just need to check that there is a
13238 // trivial default constructor and a trivial copy constructor. (We don't
13239 // worry about move constructors here, since this is a C++98 check.)
13240 if (RDecl->hasNonTrivialCopyConstructor())
13241 member = CXXCopyConstructor;
13242 else if (!RDecl->hasTrivialDefaultConstructor())
13243 member = CXXDefaultConstructor;
13244 else if (RDecl->hasNonTrivialCopyAssignment())
13245 member = CXXCopyAssignment;
13246 else if (RDecl->hasNonTrivialDestructor())
13247 member = CXXDestructor;
13249 if (member != CXXInvalid) {
13250 if (!getLangOpts().CPlusPlus11 &&
13251 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13252 // Objective-C++ ARC: it is an error to have a non-trivial field of
13253 // a union. However, system headers in Objective-C programs
13254 // occasionally have Objective-C lifetime objects within unions,
13255 // and rather than cause the program to fail, we make those
13256 // members unavailable.
13257 SourceLocation Loc = FD->getLocation();
13258 if (getSourceManager().isInSystemHeader(Loc)) {
13259 if (!FD->hasAttr<UnavailableAttr>())
13260 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13261 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13266 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13267 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13268 diag::err_illegal_union_or_anon_struct_member)
13269 << FD->getParent()->isUnion() << FD->getDeclName() << member;
13270 DiagnoseNontrivial(RDecl, member);
13271 return !getLangOpts().CPlusPlus11;
13279 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13280 /// AST enum value.
13281 static ObjCIvarDecl::AccessControl
13282 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13283 switch (ivarVisibility) {
13284 default: llvm_unreachable("Unknown visitibility kind");
13285 case tok::objc_private: return ObjCIvarDecl::Private;
13286 case tok::objc_public: return ObjCIvarDecl::Public;
13287 case tok::objc_protected: return ObjCIvarDecl::Protected;
13288 case tok::objc_package: return ObjCIvarDecl::Package;
13292 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13293 /// in order to create an IvarDecl object for it.
13294 Decl *Sema::ActOnIvar(Scope *S,
13295 SourceLocation DeclStart,
13296 Declarator &D, Expr *BitfieldWidth,
13297 tok::ObjCKeywordKind Visibility) {
13299 IdentifierInfo *II = D.getIdentifier();
13300 Expr *BitWidth = (Expr*)BitfieldWidth;
13301 SourceLocation Loc = DeclStart;
13302 if (II) Loc = D.getIdentifierLoc();
13304 // FIXME: Unnamed fields can be handled in various different ways, for
13305 // example, unnamed unions inject all members into the struct namespace!
13307 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13308 QualType T = TInfo->getType();
13311 // 6.7.2.1p3, 6.7.2.1p4
13312 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13314 D.setInvalidType();
13321 if (T->isReferenceType()) {
13322 Diag(Loc, diag::err_ivar_reference_type);
13323 D.setInvalidType();
13325 // C99 6.7.2.1p8: A member of a structure or union may have any type other
13326 // than a variably modified type.
13327 else if (T->isVariablyModifiedType()) {
13328 Diag(Loc, diag::err_typecheck_ivar_variable_size);
13329 D.setInvalidType();
13332 // Get the visibility (access control) for this ivar.
13333 ObjCIvarDecl::AccessControl ac =
13334 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13335 : ObjCIvarDecl::None;
13336 // Must set ivar's DeclContext to its enclosing interface.
13337 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13338 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13340 ObjCContainerDecl *EnclosingContext;
13341 if (ObjCImplementationDecl *IMPDecl =
13342 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13343 if (LangOpts.ObjCRuntime.isFragile()) {
13344 // Case of ivar declared in an implementation. Context is that of its class.
13345 EnclosingContext = IMPDecl->getClassInterface();
13346 assert(EnclosingContext && "Implementation has no class interface!");
13349 EnclosingContext = EnclosingDecl;
13351 if (ObjCCategoryDecl *CDecl =
13352 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13353 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13354 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13358 EnclosingContext = EnclosingDecl;
13361 // Construct the decl.
13362 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13363 DeclStart, Loc, II, T,
13364 TInfo, ac, (Expr *)BitfieldWidth);
13367 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13369 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13370 && !isa<TagDecl>(PrevDecl)) {
13371 Diag(Loc, diag::err_duplicate_member) << II;
13372 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13373 NewID->setInvalidDecl();
13377 // Process attributes attached to the ivar.
13378 ProcessDeclAttributes(S, NewID, D);
13380 if (D.isInvalidType())
13381 NewID->setInvalidDecl();
13383 // In ARC, infer 'retaining' for ivars of retainable type.
13384 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13385 NewID->setInvalidDecl();
13387 if (D.getDeclSpec().isModulePrivateSpecified())
13388 NewID->setModulePrivate();
13391 // FIXME: When interfaces are DeclContexts, we'll need to add
13392 // these to the interface.
13394 IdResolver.AddDecl(NewID);
13397 if (LangOpts.ObjCRuntime.isNonFragile() &&
13398 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13399 Diag(Loc, diag::warn_ivars_in_interface);
13404 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13405 /// class and class extensions. For every class \@interface and class
13406 /// extension \@interface, if the last ivar is a bitfield of any type,
13407 /// then add an implicit `char :0` ivar to the end of that interface.
13408 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13409 SmallVectorImpl<Decl *> &AllIvarDecls) {
13410 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13413 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13414 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13416 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13418 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13420 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13421 if (!CD->IsClassExtension())
13424 // No need to add this to end of @implementation.
13428 // All conditions are met. Add a new bitfield to the tail end of ivars.
13429 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13430 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13432 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13433 DeclLoc, DeclLoc, nullptr,
13435 Context.getTrivialTypeSourceInfo(Context.CharTy,
13437 ObjCIvarDecl::Private, BW,
13439 AllIvarDecls.push_back(Ivar);
13442 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13443 ArrayRef<Decl *> Fields, SourceLocation LBrac,
13444 SourceLocation RBrac, AttributeList *Attr) {
13445 assert(EnclosingDecl && "missing record or interface decl");
13447 // If this is an Objective-C @implementation or category and we have
13448 // new fields here we should reset the layout of the interface since
13449 // it will now change.
13450 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13451 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13452 switch (DC->getKind()) {
13454 case Decl::ObjCCategory:
13455 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13457 case Decl::ObjCImplementation:
13459 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13464 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13466 // Start counting up the number of named members; make sure to include
13467 // members of anonymous structs and unions in the total.
13468 unsigned NumNamedMembers = 0;
13470 for (const auto *I : Record->decls()) {
13471 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13472 if (IFD->getDeclName())
13477 // Verify that all the fields are okay.
13478 SmallVector<FieldDecl*, 32> RecFields;
13480 bool ARCErrReported = false;
13481 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13483 FieldDecl *FD = cast<FieldDecl>(*i);
13485 // Get the type for the field.
13486 const Type *FDTy = FD->getType().getTypePtr();
13488 if (!FD->isAnonymousStructOrUnion()) {
13489 // Remember all fields written by the user.
13490 RecFields.push_back(FD);
13493 // If the field is already invalid for some reason, don't emit more
13494 // diagnostics about it.
13495 if (FD->isInvalidDecl()) {
13496 EnclosingDecl->setInvalidDecl();
13501 // A structure or union shall not contain a member with
13502 // incomplete or function type (hence, a structure shall not
13503 // contain an instance of itself, but may contain a pointer to
13504 // an instance of itself), except that the last member of a
13505 // structure with more than one named member may have incomplete
13506 // array type; such a structure (and any union containing,
13507 // possibly recursively, a member that is such a structure)
13508 // shall not be a member of a structure or an element of an
13510 if (FDTy->isFunctionType()) {
13511 // Field declared as a function.
13512 Diag(FD->getLocation(), diag::err_field_declared_as_function)
13513 << FD->getDeclName();
13514 FD->setInvalidDecl();
13515 EnclosingDecl->setInvalidDecl();
13517 } else if (FDTy->isIncompleteArrayType() && Record &&
13518 ((i + 1 == Fields.end() && !Record->isUnion()) ||
13519 ((getLangOpts().MicrosoftExt ||
13520 getLangOpts().CPlusPlus) &&
13521 (i + 1 == Fields.end() || Record->isUnion())))) {
13522 // Flexible array member.
13523 // Microsoft and g++ is more permissive regarding flexible array.
13524 // It will accept flexible array in union and also
13525 // as the sole element of a struct/class.
13526 unsigned DiagID = 0;
13527 if (Record->isUnion())
13528 DiagID = getLangOpts().MicrosoftExt
13529 ? diag::ext_flexible_array_union_ms
13530 : getLangOpts().CPlusPlus
13531 ? diag::ext_flexible_array_union_gnu
13532 : diag::err_flexible_array_union;
13533 else if (Fields.size() == 1)
13534 DiagID = getLangOpts().MicrosoftExt
13535 ? diag::ext_flexible_array_empty_aggregate_ms
13536 : getLangOpts().CPlusPlus
13537 ? diag::ext_flexible_array_empty_aggregate_gnu
13538 : NumNamedMembers < 1
13539 ? diag::err_flexible_array_empty_aggregate
13543 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13544 << Record->getTagKind();
13545 // While the layout of types that contain virtual bases is not specified
13546 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13547 // virtual bases after the derived members. This would make a flexible
13548 // array member declared at the end of an object not adjacent to the end
13550 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13551 if (RD->getNumVBases() != 0)
13552 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13553 << FD->getDeclName() << Record->getTagKind();
13554 if (!getLangOpts().C99)
13555 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13556 << FD->getDeclName() << Record->getTagKind();
13558 // If the element type has a non-trivial destructor, we would not
13559 // implicitly destroy the elements, so disallow it for now.
13561 // FIXME: GCC allows this. We should probably either implicitly delete
13562 // the destructor of the containing class, or just allow this.
13563 QualType BaseElem = Context.getBaseElementType(FD->getType());
13564 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13565 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13566 << FD->getDeclName() << FD->getType();
13567 FD->setInvalidDecl();
13568 EnclosingDecl->setInvalidDecl();
13571 // Okay, we have a legal flexible array member at the end of the struct.
13572 Record->setHasFlexibleArrayMember(true);
13573 } else if (!FDTy->isDependentType() &&
13574 RequireCompleteType(FD->getLocation(), FD->getType(),
13575 diag::err_field_incomplete)) {
13577 FD->setInvalidDecl();
13578 EnclosingDecl->setInvalidDecl();
13580 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13581 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13582 // A type which contains a flexible array member is considered to be a
13583 // flexible array member.
13584 Record->setHasFlexibleArrayMember(true);
13585 if (!Record->isUnion()) {
13586 // If this is a struct/class and this is not the last element, reject
13587 // it. Note that GCC supports variable sized arrays in the middle of
13589 if (i + 1 != Fields.end())
13590 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13591 << FD->getDeclName() << FD->getType();
13593 // We support flexible arrays at the end of structs in
13594 // other structs as an extension.
13595 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13596 << FD->getDeclName();
13600 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13601 RequireNonAbstractType(FD->getLocation(), FD->getType(),
13602 diag::err_abstract_type_in_decl,
13603 AbstractIvarType)) {
13604 // Ivars can not have abstract class types
13605 FD->setInvalidDecl();
13607 if (Record && FDTTy->getDecl()->hasObjectMember())
13608 Record->setHasObjectMember(true);
13609 if (Record && FDTTy->getDecl()->hasVolatileMember())
13610 Record->setHasVolatileMember(true);
13611 } else if (FDTy->isObjCObjectType()) {
13612 /// A field cannot be an Objective-c object
13613 Diag(FD->getLocation(), diag::err_statically_allocated_object)
13614 << FixItHint::CreateInsertion(FD->getLocation(), "*");
13615 QualType T = Context.getObjCObjectPointerType(FD->getType());
13617 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13618 (!getLangOpts().CPlusPlus || Record->isUnion())) {
13619 // It's an error in ARC if a field has lifetime.
13620 // We don't want to report this in a system header, though,
13621 // so we just make the field unavailable.
13622 // FIXME: that's really not sufficient; we need to make the type
13623 // itself invalid to, say, initialize or copy.
13624 QualType T = FD->getType();
13625 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13626 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13627 SourceLocation loc = FD->getLocation();
13628 if (getSourceManager().isInSystemHeader(loc)) {
13629 if (!FD->hasAttr<UnavailableAttr>()) {
13630 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13631 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13634 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13635 << T->isBlockPointerType() << Record->getTagKind();
13637 ARCErrReported = true;
13639 } else if (getLangOpts().ObjC1 &&
13640 getLangOpts().getGC() != LangOptions::NonGC &&
13641 Record && !Record->hasObjectMember()) {
13642 if (FD->getType()->isObjCObjectPointerType() ||
13643 FD->getType().isObjCGCStrong())
13644 Record->setHasObjectMember(true);
13645 else if (Context.getAsArrayType(FD->getType())) {
13646 QualType BaseType = Context.getBaseElementType(FD->getType());
13647 if (BaseType->isRecordType() &&
13648 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13649 Record->setHasObjectMember(true);
13650 else if (BaseType->isObjCObjectPointerType() ||
13651 BaseType.isObjCGCStrong())
13652 Record->setHasObjectMember(true);
13655 if (Record && FD->getType().isVolatileQualified())
13656 Record->setHasVolatileMember(true);
13657 // Keep track of the number of named members.
13658 if (FD->getIdentifier())
13662 // Okay, we successfully defined 'Record'.
13664 bool Completed = false;
13665 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13666 if (!CXXRecord->isInvalidDecl()) {
13667 // Set access bits correctly on the directly-declared conversions.
13668 for (CXXRecordDecl::conversion_iterator
13669 I = CXXRecord->conversion_begin(),
13670 E = CXXRecord->conversion_end(); I != E; ++I)
13671 I.setAccess((*I)->getAccess());
13673 if (!CXXRecord->isDependentType()) {
13674 if (CXXRecord->hasUserDeclaredDestructor()) {
13675 // Adjust user-defined destructor exception spec.
13676 if (getLangOpts().CPlusPlus11)
13677 AdjustDestructorExceptionSpec(CXXRecord,
13678 CXXRecord->getDestructor());
13681 // Add any implicitly-declared members to this class.
13682 AddImplicitlyDeclaredMembersToClass(CXXRecord);
13684 // If we have virtual base classes, we may end up finding multiple
13685 // final overriders for a given virtual function. Check for this
13687 if (CXXRecord->getNumVBases()) {
13688 CXXFinalOverriderMap FinalOverriders;
13689 CXXRecord->getFinalOverriders(FinalOverriders);
13691 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13692 MEnd = FinalOverriders.end();
13694 for (OverridingMethods::iterator SO = M->second.begin(),
13695 SOEnd = M->second.end();
13696 SO != SOEnd; ++SO) {
13697 assert(SO->second.size() > 0 &&
13698 "Virtual function without overridding functions?");
13699 if (SO->second.size() == 1)
13702 // C++ [class.virtual]p2:
13703 // In a derived class, if a virtual member function of a base
13704 // class subobject has more than one final overrider the
13705 // program is ill-formed.
13706 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13707 << (const NamedDecl *)M->first << Record;
13708 Diag(M->first->getLocation(),
13709 diag::note_overridden_virtual_function);
13710 for (OverridingMethods::overriding_iterator
13711 OM = SO->second.begin(),
13712 OMEnd = SO->second.end();
13714 Diag(OM->Method->getLocation(), diag::note_final_overrider)
13715 << (const NamedDecl *)M->first << OM->Method->getParent();
13717 Record->setInvalidDecl();
13720 CXXRecord->completeDefinition(&FinalOverriders);
13728 Record->completeDefinition();
13730 if (Record->hasAttrs()) {
13731 CheckAlignasUnderalignment(Record);
13733 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13734 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13735 IA->getRange(), IA->getBestCase(),
13736 IA->getSemanticSpelling());
13739 // Check if the structure/union declaration is a type that can have zero
13740 // size in C. For C this is a language extension, for C++ it may cause
13741 // compatibility problems.
13742 bool CheckForZeroSize;
13743 if (!getLangOpts().CPlusPlus) {
13744 CheckForZeroSize = true;
13746 // For C++ filter out types that cannot be referenced in C code.
13747 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13749 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13750 !CXXRecord->isDependentType() &&
13751 CXXRecord->isCLike();
13753 if (CheckForZeroSize) {
13754 bool ZeroSize = true;
13755 bool IsEmpty = true;
13756 unsigned NonBitFields = 0;
13757 for (RecordDecl::field_iterator I = Record->field_begin(),
13758 E = Record->field_end();
13759 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13761 if (I->isUnnamedBitfield()) {
13762 if (I->getBitWidthValue(Context) > 0)
13766 QualType FieldType = I->getType();
13767 if (FieldType->isIncompleteType() ||
13768 !Context.getTypeSizeInChars(FieldType).isZero())
13773 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13774 // allowed in C++, but warn if its declaration is inside
13775 // extern "C" block.
13777 Diag(RecLoc, getLangOpts().CPlusPlus ?
13778 diag::warn_zero_size_struct_union_in_extern_c :
13779 diag::warn_zero_size_struct_union_compat)
13780 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13783 // Structs without named members are extension in C (C99 6.7.2.1p7),
13784 // but are accepted by GCC.
13785 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13786 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13787 diag::ext_no_named_members_in_struct_union)
13788 << Record->isUnion();
13792 ObjCIvarDecl **ClsFields =
13793 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13794 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13795 ID->setEndOfDefinitionLoc(RBrac);
13796 // Add ivar's to class's DeclContext.
13797 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13798 ClsFields[i]->setLexicalDeclContext(ID);
13799 ID->addDecl(ClsFields[i]);
13801 // Must enforce the rule that ivars in the base classes may not be
13803 if (ID->getSuperClass())
13804 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13805 } else if (ObjCImplementationDecl *IMPDecl =
13806 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13807 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13808 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13809 // Ivar declared in @implementation never belongs to the implementation.
13810 // Only it is in implementation's lexical context.
13811 ClsFields[I]->setLexicalDeclContext(IMPDecl);
13812 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13813 IMPDecl->setIvarLBraceLoc(LBrac);
13814 IMPDecl->setIvarRBraceLoc(RBrac);
13815 } else if (ObjCCategoryDecl *CDecl =
13816 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13817 // case of ivars in class extension; all other cases have been
13818 // reported as errors elsewhere.
13819 // FIXME. Class extension does not have a LocEnd field.
13820 // CDecl->setLocEnd(RBrac);
13821 // Add ivar's to class extension's DeclContext.
13822 // Diagnose redeclaration of private ivars.
13823 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13824 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13826 if (const ObjCIvarDecl *ClsIvar =
13827 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13828 Diag(ClsFields[i]->getLocation(),
13829 diag::err_duplicate_ivar_declaration);
13830 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13833 for (const auto *Ext : IDecl->known_extensions()) {
13834 if (const ObjCIvarDecl *ClsExtIvar
13835 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13836 Diag(ClsFields[i]->getLocation(),
13837 diag::err_duplicate_ivar_declaration);
13838 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13843 ClsFields[i]->setLexicalDeclContext(CDecl);
13844 CDecl->addDecl(ClsFields[i]);
13846 CDecl->setIvarLBraceLoc(LBrac);
13847 CDecl->setIvarRBraceLoc(RBrac);
13852 ProcessDeclAttributeList(S, Record, Attr);
13855 /// \brief Determine whether the given integral value is representable within
13856 /// the given type T.
13857 static bool isRepresentableIntegerValue(ASTContext &Context,
13858 llvm::APSInt &Value,
13860 assert(T->isIntegralType(Context) && "Integral type required!");
13861 unsigned BitWidth = Context.getIntWidth(T);
13863 if (Value.isUnsigned() || Value.isNonNegative()) {
13864 if (T->isSignedIntegerOrEnumerationType())
13866 return Value.getActiveBits() <= BitWidth;
13868 return Value.getMinSignedBits() <= BitWidth;
13871 // \brief Given an integral type, return the next larger integral type
13872 // (or a NULL type of no such type exists).
13873 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13874 // FIXME: Int128/UInt128 support, which also needs to be introduced into
13875 // enum checking below.
13876 assert(T->isIntegralType(Context) && "Integral type required!");
13877 const unsigned NumTypes = 4;
13878 QualType SignedIntegralTypes[NumTypes] = {
13879 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13881 QualType UnsignedIntegralTypes[NumTypes] = {
13882 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13883 Context.UnsignedLongLongTy
13886 unsigned BitWidth = Context.getTypeSize(T);
13887 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13888 : UnsignedIntegralTypes;
13889 for (unsigned I = 0; I != NumTypes; ++I)
13890 if (Context.getTypeSize(Types[I]) > BitWidth)
13896 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13897 EnumConstantDecl *LastEnumConst,
13898 SourceLocation IdLoc,
13899 IdentifierInfo *Id,
13901 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13902 llvm::APSInt EnumVal(IntWidth);
13905 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13909 Val = DefaultLvalueConversion(Val).get();
13912 if (Enum->isDependentType() || Val->isTypeDependent())
13913 EltTy = Context.DependentTy;
13915 SourceLocation ExpLoc;
13916 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13917 !getLangOpts().MSVCCompat) {
13918 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13919 // constant-expression in the enumerator-definition shall be a converted
13920 // constant expression of the underlying type.
13921 EltTy = Enum->getIntegerType();
13922 ExprResult Converted =
13923 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13925 if (Converted.isInvalid())
13928 Val = Converted.get();
13929 } else if (!Val->isValueDependent() &&
13930 !(Val = VerifyIntegerConstantExpression(Val,
13931 &EnumVal).get())) {
13932 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13934 if (Enum->isFixed()) {
13935 EltTy = Enum->getIntegerType();
13937 // In Obj-C and Microsoft mode, require the enumeration value to be
13938 // representable in the underlying type of the enumeration. In C++11,
13939 // we perform a non-narrowing conversion as part of converted constant
13940 // expression checking.
13941 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13942 if (getLangOpts().MSVCCompat) {
13943 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13944 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13946 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13948 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13949 } else if (getLangOpts().CPlusPlus) {
13950 // C++11 [dcl.enum]p5:
13951 // If the underlying type is not fixed, the type of each enumerator
13952 // is the type of its initializing value:
13953 // - If an initializer is specified for an enumerator, the
13954 // initializing value has the same type as the expression.
13955 EltTy = Val->getType();
13958 // The expression that defines the value of an enumeration constant
13959 // shall be an integer constant expression that has a value
13960 // representable as an int.
13962 // Complain if the value is not representable in an int.
13963 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13964 Diag(IdLoc, diag::ext_enum_value_not_int)
13965 << EnumVal.toString(10) << Val->getSourceRange()
13966 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13967 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13968 // Force the type of the expression to 'int'.
13969 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13971 EltTy = Val->getType();
13978 if (Enum->isDependentType())
13979 EltTy = Context.DependentTy;
13980 else if (!LastEnumConst) {
13981 // C++0x [dcl.enum]p5:
13982 // If the underlying type is not fixed, the type of each enumerator
13983 // is the type of its initializing value:
13984 // - If no initializer is specified for the first enumerator, the
13985 // initializing value has an unspecified integral type.
13987 // GCC uses 'int' for its unspecified integral type, as does
13989 if (Enum->isFixed()) {
13990 EltTy = Enum->getIntegerType();
13993 EltTy = Context.IntTy;
13996 // Assign the last value + 1.
13997 EnumVal = LastEnumConst->getInitVal();
13999 EltTy = LastEnumConst->getType();
14001 // Check for overflow on increment.
14002 if (EnumVal < LastEnumConst->getInitVal()) {
14003 // C++0x [dcl.enum]p5:
14004 // If the underlying type is not fixed, the type of each enumerator
14005 // is the type of its initializing value:
14007 // - Otherwise the type of the initializing value is the same as
14008 // the type of the initializing value of the preceding enumerator
14009 // unless the incremented value is not representable in that type,
14010 // in which case the type is an unspecified integral type
14011 // sufficient to contain the incremented value. If no such type
14012 // exists, the program is ill-formed.
14013 QualType T = getNextLargerIntegralType(Context, EltTy);
14014 if (T.isNull() || Enum->isFixed()) {
14015 // There is no integral type larger enough to represent this
14016 // value. Complain, then allow the value to wrap around.
14017 EnumVal = LastEnumConst->getInitVal();
14018 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14020 if (Enum->isFixed())
14021 // When the underlying type is fixed, this is ill-formed.
14022 Diag(IdLoc, diag::err_enumerator_wrapped)
14023 << EnumVal.toString(10)
14026 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14027 << EnumVal.toString(10);
14032 // Retrieve the last enumerator's value, extent that type to the
14033 // type that is supposed to be large enough to represent the incremented
14034 // value, then increment.
14035 EnumVal = LastEnumConst->getInitVal();
14036 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14037 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14040 // If we're not in C++, diagnose the overflow of enumerator values,
14041 // which in C99 means that the enumerator value is not representable in
14042 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14043 // permits enumerator values that are representable in some larger
14045 if (!getLangOpts().CPlusPlus && !T.isNull())
14046 Diag(IdLoc, diag::warn_enum_value_overflow);
14047 } else if (!getLangOpts().CPlusPlus &&
14048 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14049 // Enforce C99 6.7.2.2p2 even when we compute the next value.
14050 Diag(IdLoc, diag::ext_enum_value_not_int)
14051 << EnumVal.toString(10) << 1;
14056 if (!EltTy->isDependentType()) {
14057 // Make the enumerator value match the signedness and size of the
14058 // enumerator's type.
14059 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14060 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14063 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14067 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14068 SourceLocation IILoc) {
14069 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14070 !getLangOpts().CPlusPlus)
14071 return SkipBodyInfo();
14073 // We have an anonymous enum definition. Look up the first enumerator to
14074 // determine if we should merge the definition with an existing one and
14076 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14078 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14080 return SkipBodyInfo();
14082 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14084 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14086 Skip.Previous = Hidden;
14090 return SkipBodyInfo();
14093 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14094 SourceLocation IdLoc, IdentifierInfo *Id,
14095 AttributeList *Attr,
14096 SourceLocation EqualLoc, Expr *Val) {
14097 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14098 EnumConstantDecl *LastEnumConst =
14099 cast_or_null<EnumConstantDecl>(lastEnumConst);
14101 // The scope passed in may not be a decl scope. Zip up the scope tree until
14102 // we find one that is.
14103 S = getNonFieldDeclScope(S);
14105 // Verify that there isn't already something declared with this name in this
14107 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14109 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14110 // Maybe we will complain about the shadowed template parameter.
14111 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14112 // Just pretend that we didn't see the previous declaration.
14113 PrevDecl = nullptr;
14116 // C++ [class.mem]p15:
14117 // If T is the name of a class, then each of the following shall have a name
14118 // different from T:
14119 // - every enumerator of every member of class T that is an unscoped
14121 if (!TheEnumDecl->isScoped())
14122 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14123 DeclarationNameInfo(Id, IdLoc));
14125 EnumConstantDecl *New =
14126 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14131 // When in C++, we may get a TagDecl with the same name; in this case the
14132 // enum constant will 'hide' the tag.
14133 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14134 "Received TagDecl when not in C++!");
14135 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14136 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14137 if (isa<EnumConstantDecl>(PrevDecl))
14138 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14140 Diag(IdLoc, diag::err_redefinition) << Id;
14141 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14146 // Process attributes.
14147 if (Attr) ProcessDeclAttributeList(S, New, Attr);
14149 // Register this decl in the current scope stack.
14150 New->setAccess(TheEnumDecl->getAccess());
14151 PushOnScopeChains(New, S);
14153 ActOnDocumentableDecl(New);
14158 // Returns true when the enum initial expression does not trigger the
14159 // duplicate enum warning. A few common cases are exempted as follows:
14160 // Element2 = Element1
14161 // Element2 = Element1 + 1
14162 // Element2 = Element1 - 1
14163 // Where Element2 and Element1 are from the same enum.
14164 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14165 Expr *InitExpr = ECD->getInitExpr();
14168 InitExpr = InitExpr->IgnoreImpCasts();
14170 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14171 if (!BO->isAdditiveOp())
14173 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14176 if (IL->getValue() != 1)
14179 InitExpr = BO->getLHS();
14182 // This checks if the elements are from the same enum.
14183 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14187 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14191 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14201 bool isTombstoneOrEmptyKey;
14202 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14203 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14206 static DupKey GetDupKey(const llvm::APSInt& Val) {
14207 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14211 struct DenseMapInfoDupKey {
14212 static DupKey getEmptyKey() { return DupKey(0, true); }
14213 static DupKey getTombstoneKey() { return DupKey(1, true); }
14214 static unsigned getHashValue(const DupKey Key) {
14215 return (unsigned)(Key.val * 37);
14217 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14218 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14219 LHS.val == RHS.val;
14222 } // end anonymous namespace
14224 // Emits a warning when an element is implicitly set a value that
14225 // a previous element has already been set to.
14226 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14228 QualType EnumType) {
14229 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14231 // Avoid anonymous enums
14232 if (!Enum->getIdentifier())
14235 // Only check for small enums.
14236 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14239 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14240 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14242 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14243 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14246 DuplicatesVector DupVector;
14247 ValueToVectorMap EnumMap;
14249 // Populate the EnumMap with all values represented by enum constants without
14251 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14252 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14254 // Null EnumConstantDecl means a previous diagnostic has been emitted for
14255 // this constant. Skip this enum since it may be ill-formed.
14260 if (ECD->getInitExpr())
14263 DupKey Key = GetDupKey(ECD->getInitVal());
14264 DeclOrVector &Entry = EnumMap[Key];
14266 // First time encountering this value.
14267 if (Entry.isNull())
14271 // Create vectors for any values that has duplicates.
14272 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14273 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14274 if (!ValidDuplicateEnum(ECD, Enum))
14277 DupKey Key = GetDupKey(ECD->getInitVal());
14279 DeclOrVector& Entry = EnumMap[Key];
14280 if (Entry.isNull())
14283 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14284 // Ensure constants are different.
14288 // Create new vector and push values onto it.
14289 ECDVector *Vec = new ECDVector();
14291 Vec->push_back(ECD);
14293 // Update entry to point to the duplicates vector.
14296 // Store the vector somewhere we can consult later for quick emission of
14298 DupVector.push_back(Vec);
14302 ECDVector *Vec = Entry.get<ECDVector*>();
14303 // Make sure constants are not added more than once.
14304 if (*Vec->begin() == ECD)
14307 Vec->push_back(ECD);
14310 // Emit diagnostics.
14311 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14312 DupVectorEnd = DupVector.end();
14313 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14314 ECDVector *Vec = *DupVectorIter;
14315 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14317 // Emit warning for one enum constant.
14318 ECDVector::iterator I = Vec->begin();
14319 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14320 << (*I)->getName() << (*I)->getInitVal().toString(10)
14321 << (*I)->getSourceRange();
14324 // Emit one note for each of the remaining enum constants with
14326 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14327 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14328 << (*I)->getName() << (*I)->getInitVal().toString(10)
14329 << (*I)->getSourceRange();
14334 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14335 bool AllowMask) const {
14336 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14337 assert(ED->isCompleteDefinition() && "expected enum definition");
14339 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14340 llvm::APInt &FlagBits = R.first->second;
14343 for (auto *E : ED->enumerators()) {
14344 const auto &EVal = E->getInitVal();
14345 // Only single-bit enumerators introduce new flag values.
14346 if (EVal.isPowerOf2())
14347 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14351 // A value is in a flag enum if either its bits are a subset of the enum's
14352 // flag bits (the first condition) or we are allowing masks and the same is
14353 // true of its complement (the second condition). When masks are allowed, we
14354 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14356 // While it's true that any value could be used as a mask, the assumption is
14357 // that a mask will have all of the insignificant bits set. Anything else is
14358 // likely a logic error.
14359 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14360 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14363 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14364 SourceLocation RBraceLoc, Decl *EnumDeclX,
14365 ArrayRef<Decl *> Elements,
14366 Scope *S, AttributeList *Attr) {
14367 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14368 QualType EnumType = Context.getTypeDeclType(Enum);
14371 ProcessDeclAttributeList(S, Enum, Attr);
14373 if (Enum->isDependentType()) {
14374 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14375 EnumConstantDecl *ECD =
14376 cast_or_null<EnumConstantDecl>(Elements[i]);
14377 if (!ECD) continue;
14379 ECD->setType(EnumType);
14382 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14386 // TODO: If the result value doesn't fit in an int, it must be a long or long
14387 // long value. ISO C does not support this, but GCC does as an extension,
14389 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14390 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14391 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14393 // Verify that all the values are okay, compute the size of the values, and
14394 // reverse the list.
14395 unsigned NumNegativeBits = 0;
14396 unsigned NumPositiveBits = 0;
14398 // Keep track of whether all elements have type int.
14399 bool AllElementsInt = true;
14401 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14402 EnumConstantDecl *ECD =
14403 cast_or_null<EnumConstantDecl>(Elements[i]);
14404 if (!ECD) continue; // Already issued a diagnostic.
14406 const llvm::APSInt &InitVal = ECD->getInitVal();
14408 // Keep track of the size of positive and negative values.
14409 if (InitVal.isUnsigned() || InitVal.isNonNegative())
14410 NumPositiveBits = std::max(NumPositiveBits,
14411 (unsigned)InitVal.getActiveBits());
14413 NumNegativeBits = std::max(NumNegativeBits,
14414 (unsigned)InitVal.getMinSignedBits());
14416 // Keep track of whether every enum element has type int (very commmon).
14417 if (AllElementsInt)
14418 AllElementsInt = ECD->getType() == Context.IntTy;
14421 // Figure out the type that should be used for this enum.
14423 unsigned BestWidth;
14425 // C++0x N3000 [conv.prom]p3:
14426 // An rvalue of an unscoped enumeration type whose underlying
14427 // type is not fixed can be converted to an rvalue of the first
14428 // of the following types that can represent all the values of
14429 // the enumeration: int, unsigned int, long int, unsigned long
14430 // int, long long int, or unsigned long long int.
14432 // An identifier declared as an enumeration constant has type int.
14433 // The C99 rule is modified by a gcc extension
14434 QualType BestPromotionType;
14436 bool Packed = Enum->hasAttr<PackedAttr>();
14437 // -fshort-enums is the equivalent to specifying the packed attribute on all
14438 // enum definitions.
14439 if (LangOpts.ShortEnums)
14442 if (Enum->isFixed()) {
14443 BestType = Enum->getIntegerType();
14444 if (BestType->isPromotableIntegerType())
14445 BestPromotionType = Context.getPromotedIntegerType(BestType);
14447 BestPromotionType = BestType;
14449 BestWidth = Context.getIntWidth(BestType);
14451 else if (NumNegativeBits) {
14452 // If there is a negative value, figure out the smallest integer type (of
14453 // int/long/longlong) that fits.
14454 // If it's packed, check also if it fits a char or a short.
14455 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14456 BestType = Context.SignedCharTy;
14457 BestWidth = CharWidth;
14458 } else if (Packed && NumNegativeBits <= ShortWidth &&
14459 NumPositiveBits < ShortWidth) {
14460 BestType = Context.ShortTy;
14461 BestWidth = ShortWidth;
14462 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14463 BestType = Context.IntTy;
14464 BestWidth = IntWidth;
14466 BestWidth = Context.getTargetInfo().getLongWidth();
14468 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14469 BestType = Context.LongTy;
14471 BestWidth = Context.getTargetInfo().getLongLongWidth();
14473 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14474 Diag(Enum->getLocation(), diag::ext_enum_too_large);
14475 BestType = Context.LongLongTy;
14478 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14480 // If there is no negative value, figure out the smallest type that fits
14481 // all of the enumerator values.
14482 // If it's packed, check also if it fits a char or a short.
14483 if (Packed && NumPositiveBits <= CharWidth) {
14484 BestType = Context.UnsignedCharTy;
14485 BestPromotionType = Context.IntTy;
14486 BestWidth = CharWidth;
14487 } else if (Packed && NumPositiveBits <= ShortWidth) {
14488 BestType = Context.UnsignedShortTy;
14489 BestPromotionType = Context.IntTy;
14490 BestWidth = ShortWidth;
14491 } else if (NumPositiveBits <= IntWidth) {
14492 BestType = Context.UnsignedIntTy;
14493 BestWidth = IntWidth;
14495 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14496 ? Context.UnsignedIntTy : Context.IntTy;
14497 } else if (NumPositiveBits <=
14498 (BestWidth = Context.getTargetInfo().getLongWidth())) {
14499 BestType = Context.UnsignedLongTy;
14501 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14502 ? Context.UnsignedLongTy : Context.LongTy;
14504 BestWidth = Context.getTargetInfo().getLongLongWidth();
14505 assert(NumPositiveBits <= BestWidth &&
14506 "How could an initializer get larger than ULL?");
14507 BestType = Context.UnsignedLongLongTy;
14509 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14510 ? Context.UnsignedLongLongTy : Context.LongLongTy;
14514 // Loop over all of the enumerator constants, changing their types to match
14515 // the type of the enum if needed.
14516 for (auto *D : Elements) {
14517 auto *ECD = cast_or_null<EnumConstantDecl>(D);
14518 if (!ECD) continue; // Already issued a diagnostic.
14520 // Standard C says the enumerators have int type, but we allow, as an
14521 // extension, the enumerators to be larger than int size. If each
14522 // enumerator value fits in an int, type it as an int, otherwise type it the
14523 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
14524 // that X has type 'int', not 'unsigned'.
14526 // Determine whether the value fits into an int.
14527 llvm::APSInt InitVal = ECD->getInitVal();
14529 // If it fits into an integer type, force it. Otherwise force it to match
14530 // the enum decl type.
14534 if (!getLangOpts().CPlusPlus &&
14535 !Enum->isFixed() &&
14536 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14537 NewTy = Context.IntTy;
14538 NewWidth = IntWidth;
14540 } else if (ECD->getType() == BestType) {
14541 // Already the right type!
14542 if (getLangOpts().CPlusPlus)
14543 // C++ [dcl.enum]p4: Following the closing brace of an
14544 // enum-specifier, each enumerator has the type of its
14546 ECD->setType(EnumType);
14550 NewWidth = BestWidth;
14551 NewSign = BestType->isSignedIntegerOrEnumerationType();
14554 // Adjust the APSInt value.
14555 InitVal = InitVal.extOrTrunc(NewWidth);
14556 InitVal.setIsSigned(NewSign);
14557 ECD->setInitVal(InitVal);
14559 // Adjust the Expr initializer and type.
14560 if (ECD->getInitExpr() &&
14561 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14562 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14564 ECD->getInitExpr(),
14565 /*base paths*/ nullptr,
14567 if (getLangOpts().CPlusPlus)
14568 // C++ [dcl.enum]p4: Following the closing brace of an
14569 // enum-specifier, each enumerator has the type of its
14571 ECD->setType(EnumType);
14573 ECD->setType(NewTy);
14576 Enum->completeDefinition(BestType, BestPromotionType,
14577 NumPositiveBits, NumNegativeBits);
14579 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14581 if (Enum->hasAttr<FlagEnumAttr>()) {
14582 for (Decl *D : Elements) {
14583 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14584 if (!ECD) continue; // Already issued a diagnostic.
14586 llvm::APSInt InitVal = ECD->getInitVal();
14587 if (InitVal != 0 && !InitVal.isPowerOf2() &&
14588 !IsValueInFlagEnum(Enum, InitVal, true))
14589 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14594 // Now that the enum type is defined, ensure it's not been underaligned.
14595 if (Enum->hasAttrs())
14596 CheckAlignasUnderalignment(Enum);
14599 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14600 SourceLocation StartLoc,
14601 SourceLocation EndLoc) {
14602 StringLiteral *AsmString = cast<StringLiteral>(expr);
14604 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14605 AsmString, StartLoc,
14607 CurContext->addDecl(New);
14611 static void checkModuleImportContext(Sema &S, Module *M,
14612 SourceLocation ImportLoc, DeclContext *DC,
14613 bool FromInclude = false) {
14614 SourceLocation ExternCLoc;
14616 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14617 switch (LSD->getLanguage()) {
14618 case LinkageSpecDecl::lang_c:
14619 if (ExternCLoc.isInvalid())
14620 ExternCLoc = LSD->getLocStart();
14622 case LinkageSpecDecl::lang_cxx:
14625 DC = LSD->getParent();
14628 while (isa<LinkageSpecDecl>(DC))
14629 DC = DC->getParent();
14631 if (!isa<TranslationUnitDecl>(DC)) {
14632 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14633 ? diag::ext_module_import_not_at_top_level_noop
14634 : diag::err_module_import_not_at_top_level_fatal)
14635 << M->getFullModuleName() << DC;
14636 S.Diag(cast<Decl>(DC)->getLocStart(),
14637 diag::note_module_import_not_at_top_level) << DC;
14638 } else if (!M->IsExternC && ExternCLoc.isValid()) {
14639 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14640 << M->getFullModuleName();
14641 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14645 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14646 return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14649 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14650 SourceLocation ImportLoc,
14651 ModuleIdPath Path) {
14653 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14654 /*IsIncludeDirective=*/false);
14658 VisibleModules.setVisible(Mod, ImportLoc);
14660 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14662 // FIXME: we should support importing a submodule within a different submodule
14663 // of the same top-level module. Until we do, make it an error rather than
14664 // silently ignoring the import.
14665 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14666 Diag(ImportLoc, diag::err_module_self_import)
14667 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14668 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
14669 Diag(ImportLoc, diag::err_module_import_in_implementation)
14670 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
14672 SmallVector<SourceLocation, 2> IdentifierLocs;
14673 Module *ModCheck = Mod;
14674 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14675 // If we've run out of module parents, just drop the remaining identifiers.
14676 // We need the length to be consistent.
14679 ModCheck = ModCheck->Parent;
14681 IdentifierLocs.push_back(Path[I].second);
14684 ImportDecl *Import = ImportDecl::Create(Context,
14685 Context.getTranslationUnitDecl(),
14686 AtLoc.isValid()? AtLoc : ImportLoc,
14687 Mod, IdentifierLocs);
14688 Context.getTranslationUnitDecl()->addDecl(Import);
14692 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14693 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14695 // Determine whether we're in the #include buffer for a module. The #includes
14696 // in that buffer do not qualify as module imports; they're just an
14697 // implementation detail of us building the module.
14699 // FIXME: Should we even get ActOnModuleInclude calls for those?
14700 bool IsInModuleIncludes =
14701 TUKind == TU_Module &&
14702 getSourceManager().isWrittenInMainFile(DirectiveLoc);
14704 // If this module import was due to an inclusion directive, create an
14705 // implicit import declaration to capture it in the AST.
14706 if (!IsInModuleIncludes) {
14707 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14708 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14711 TU->addDecl(ImportD);
14712 Consumer.HandleImplicitImportDecl(ImportD);
14715 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14716 VisibleModules.setVisible(Mod, DirectiveLoc);
14719 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14720 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14722 if (getLangOpts().ModulesLocalVisibility)
14723 VisibleModulesStack.push_back(std::move(VisibleModules));
14724 VisibleModules.setVisible(Mod, DirectiveLoc);
14727 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14728 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14730 if (getLangOpts().ModulesLocalVisibility) {
14731 VisibleModules = std::move(VisibleModulesStack.back());
14732 VisibleModulesStack.pop_back();
14733 VisibleModules.setVisible(Mod, DirectiveLoc);
14737 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14739 // Bail if we're not allowed to implicitly import a module here.
14740 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14743 // Create the implicit import declaration.
14744 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14745 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14747 TU->addDecl(ImportD);
14748 Consumer.HandleImplicitImportDecl(ImportD);
14750 // Make the module visible.
14751 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14752 VisibleModules.setVisible(Mod, Loc);
14755 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
14756 IdentifierInfo* AliasName,
14757 SourceLocation PragmaLoc,
14758 SourceLocation NameLoc,
14759 SourceLocation AliasNameLoc) {
14760 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14761 LookupOrdinaryName);
14762 AsmLabelAttr *Attr =
14763 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14765 // If a declaration that:
14766 // 1) declares a function or a variable
14767 // 2) has external linkage
14768 // already exists, add a label attribute to it.
14769 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14770 if (isDeclExternC(PrevDecl))
14771 PrevDecl->addAttr(Attr);
14773 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
14774 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
14775 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14777 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14780 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14781 SourceLocation PragmaLoc,
14782 SourceLocation NameLoc) {
14783 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14786 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14788 (void)WeakUndeclaredIdentifiers.insert(
14789 std::pair<IdentifierInfo*,WeakInfo>
14790 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14794 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14795 IdentifierInfo* AliasName,
14796 SourceLocation PragmaLoc,
14797 SourceLocation NameLoc,
14798 SourceLocation AliasNameLoc) {
14799 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14800 LookupOrdinaryName);
14801 WeakInfo W = WeakInfo(Name, NameLoc);
14803 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14804 if (!PrevDecl->hasAttr<AliasAttr>())
14805 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14806 DeclApplyPragmaWeak(TUScope, ND, W);
14808 (void)WeakUndeclaredIdentifiers.insert(
14809 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14813 Decl *Sema::getObjCDeclContext() const {
14814 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14817 AvailabilityResult Sema::getCurContextAvailability() const {
14818 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14820 return AR_Available;
14822 // If we are within an Objective-C method, we should consult
14823 // both the availability of the method as well as the
14824 // enclosing class. If the class is (say) deprecated,
14825 // the entire method is considered deprecated from the
14826 // purpose of checking if the current context is deprecated.
14827 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14828 AvailabilityResult R = MD->getAvailability();
14829 if (R != AR_Available)
14831 D = MD->getClassInterface();
14833 // If we are within an Objective-c @implementation, it
14834 // gets the same availability context as the @interface.
14835 else if (const ObjCImplementationDecl *ID =
14836 dyn_cast<ObjCImplementationDecl>(D)) {
14837 D = ID->getClassInterface();
14839 // Recover from user error.
14840 return D ? D->getAvailability() : AR_Available;