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"
51 using namespace clang;
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
56 Decl *Group[2] = { OwnedType, Ptr };
57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68 bool AllowTemplates=false)
69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70 AllowClassTemplates(AllowTemplates) {
71 WantExpressionKeywords = false;
72 WantCXXNamedCasts = false;
73 WantRemainingKeywords = false;
76 bool ValidateCandidate(const TypoCorrection &candidate) override {
77 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80 return (IsType || AllowedTemplate) &&
81 (AllowInvalidDecl || !ND->isInvalidDecl());
83 return !WantClassName && candidate.isKeyword();
87 bool AllowInvalidDecl;
89 bool AllowClassTemplates;
92 } // end anonymous namespace
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
97 // FIXME: Take into account the current language when deciding whether a
98 // token kind is a valid type specifier
101 case tok::kw___int64:
102 case tok::kw___int128:
104 case tok::kw_unsigned:
111 case tok::kw_wchar_t:
113 case tok::kw___underlying_type:
114 case tok::kw___auto_type:
117 case tok::annot_typename:
118 case tok::kw_char16_t:
119 case tok::kw_char32_t:
121 case tok::annot_decltype:
122 case tok::kw_decltype:
123 return getLangOpts().CPlusPlus;
133 enum class UnqualifiedTypeNameLookupResult {
138 } // end anonymous namespace
140 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
143 /// type decl, \a FoundType if only type decls are found.
144 static UnqualifiedTypeNameLookupResult
145 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
146 SourceLocation NameLoc,
147 const CXXRecordDecl *RD) {
148 if (!RD->hasDefinition())
149 return UnqualifiedTypeNameLookupResult::NotFound;
150 // Look for type decls in base classes.
151 UnqualifiedTypeNameLookupResult FoundTypeDecl =
152 UnqualifiedTypeNameLookupResult::NotFound;
153 for (const auto &Base : RD->bases()) {
154 const CXXRecordDecl *BaseRD = nullptr;
155 if (auto *BaseTT = Base.getType()->getAs<TagType>())
156 BaseRD = BaseTT->getAsCXXRecordDecl();
157 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
158 // Look for type decls in dependent base classes that have known primary
160 if (!TST || !TST->isDependentType())
162 auto *TD = TST->getTemplateName().getAsTemplateDecl();
165 auto *BasePrimaryTemplate =
166 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
167 if (!BasePrimaryTemplate)
169 BaseRD = BasePrimaryTemplate;
172 for (NamedDecl *ND : BaseRD->lookup(&II)) {
173 if (!isa<TypeDecl>(ND))
174 return UnqualifiedTypeNameLookupResult::FoundNonType;
175 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
177 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
178 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
179 case UnqualifiedTypeNameLookupResult::FoundNonType:
180 return UnqualifiedTypeNameLookupResult::FoundNonType;
181 case UnqualifiedTypeNameLookupResult::FoundType:
182 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
184 case UnqualifiedTypeNameLookupResult::NotFound:
191 return FoundTypeDecl;
194 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
195 const IdentifierInfo &II,
196 SourceLocation NameLoc) {
197 // Lookup in the parent class template context, if any.
198 const CXXRecordDecl *RD = nullptr;
199 UnqualifiedTypeNameLookupResult FoundTypeDecl =
200 UnqualifiedTypeNameLookupResult::NotFound;
201 for (DeclContext *DC = S.CurContext;
202 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
203 DC = DC->getParent()) {
204 // Look for type decls in dependent base classes that have known primary
206 RD = dyn_cast<CXXRecordDecl>(DC);
207 if (RD && RD->getDescribedClassTemplate())
208 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
210 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
213 // We found some types in dependent base classes. Recover as if the user
214 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
215 // lookup during template instantiation.
216 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
218 ASTContext &Context = S.Context;
219 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
220 cast<Type>(Context.getRecordType(RD)));
221 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
224 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226 TypeLocBuilder Builder;
227 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
228 DepTL.setNameLoc(NameLoc);
229 DepTL.setElaboratedKeywordLoc(SourceLocation());
230 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
231 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
234 /// \brief If the identifier refers to a type name within this scope,
235 /// return the declaration of that type.
237 /// This routine performs ordinary name lookup of the identifier II
238 /// within the given scope, with optional C++ scope specifier SS, to
239 /// determine whether the name refers to a type. If so, returns an
240 /// opaque pointer (actually a QualType) corresponding to that
241 /// type. Otherwise, returns NULL.
242 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
243 Scope *S, CXXScopeSpec *SS,
244 bool isClassName, bool HasTrailingDot,
245 ParsedType ObjectTypePtr,
246 bool IsCtorOrDtorName,
247 bool WantNontrivialTypeSourceInfo,
248 IdentifierInfo **CorrectedII) {
249 // Determine where we will perform name lookup.
250 DeclContext *LookupCtx = nullptr;
252 QualType ObjectType = ObjectTypePtr.get();
253 if (ObjectType->isRecordType())
254 LookupCtx = computeDeclContext(ObjectType);
255 } else if (SS && SS->isNotEmpty()) {
256 LookupCtx = computeDeclContext(*SS, false);
259 if (isDependentScopeSpecifier(*SS)) {
261 // A qualified-id that refers to a type and in which the
262 // nested-name-specifier depends on a template-parameter (14.6.2)
263 // shall be prefixed by the keyword typename to indicate that the
264 // qualified-id denotes a type, forming an
265 // elaborated-type-specifier (7.1.5.3).
267 // We therefore do not perform any name lookup if the result would
268 // refer to a member of an unknown specialization.
269 if (!isClassName && !IsCtorOrDtorName)
272 // We know from the grammar that this name refers to a type,
273 // so build a dependent node to describe the type.
274 if (WantNontrivialTypeSourceInfo)
275 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
277 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
278 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
280 return ParsedType::make(T);
286 if (!LookupCtx->isDependentContext() &&
287 RequireCompleteDeclContext(*SS, LookupCtx))
291 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
292 // lookup for class-names.
293 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
295 LookupResult Result(*this, &II, NameLoc, Kind);
297 // Perform "qualified" name lookup into the declaration context we
298 // computed, which is either the type of the base of a member access
299 // expression or the declaration context associated with a prior
300 // nested-name-specifier.
301 LookupQualifiedName(Result, LookupCtx);
303 if (ObjectTypePtr && Result.empty()) {
304 // C++ [basic.lookup.classref]p3:
305 // If the unqualified-id is ~type-name, the type-name is looked up
306 // in the context of the entire postfix-expression. If the type T of
307 // the object expression is of a class type C, the type-name is also
308 // looked up in the scope of class C. At least one of the lookups shall
309 // find a name that refers to (possibly cv-qualified) T.
310 LookupName(Result, S);
313 // Perform unqualified name lookup.
314 LookupName(Result, S);
316 // For unqualified lookup in a class template in MSVC mode, look into
317 // dependent base classes where the primary class template is known.
318 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
319 if (ParsedType TypeInBase =
320 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
325 NamedDecl *IIDecl = nullptr;
326 switch (Result.getResultKind()) {
327 case LookupResult::NotFound:
328 case LookupResult::NotFoundInCurrentInstantiation:
330 TypoCorrection Correction = CorrectTypo(
331 Result.getLookupNameInfo(), Kind, S, SS,
332 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
334 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
336 bool MemberOfUnknownSpecialization;
337 UnqualifiedId TemplateName;
338 TemplateName.setIdentifier(NewII, NameLoc);
339 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
340 CXXScopeSpec NewSS, *NewSSPtr = SS;
342 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
345 if (Correction && (NNS || NewII != &II) &&
346 // Ignore a correction to a template type as the to-be-corrected
347 // identifier is not a template (typo correction for template names
348 // is handled elsewhere).
349 !(getLangOpts().CPlusPlus && NewSSPtr &&
350 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
351 Template, MemberOfUnknownSpecialization))) {
352 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
353 isClassName, HasTrailingDot, ObjectTypePtr,
355 WantNontrivialTypeSourceInfo);
357 diagnoseTypo(Correction,
358 PDiag(diag::err_unknown_type_or_class_name_suggest)
359 << Result.getLookupName() << isClassName);
361 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
362 *CorrectedII = NewII;
367 // If typo correction failed or was not performed, fall through
368 case LookupResult::FoundOverloaded:
369 case LookupResult::FoundUnresolvedValue:
370 Result.suppressDiagnostics();
373 case LookupResult::Ambiguous:
374 // Recover from type-hiding ambiguities by hiding the type. We'll
375 // do the lookup again when looking for an object, and we can
376 // diagnose the error then. If we don't do this, then the error
377 // about hiding the type will be immediately followed by an error
378 // that only makes sense if the identifier was treated like a type.
379 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
380 Result.suppressDiagnostics();
384 // Look to see if we have a type anywhere in the list of results.
385 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
386 Res != ResEnd; ++Res) {
387 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
389 (*Res)->getLocation().getRawEncoding() <
390 IIDecl->getLocation().getRawEncoding())
396 // None of the entities we found is a type, so there is no way
397 // to even assume that the result is a type. In this case, don't
398 // complain about the ambiguity. The parser will either try to
399 // perform this lookup again (e.g., as an object name), which
400 // will produce the ambiguity, or will complain that it expected
402 Result.suppressDiagnostics();
406 // We found a type within the ambiguous lookup; diagnose the
407 // ambiguity and then return that type. This might be the right
408 // answer, or it might not be, but it suppresses any attempt to
409 // perform the name lookup again.
412 case LookupResult::Found:
413 IIDecl = Result.getFoundDecl();
417 assert(IIDecl && "Didn't find decl");
420 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
421 DiagnoseUseOfDecl(IIDecl, NameLoc);
423 T = Context.getTypeDeclType(TD);
424 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
426 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
427 // constructor or destructor name (in such a case, the scope specifier
428 // will be attached to the enclosing Expr or Decl node).
429 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
430 if (WantNontrivialTypeSourceInfo) {
431 // Construct a type with type-source information.
432 TypeLocBuilder Builder;
433 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
435 T = getElaboratedType(ETK_None, *SS, T);
436 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
437 ElabTL.setElaboratedKeywordLoc(SourceLocation());
438 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
439 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
441 T = getElaboratedType(ETK_None, *SS, T);
444 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
445 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
447 T = Context.getObjCInterfaceType(IDecl);
451 // If it's not plausibly a type, suppress diagnostics.
452 Result.suppressDiagnostics();
455 return ParsedType::make(T);
458 // Builds a fake NNS for the given decl context.
459 static NestedNameSpecifier *
460 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
461 for (;; DC = DC->getLookupParent()) {
462 DC = DC->getPrimaryContext();
463 auto *ND = dyn_cast<NamespaceDecl>(DC);
464 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
465 return NestedNameSpecifier::Create(Context, nullptr, ND);
466 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
467 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
468 RD->getTypeForDecl());
469 else if (isa<TranslationUnitDecl>(DC))
470 return NestedNameSpecifier::GlobalSpecifier(Context);
472 llvm_unreachable("something isn't in TU scope?");
475 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
476 SourceLocation NameLoc) {
477 // Accepting an undeclared identifier as a default argument for a template
478 // type parameter is a Microsoft extension.
479 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
481 // Build a fake DependentNameType that will perform lookup into CurContext at
482 // instantiation time. The name specifier isn't dependent, so template
483 // instantiation won't transform it. It will retry the lookup, however.
484 NestedNameSpecifier *NNS =
485 synthesizeCurrentNestedNameSpecifier(Context, CurContext);
486 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
488 // Build type location information. We synthesized the qualifier, so we have
489 // to build a fake NestedNameSpecifierLoc.
490 NestedNameSpecifierLocBuilder NNSLocBuilder;
491 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
492 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
494 TypeLocBuilder Builder;
495 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
496 DepTL.setNameLoc(NameLoc);
497 DepTL.setElaboratedKeywordLoc(SourceLocation());
498 DepTL.setQualifierLoc(QualifierLoc);
499 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
502 /// isTagName() - This method is called *for error recovery purposes only*
503 /// to determine if the specified name is a valid tag name ("struct foo"). If
504 /// so, this returns the TST for the tag corresponding to it (TST_enum,
505 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
506 /// cases in C where the user forgot to specify the tag.
507 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
508 // Do a tag name lookup in this scope.
509 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
510 LookupName(R, S, false);
511 R.suppressDiagnostics();
512 if (R.getResultKind() == LookupResult::Found)
513 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
514 switch (TD->getTagKind()) {
515 case TTK_Struct: return DeclSpec::TST_struct;
516 case TTK_Interface: return DeclSpec::TST_interface;
517 case TTK_Union: return DeclSpec::TST_union;
518 case TTK_Class: return DeclSpec::TST_class;
519 case TTK_Enum: return DeclSpec::TST_enum;
523 return DeclSpec::TST_unspecified;
526 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
527 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
528 /// then downgrade the missing typename error to a warning.
529 /// This is needed for MSVC compatibility; Example:
531 /// template<class T> class A {
533 /// typedef int TYPE;
535 /// template<class T> class B : public A<T> {
537 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
540 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
541 if (CurContext->isRecord()) {
542 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
545 const Type *Ty = SS->getScopeRep()->getAsType();
547 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
548 for (const auto &Base : RD->bases())
549 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
551 return S->isFunctionPrototypeScope();
553 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
556 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
557 SourceLocation IILoc,
560 ParsedType &SuggestedType,
561 bool AllowClassTemplates) {
562 // We don't have anything to suggest (yet).
563 SuggestedType = nullptr;
565 // There may have been a typo in the name of the type. Look up typo
566 // results, in case we have something that we can suggest.
567 if (TypoCorrection Corrected =
568 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
569 llvm::make_unique<TypeNameValidatorCCC>(
570 false, false, AllowClassTemplates),
571 CTK_ErrorRecovery)) {
572 if (Corrected.isKeyword()) {
573 // We corrected to a keyword.
574 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
575 II = Corrected.getCorrectionAsIdentifierInfo();
577 // We found a similarly-named type or interface; suggest that.
578 if (!SS || !SS->isSet()) {
579 diagnoseTypo(Corrected,
580 PDiag(diag::err_unknown_typename_suggest) << II);
581 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
582 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
583 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
584 II->getName().equals(CorrectedStr);
585 diagnoseTypo(Corrected,
586 PDiag(diag::err_unknown_nested_typename_suggest)
587 << II << DC << DroppedSpecifier << SS->getRange());
589 llvm_unreachable("could not have corrected a typo here");
593 if (Corrected.getCorrectionSpecifier())
594 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
597 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
598 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
599 /*IsCtorOrDtorName=*/false,
600 /*NonTrivialTypeSourceInfo=*/true);
605 if (getLangOpts().CPlusPlus) {
606 // See if II is a class template that the user forgot to pass arguments to.
608 Name.setIdentifier(II, IILoc);
609 CXXScopeSpec EmptySS;
610 TemplateTy TemplateResult;
611 bool MemberOfUnknownSpecialization;
612 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
613 Name, nullptr, true, TemplateResult,
614 MemberOfUnknownSpecialization) == TNK_Type_template) {
615 TemplateName TplName = TemplateResult.get();
616 Diag(IILoc, diag::err_template_missing_args) << TplName;
617 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
618 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
619 << TplDecl->getTemplateParameters()->getSourceRange();
625 // FIXME: Should we move the logic that tries to recover from a missing tag
626 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
628 if (!SS || (!SS->isSet() && !SS->isInvalid()))
629 Diag(IILoc, diag::err_unknown_typename) << II;
630 else if (DeclContext *DC = computeDeclContext(*SS, false))
631 Diag(IILoc, diag::err_typename_nested_not_found)
632 << II << DC << SS->getRange();
633 else if (isDependentScopeSpecifier(*SS)) {
634 unsigned DiagID = diag::err_typename_missing;
635 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
636 DiagID = diag::ext_typename_missing;
638 Diag(SS->getRange().getBegin(), DiagID)
639 << SS->getScopeRep() << II->getName()
640 << SourceRange(SS->getRange().getBegin(), IILoc)
641 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
642 SuggestedType = ActOnTypenameType(S, SourceLocation(),
643 *SS, *II, IILoc).get();
645 assert(SS && SS->isInvalid() &&
646 "Invalid scope specifier has already been diagnosed");
650 /// \brief Determine whether the given result set contains either a type name
652 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
653 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
654 NextToken.is(tok::less);
656 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
657 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
660 if (CheckTemplate && isa<TemplateDecl>(*I))
667 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
668 Scope *S, CXXScopeSpec &SS,
669 IdentifierInfo *&Name,
670 SourceLocation NameLoc) {
671 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
672 SemaRef.LookupParsedName(R, S, &SS);
673 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
674 StringRef FixItTagName;
675 switch (Tag->getTagKind()) {
677 FixItTagName = "class ";
681 FixItTagName = "enum ";
685 FixItTagName = "struct ";
689 FixItTagName = "__interface ";
693 FixItTagName = "union ";
697 StringRef TagName = FixItTagName.drop_back();
698 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
699 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
700 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
702 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
704 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
707 // Replace lookup results with just the tag decl.
708 Result.clear(Sema::LookupTagName);
709 SemaRef.LookupParsedName(Result, S, &SS);
716 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
717 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
718 QualType T, SourceLocation NameLoc) {
719 ASTContext &Context = S.Context;
721 TypeLocBuilder Builder;
722 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
724 T = S.getElaboratedType(ETK_None, SS, T);
725 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
726 ElabTL.setElaboratedKeywordLoc(SourceLocation());
727 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
728 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
731 Sema::NameClassification
732 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
733 SourceLocation NameLoc, const Token &NextToken,
734 bool IsAddressOfOperand,
735 std::unique_ptr<CorrectionCandidateCallback> CCC) {
736 DeclarationNameInfo NameInfo(Name, NameLoc);
737 ObjCMethodDecl *CurMethod = getCurMethodDecl();
739 if (NextToken.is(tok::coloncolon)) {
740 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
741 QualType(), false, SS, nullptr, false);
744 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
745 LookupParsedName(Result, S, &SS, !CurMethod);
747 // For unqualified lookup in a class template in MSVC mode, look into
748 // dependent base classes where the primary class template is known.
749 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
750 if (ParsedType TypeInBase =
751 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
755 // Perform lookup for Objective-C instance variables (including automatically
756 // synthesized instance variables), if we're in an Objective-C method.
757 // FIXME: This lookup really, really needs to be folded in to the normal
758 // unqualified lookup mechanism.
759 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
760 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
761 if (E.get() || E.isInvalid())
765 bool SecondTry = false;
766 bool IsFilteredTemplateName = false;
769 switch (Result.getResultKind()) {
770 case LookupResult::NotFound:
771 // If an unqualified-id is followed by a '(', then we have a function
773 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
774 // In C++, this is an ADL-only call.
776 if (getLangOpts().CPlusPlus)
777 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
780 // If the expression that precedes the parenthesized argument list in a
781 // function call consists solely of an identifier, and if no
782 // declaration is visible for this identifier, the identifier is
783 // implicitly declared exactly as if, in the innermost block containing
784 // the function call, the declaration
786 // extern int identifier ();
790 // We also allow this in C99 as an extension.
791 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
793 Result.resolveKind();
794 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
798 // In C, we first see whether there is a tag type by the same name, in
799 // which case it's likely that the user just forgot to write "enum",
800 // "struct", or "union".
801 if (!getLangOpts().CPlusPlus && !SecondTry &&
802 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
806 // Perform typo correction to determine if there is another name that is
807 // close to this name.
808 if (!SecondTry && CCC) {
810 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
811 Result.getLookupKind(), S,
813 CTK_ErrorRecovery)) {
814 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
815 unsigned QualifiedDiag = diag::err_no_member_suggest;
817 NamedDecl *FirstDecl = Corrected.getFoundDecl();
818 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
819 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
820 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
821 UnqualifiedDiag = diag::err_no_template_suggest;
822 QualifiedDiag = diag::err_no_member_template_suggest;
823 } else if (UnderlyingFirstDecl &&
824 (isa<TypeDecl>(UnderlyingFirstDecl) ||
825 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
826 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
827 UnqualifiedDiag = diag::err_unknown_typename_suggest;
828 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
832 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
833 } else {// FIXME: is this even reachable? Test it.
834 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
835 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
836 Name->getName().equals(CorrectedStr);
837 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
838 << Name << computeDeclContext(SS, false)
839 << DroppedSpecifier << SS.getRange());
842 // Update the name, so that the caller has the new name.
843 Name = Corrected.getCorrectionAsIdentifierInfo();
845 // Typo correction corrected to a keyword.
846 if (Corrected.isKeyword())
849 // Also update the LookupResult...
850 // FIXME: This should probably go away at some point
852 Result.setLookupName(Corrected.getCorrection());
854 Result.addDecl(FirstDecl);
856 // If we found an Objective-C instance variable, let
857 // LookupInObjCMethod build the appropriate expression to
858 // reference the ivar.
859 // FIXME: This is a gross hack.
860 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
862 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
870 // We failed to correct; just fall through and let the parser deal with it.
871 Result.suppressDiagnostics();
872 return NameClassification::Unknown();
874 case LookupResult::NotFoundInCurrentInstantiation: {
875 // We performed name lookup into the current instantiation, and there were
876 // dependent bases, so we treat this result the same way as any other
877 // dependent nested-name-specifier.
880 // A name used in a template declaration or definition and that is
881 // dependent on a template-parameter is assumed not to name a type
882 // unless the applicable name lookup finds a type name or the name is
883 // qualified by the keyword typename.
885 // FIXME: If the next token is '<', we might want to ask the parser to
886 // perform some heroics to see if we actually have a
887 // template-argument-list, which would indicate a missing 'template'
889 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
890 NameInfo, IsAddressOfOperand,
891 /*TemplateArgs=*/nullptr);
894 case LookupResult::Found:
895 case LookupResult::FoundOverloaded:
896 case LookupResult::FoundUnresolvedValue:
899 case LookupResult::Ambiguous:
900 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901 hasAnyAcceptableTemplateNames(Result)) {
902 // C++ [temp.local]p3:
903 // A lookup that finds an injected-class-name (10.2) can result in an
904 // ambiguity in certain cases (for example, if it is found in more than
905 // one base class). If all of the injected-class-names that are found
906 // refer to specializations of the same class template, and if the name
907 // is followed by a template-argument-list, the reference refers to the
908 // class template itself and not a specialization thereof, and is not
911 // This filtering can make an ambiguous result into an unambiguous one,
912 // so try again after filtering out template names.
913 FilterAcceptableTemplateNames(Result);
914 if (!Result.isAmbiguous()) {
915 IsFilteredTemplateName = true;
920 // Diagnose the ambiguity and return an error.
921 return NameClassification::Error();
924 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
925 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
926 // C++ [temp.names]p3:
927 // After name lookup (3.4) finds that a name is a template-name or that
928 // an operator-function-id or a literal- operator-id refers to a set of
929 // overloaded functions any member of which is a function template if
930 // this is followed by a <, the < is always taken as the delimiter of a
931 // template-argument-list and never as the less-than operator.
932 if (!IsFilteredTemplateName)
933 FilterAcceptableTemplateNames(Result);
935 if (!Result.empty()) {
936 bool IsFunctionTemplate;
938 TemplateName Template;
939 if (Result.end() - Result.begin() > 1) {
940 IsFunctionTemplate = true;
941 Template = Context.getOverloadedTemplateName(Result.begin(),
945 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
946 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
947 IsVarTemplate = isa<VarTemplateDecl>(TD);
949 if (SS.isSet() && !SS.isInvalid())
950 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
951 /*TemplateKeyword=*/false,
954 Template = TemplateName(TD);
957 if (IsFunctionTemplate) {
958 // Function templates always go through overload resolution, at which
959 // point we'll perform the various checks (e.g., accessibility) we need
960 // to based on which function we selected.
961 Result.suppressDiagnostics();
963 return NameClassification::FunctionTemplate(Template);
966 return IsVarTemplate ? NameClassification::VarTemplate(Template)
967 : NameClassification::TypeTemplate(Template);
971 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
972 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
973 DiagnoseUseOfDecl(Type, NameLoc);
974 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
975 QualType T = Context.getTypeDeclType(Type);
977 return buildNestedType(*this, SS, T, NameLoc);
978 return ParsedType::make(T);
981 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
983 // FIXME: It's unfortunate that we don't have a Type node for handling this.
984 if (ObjCCompatibleAliasDecl *Alias =
985 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
986 Class = Alias->getClassInterface();
990 DiagnoseUseOfDecl(Class, NameLoc);
992 if (NextToken.is(tok::period)) {
993 // Interface. <something> is parsed as a property reference expression.
994 // Just return "unknown" as a fall-through for now.
995 Result.suppressDiagnostics();
996 return NameClassification::Unknown();
999 QualType T = Context.getObjCInterfaceType(Class);
1000 return ParsedType::make(T);
1003 // We can have a type template here if we're classifying a template argument.
1004 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1005 return NameClassification::TypeTemplate(
1006 TemplateName(cast<TemplateDecl>(FirstDecl)));
1008 // Check for a tag type hidden by a non-type decl in a few cases where it
1009 // seems likely a type is wanted instead of the non-type that was found.
1010 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1011 if ((NextToken.is(tok::identifier) ||
1013 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1014 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1015 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1016 DiagnoseUseOfDecl(Type, NameLoc);
1017 QualType T = Context.getTypeDeclType(Type);
1018 if (SS.isNotEmpty())
1019 return buildNestedType(*this, SS, T, NameLoc);
1020 return ParsedType::make(T);
1023 if (FirstDecl->isCXXClassMember())
1024 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1027 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1028 return BuildDeclarationNameExpr(SS, Result, ADL);
1031 // Determines the context to return to after temporarily entering a
1032 // context. This depends in an unnecessarily complicated way on the
1033 // exact ordering of callbacks from the parser.
1034 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1036 // Functions defined inline within classes aren't parsed until we've
1037 // finished parsing the top-level class, so the top-level class is
1038 // the context we'll need to return to.
1039 // A Lambda call operator whose parent is a class must not be treated
1040 // as an inline member function. A Lambda can be used legally
1041 // either as an in-class member initializer or a default argument. These
1042 // are parsed once the class has been marked complete and so the containing
1043 // context would be the nested class (when the lambda is defined in one);
1044 // If the class is not complete, then the lambda is being used in an
1045 // ill-formed fashion (such as to specify the width of a bit-field, or
1046 // in an array-bound) - in which case we still want to return the
1047 // lexically containing DC (which could be a nested class).
1048 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1049 DC = DC->getLexicalParent();
1051 // A function not defined within a class will always return to its
1053 if (!isa<CXXRecordDecl>(DC))
1056 // A C++ inline method/friend is parsed *after* the topmost class
1057 // it was declared in is fully parsed ("complete"); the topmost
1058 // class is the context we need to return to.
1059 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1062 // Return the declaration context of the topmost class the inline method is
1067 return DC->getLexicalParent();
1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1071 assert(getContainingDC(DC) == CurContext &&
1072 "The next DeclContext should be lexically contained in the current one.");
1077 void Sema::PopDeclContext() {
1078 assert(CurContext && "DeclContext imbalance!");
1080 CurContext = getContainingDC(CurContext);
1081 assert(CurContext && "Popped translation unit!");
1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1086 // Unlike PushDeclContext, the context to which we return is not necessarily
1087 // the containing DC of TD, because the new context will be some pre-existing
1088 // TagDecl definition instead of a fresh one.
1089 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1090 CurContext = cast<TagDecl>(D)->getDefinition();
1091 assert(CurContext && "skipping definition of undefined tag");
1092 // Start lookups from the parent of the current context; we don't want to look
1093 // into the pre-existing complete definition.
1094 S->setEntity(CurContext->getLookupParent());
1098 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1099 CurContext = static_cast<decltype(CurContext)>(Context);
1102 /// EnterDeclaratorContext - Used when we must lookup names in the context
1103 /// of a declarator's nested name specifier.
1105 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1106 // C++0x [basic.lookup.unqual]p13:
1107 // A name used in the definition of a static data member of class
1108 // X (after the qualified-id of the static member) is looked up as
1109 // if the name was used in a member function of X.
1110 // C++0x [basic.lookup.unqual]p14:
1111 // If a variable member of a namespace is defined outside of the
1112 // scope of its namespace then any name used in the definition of
1113 // the variable member (after the declarator-id) is looked up as
1114 // if the definition of the variable member occurred in its
1116 // Both of these imply that we should push a scope whose context
1117 // is the semantic context of the declaration. We can't use
1118 // PushDeclContext here because that context is not necessarily
1119 // lexically contained in the current context. Fortunately,
1120 // the containing scope should have the appropriate information.
1122 assert(!S->getEntity() && "scope already has entity");
1125 Scope *Ancestor = S->getParent();
1126 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1127 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1134 void Sema::ExitDeclaratorContext(Scope *S) {
1135 assert(S->getEntity() == CurContext && "Context imbalance!");
1137 // Switch back to the lexical context. The safety of this is
1138 // enforced by an assert in EnterDeclaratorContext.
1139 Scope *Ancestor = S->getParent();
1140 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1141 CurContext = Ancestor->getEntity();
1143 // 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);
1171 void Sema::ActOnExitFunctionContext() {
1172 // Same implementation as PopDeclContext, but returns to the lexical parent,
1173 // rather than the top-level class.
1174 assert(CurContext && "DeclContext imbalance!");
1175 CurContext = CurContext->getLexicalParent();
1176 assert(CurContext && "Popped translation unit!");
1179 /// \brief Determine whether we allow overloading of the function
1180 /// PrevDecl with another declaration.
1182 /// This routine determines whether overloading is possible, not
1183 /// whether some new function is actually an overload. It will return
1184 /// true in C++ (where we can always provide overloads) or, as an
1185 /// extension, in C when the previous function is already an
1186 /// overloaded function declaration or has the "overloadable"
1188 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1189 ASTContext &Context) {
1190 if (Context.getLangOpts().CPlusPlus)
1193 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1196 return (Previous.getResultKind() == LookupResult::Found
1197 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1200 /// Add this decl to the scope shadowed decl chains.
1201 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1202 // Move up the scope chain until we find the nearest enclosing
1203 // non-transparent context. The declaration will be introduced into this
1205 while (S->getEntity() && S->getEntity()->isTransparentContext())
1208 // Add scoped declarations into their context, so that they can be
1209 // found later. Declarations without a context won't be inserted
1210 // into any context.
1212 CurContext->addDecl(D);
1214 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1215 // are function-local declarations.
1216 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1217 !D->getDeclContext()->getRedeclContext()->Equals(
1218 D->getLexicalDeclContext()->getRedeclContext()) &&
1219 !D->getLexicalDeclContext()->isFunctionOrMethod())
1222 // Template instantiations should also not be pushed into scope.
1223 if (isa<FunctionDecl>(D) &&
1224 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1227 // If this replaces anything in the current scope,
1228 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1229 IEnd = IdResolver.end();
1230 for (; I != IEnd; ++I) {
1231 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1233 IdResolver.RemoveDecl(*I);
1235 // Should only need to replace one decl.
1242 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1243 // Implicitly-generated labels may end up getting generated in an order that
1244 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1245 // the label at the appropriate place in the identifier chain.
1246 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1247 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1248 if (IDC == CurContext) {
1249 if (!S->isDeclScope(*I))
1251 } else if (IDC->Encloses(CurContext))
1255 IdResolver.InsertDeclAfter(I, D);
1257 IdResolver.AddDecl(D);
1261 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1262 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1263 TUScope->AddDecl(D);
1266 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1267 bool AllowInlineNamespace) {
1268 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1271 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1272 DeclContext *TargetDC = DC->getPrimaryContext();
1274 if (DeclContext *ScopeDC = S->getEntity())
1275 if (ScopeDC->getPrimaryContext() == TargetDC)
1277 } while ((S = S->getParent()));
1282 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1286 /// Filters out lookup results that don't fall within the given scope
1287 /// as determined by isDeclInScope.
1288 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1289 bool ConsiderLinkage,
1290 bool AllowInlineNamespace) {
1291 LookupResult::Filter F = R.makeFilter();
1292 while (F.hasNext()) {
1293 NamedDecl *D = F.next();
1295 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1298 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1307 static bool isUsingDecl(NamedDecl *D) {
1308 return isa<UsingShadowDecl>(D) ||
1309 isa<UnresolvedUsingTypenameDecl>(D) ||
1310 isa<UnresolvedUsingValueDecl>(D);
1313 /// Removes using shadow declarations from the lookup results.
1314 static void RemoveUsingDecls(LookupResult &R) {
1315 LookupResult::Filter F = R.makeFilter();
1317 if (isUsingDecl(F.next()))
1323 /// \brief Check for this common pattern:
1326 /// S(const S&); // DO NOT IMPLEMENT
1327 /// void operator=(const S&); // DO NOT IMPLEMENT
1330 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1331 // FIXME: Should check for private access too but access is set after we get
1333 if (D->doesThisDeclarationHaveABody())
1336 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1337 return CD->isCopyConstructor();
1338 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1339 return Method->isCopyAssignmentOperator();
1343 // We need this to handle
1346 // void *foo() { return 0; }
1349 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1350 // for example. If 'A', foo will have external linkage. If we have '*A',
1351 // foo will have no linkage. Since we can't know until we get to the end
1352 // of the typedef, this function finds out if D might have non-external linkage.
1353 // Callers should verify at the end of the TU if it D has external linkage or
1355 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1356 const DeclContext *DC = D->getDeclContext();
1357 while (!DC->isTranslationUnit()) {
1358 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1359 if (!RD->hasNameForLinkage())
1362 DC = DC->getParent();
1365 return !D->isExternallyVisible();
1368 // FIXME: This needs to be refactored; some other isInMainFile users want
1370 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1371 if (S.TUKind != TU_Complete)
1373 return S.SourceMgr.isInMainFile(Loc);
1376 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1379 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1382 // Ignore all entities declared within templates, and out-of-line definitions
1383 // of members of class templates.
1384 if (D->getDeclContext()->isDependentContext() ||
1385 D->getLexicalDeclContext()->isDependentContext())
1388 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1389 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1392 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1393 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1396 // 'static inline' functions are defined in headers; don't warn.
1397 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1401 if (FD->doesThisDeclarationHaveABody() &&
1402 Context.DeclMustBeEmitted(FD))
1404 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1405 // Constants and utility variables are defined in headers with internal
1406 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1408 if (!isMainFileLoc(*this, VD->getLocation()))
1411 if (Context.DeclMustBeEmitted(VD))
1414 if (VD->isStaticDataMember() &&
1415 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1421 // Only warn for unused decls internal to the translation unit.
1422 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1423 // for inline functions defined in the main source file, for instance.
1424 return mightHaveNonExternalLinkage(D);
1427 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1431 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1432 const FunctionDecl *First = FD->getFirstDecl();
1433 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1434 return; // First should already be in the vector.
1437 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1438 const VarDecl *First = VD->getFirstDecl();
1439 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1440 return; // First should already be in the vector.
1443 if (ShouldWarnIfUnusedFileScopedDecl(D))
1444 UnusedFileScopedDecls.push_back(D);
1447 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1448 if (D->isInvalidDecl())
1451 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1452 D->hasAttr<ObjCPreciseLifetimeAttr>())
1455 if (isa<LabelDecl>(D))
1458 // Except for labels, we only care about unused decls that are local to
1460 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1461 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1462 // For dependent types, the diagnostic is deferred.
1464 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1465 if (!WithinFunction)
1468 if (isa<TypedefNameDecl>(D))
1471 // White-list anything that isn't a local variable.
1472 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1475 // Types of valid local variables should be complete, so this should succeed.
1476 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1478 // White-list anything with an __attribute__((unused)) type.
1479 QualType Ty = VD->getType();
1481 // Only look at the outermost level of typedef.
1482 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1483 if (TT->getDecl()->hasAttr<UnusedAttr>())
1487 // If we failed to complete the type for some reason, or if the type is
1488 // dependent, don't diagnose the variable.
1489 if (Ty->isIncompleteType() || Ty->isDependentType())
1492 if (const TagType *TT = Ty->getAs<TagType>()) {
1493 const TagDecl *Tag = TT->getDecl();
1494 if (Tag->hasAttr<UnusedAttr>())
1497 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1498 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1501 if (const Expr *Init = VD->getInit()) {
1502 if (const ExprWithCleanups *Cleanups =
1503 dyn_cast<ExprWithCleanups>(Init))
1504 Init = Cleanups->getSubExpr();
1505 const CXXConstructExpr *Construct =
1506 dyn_cast<CXXConstructExpr>(Init);
1507 if (Construct && !Construct->isElidable()) {
1508 CXXConstructorDecl *CD = Construct->getConstructor();
1509 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1516 // TODO: __attribute__((unused)) templates?
1522 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1524 if (isa<LabelDecl>(D)) {
1525 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1526 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1527 if (AfterColon.isInvalid())
1529 Hint = FixItHint::CreateRemoval(CharSourceRange::
1530 getCharRange(D->getLocStart(), AfterColon));
1534 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1535 if (D->getTypeForDecl()->isDependentType())
1538 for (auto *TmpD : D->decls()) {
1539 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1540 DiagnoseUnusedDecl(T);
1541 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1542 DiagnoseUnusedNestedTypedefs(R);
1546 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1547 /// unless they are marked attr(unused).
1548 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1549 if (!ShouldDiagnoseUnusedDecl(D))
1552 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1553 // typedefs can be referenced later on, so the diagnostics are emitted
1554 // at end-of-translation-unit.
1555 UnusedLocalTypedefNameCandidates.insert(TD);
1560 GenerateFixForUnusedDecl(D, Context, Hint);
1563 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1564 DiagID = diag::warn_unused_exception_param;
1565 else if (isa<LabelDecl>(D))
1566 DiagID = diag::warn_unused_label;
1568 DiagID = diag::warn_unused_variable;
1570 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1573 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1574 // Verify that we have no forward references left. If so, there was a goto
1575 // or address of a label taken, but no definition of it. Label fwd
1576 // definitions are indicated with a null substmt which is also not a resolved
1577 // MS inline assembly label name.
1578 bool Diagnose = false;
1579 if (L->isMSAsmLabel())
1580 Diagnose = !L->isResolvedMSAsmLabel();
1582 Diagnose = L->getStmt() == nullptr;
1584 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1587 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1588 S->mergeNRVOIntoParent();
1590 if (S->decl_empty()) return;
1591 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1592 "Scope shouldn't contain decls!");
1594 for (auto *TmpD : S->decls()) {
1595 assert(TmpD && "This decl didn't get pushed??");
1597 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1598 NamedDecl *D = cast<NamedDecl>(TmpD);
1600 if (!D->getDeclName()) continue;
1602 // Diagnose unused variables in this scope.
1603 if (!S->hasUnrecoverableErrorOccurred()) {
1604 DiagnoseUnusedDecl(D);
1605 if (const auto *RD = dyn_cast<RecordDecl>(D))
1606 DiagnoseUnusedNestedTypedefs(RD);
1609 // If this was a forward reference to a label, verify it was defined.
1610 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1611 CheckPoppedLabel(LD, *this);
1613 // Remove this name from our lexical scope.
1614 IdResolver.RemoveDecl(D);
1618 /// \brief Look for an Objective-C class in the translation unit.
1620 /// \param Id The name of the Objective-C class we're looking for. If
1621 /// typo-correction fixes this name, the Id will be updated
1622 /// to the fixed name.
1624 /// \param IdLoc The location of the name in the translation unit.
1626 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1627 /// if there is no class with the given name.
1629 /// \returns The declaration of the named Objective-C class, or NULL if the
1630 /// class could not be found.
1631 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1632 SourceLocation IdLoc,
1633 bool DoTypoCorrection) {
1634 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1635 // creation from this context.
1636 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1638 if (!IDecl && DoTypoCorrection) {
1639 // Perform typo correction at the given location, but only if we
1640 // find an Objective-C class name.
1641 if (TypoCorrection C = CorrectTypo(
1642 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1643 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1644 CTK_ErrorRecovery)) {
1645 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1646 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1647 Id = IDecl->getIdentifier();
1650 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1651 // This routine must always return a class definition, if any.
1652 if (Def && Def->getDefinition())
1653 Def = Def->getDefinition();
1657 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1658 /// from S, where a non-field would be declared. This routine copes
1659 /// with the difference between C and C++ scoping rules in structs and
1660 /// unions. For example, the following code is well-formed in C but
1661 /// ill-formed in C++:
1667 /// void test_S6() {
1672 /// For the declaration of BAR, this routine will return a different
1673 /// scope. The scope S will be the scope of the unnamed enumeration
1674 /// within S6. In C++, this routine will return the scope associated
1675 /// with S6, because the enumeration's scope is a transparent
1676 /// context but structures can contain non-field names. In C, this
1677 /// routine will return the translation unit scope, since the
1678 /// enumeration's scope is a transparent context and structures cannot
1679 /// contain non-field names.
1680 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1681 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1682 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1683 (S->isClassScope() && !getLangOpts().CPlusPlus))
1688 /// \brief Looks up the declaration of "struct objc_super" and
1689 /// saves it for later use in building builtin declaration of
1690 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1691 /// pre-existing declaration exists no action takes place.
1692 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1693 IdentifierInfo *II) {
1694 if (!II->isStr("objc_msgSendSuper"))
1696 ASTContext &Context = ThisSema.Context;
1698 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1699 SourceLocation(), Sema::LookupTagName);
1700 ThisSema.LookupName(Result, S);
1701 if (Result.getResultKind() == LookupResult::Found)
1702 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1703 Context.setObjCSuperType(Context.getTagDeclType(TD));
1706 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1708 case ASTContext::GE_None:
1710 case ASTContext::GE_Missing_stdio:
1712 case ASTContext::GE_Missing_setjmp:
1714 case ASTContext::GE_Missing_ucontext:
1715 return "ucontext.h";
1717 llvm_unreachable("unhandled error kind");
1720 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1721 /// file scope. lazily create a decl for it. ForRedeclaration is true
1722 /// if we're creating this built-in in anticipation of redeclaring the
1724 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1725 Scope *S, bool ForRedeclaration,
1726 SourceLocation Loc) {
1727 LookupPredefedObjCSuperType(*this, S, II);
1729 ASTContext::GetBuiltinTypeError Error;
1730 QualType R = Context.GetBuiltinType(ID, Error);
1732 if (ForRedeclaration)
1733 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1734 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1738 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1739 Diag(Loc, diag::ext_implicit_lib_function_decl)
1740 << Context.BuiltinInfo.getName(ID) << R;
1741 if (Context.BuiltinInfo.getHeaderName(ID) &&
1742 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1743 Diag(Loc, diag::note_include_header_or_declare)
1744 << Context.BuiltinInfo.getHeaderName(ID)
1745 << 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(), AA->getStrict(),
2200 AA->getReplacement(), AMK,
2201 AttrSpellingListIndex);
2202 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2203 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2204 AttrSpellingListIndex);
2205 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2206 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2207 AttrSpellingListIndex);
2208 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2209 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2210 AttrSpellingListIndex);
2211 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2212 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2213 AttrSpellingListIndex);
2214 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2215 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2216 FA->getFormatIdx(), FA->getFirstArg(),
2217 AttrSpellingListIndex);
2218 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2219 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2220 AttrSpellingListIndex);
2221 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2222 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2223 AttrSpellingListIndex,
2224 IA->getSemanticSpelling());
2225 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2226 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2227 &S.Context.Idents.get(AA->getSpelling()),
2228 AttrSpellingListIndex);
2229 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2230 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2231 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2232 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2233 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2234 NewAttr = S.mergeInternalLinkageAttr(
2235 D, InternalLinkageA->getRange(),
2236 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2237 AttrSpellingListIndex);
2238 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2239 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2240 &S.Context.Idents.get(CommonA->getSpelling()),
2241 AttrSpellingListIndex);
2242 else if (isa<AlignedAttr>(Attr))
2243 // AlignedAttrs are handled separately, because we need to handle all
2244 // such attributes on a declaration at the same time.
2246 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2247 (AMK == Sema::AMK_Override ||
2248 AMK == Sema::AMK_ProtocolImplementation))
2250 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2251 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2254 NewAttr->setInherited(true);
2255 D->addAttr(NewAttr);
2256 if (isa<MSInheritanceAttr>(NewAttr))
2257 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2264 static const Decl *getDefinition(const Decl *D) {
2265 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2266 return TD->getDefinition();
2267 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2268 const VarDecl *Def = VD->getDefinition();
2271 return VD->getActingDefinition();
2273 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2274 const FunctionDecl* Def;
2275 if (FD->isDefined(Def))
2281 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2282 for (const auto *Attribute : D->attrs())
2283 if (Attribute->getKind() == Kind)
2288 /// checkNewAttributesAfterDef - If we already have a definition, check that
2289 /// there are no new attributes in this declaration.
2290 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2291 if (!New->hasAttrs())
2294 const Decl *Def = getDefinition(Old);
2295 if (!Def || Def == New)
2298 AttrVec &NewAttributes = New->getAttrs();
2299 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2300 const Attr *NewAttribute = NewAttributes[I];
2302 if (isa<AliasAttr>(NewAttribute)) {
2303 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2304 Sema::SkipBodyInfo SkipBody;
2305 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2307 // If we're skipping this definition, drop the "alias" attribute.
2308 if (SkipBody.ShouldSkip) {
2309 NewAttributes.erase(NewAttributes.begin() + I);
2314 VarDecl *VD = cast<VarDecl>(New);
2315 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2316 VarDecl::TentativeDefinition
2317 ? diag::err_alias_after_tentative
2318 : diag::err_redefinition;
2319 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2320 S.Diag(Def->getLocation(), diag::note_previous_definition);
2321 VD->setInvalidDecl();
2327 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2328 // Tentative definitions are only interesting for the alias check above.
2329 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2335 if (hasAttribute(Def, NewAttribute->getKind())) {
2337 continue; // regular attr merging will take care of validating this.
2340 if (isa<C11NoReturnAttr>(NewAttribute)) {
2341 // C's _Noreturn is allowed to be added to a function after it is defined.
2344 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2345 if (AA->isAlignas()) {
2346 // C++11 [dcl.align]p6:
2347 // if any declaration of an entity has an alignment-specifier,
2348 // every defining declaration of that entity shall specify an
2349 // equivalent alignment.
2351 // If the definition of an object does not have an alignment
2352 // specifier, any other declaration of that object shall also
2353 // have no alignment specifier.
2354 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2356 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2358 NewAttributes.erase(NewAttributes.begin() + I);
2364 S.Diag(NewAttribute->getLocation(),
2365 diag::warn_attribute_precede_definition);
2366 S.Diag(Def->getLocation(), diag::note_previous_definition);
2367 NewAttributes.erase(NewAttributes.begin() + I);
2372 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2373 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2374 AvailabilityMergeKind AMK) {
2375 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2376 UsedAttr *NewAttr = OldAttr->clone(Context);
2377 NewAttr->setInherited(true);
2378 New->addAttr(NewAttr);
2381 if (!Old->hasAttrs() && !New->hasAttrs())
2384 // Attributes declared post-definition are currently ignored.
2385 checkNewAttributesAfterDef(*this, New, Old);
2387 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2388 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2389 if (OldA->getLabel() != NewA->getLabel()) {
2390 // This redeclaration changes __asm__ label.
2391 Diag(New->getLocation(), diag::err_different_asm_label);
2392 Diag(OldA->getLocation(), diag::note_previous_declaration);
2394 } else if (Old->isUsed()) {
2395 // This redeclaration adds an __asm__ label to a declaration that has
2396 // already been ODR-used.
2397 Diag(New->getLocation(), diag::err_late_asm_label_name)
2398 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2402 // Re-declaration cannot add abi_tag's.
2403 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2404 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2405 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2406 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2407 NewTag) == OldAbiTagAttr->tags_end()) {
2408 Diag(NewAbiTagAttr->getLocation(),
2409 diag::err_new_abi_tag_on_redeclaration)
2411 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2415 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2416 Diag(Old->getLocation(), diag::note_previous_declaration);
2420 if (!Old->hasAttrs())
2423 bool foundAny = New->hasAttrs();
2425 // Ensure that any moving of objects within the allocated map is done before
2427 if (!foundAny) New->setAttrs(AttrVec());
2429 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2430 // Ignore deprecated/unavailable/availability attributes if requested.
2431 AvailabilityMergeKind LocalAMK = AMK_None;
2432 if (isa<DeprecatedAttr>(I) ||
2433 isa<UnavailableAttr>(I) ||
2434 isa<AvailabilityAttr>(I)) {
2439 case AMK_Redeclaration:
2441 case AMK_ProtocolImplementation:
2448 if (isa<UsedAttr>(I))
2451 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2455 if (mergeAlignedAttrs(*this, New, Old))
2458 if (!foundAny) New->dropAttrs();
2461 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2463 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2464 const ParmVarDecl *oldDecl,
2466 // C++11 [dcl.attr.depend]p2:
2467 // The first declaration of a function shall specify the
2468 // carries_dependency attribute for its declarator-id if any declaration
2469 // of the function specifies the carries_dependency attribute.
2470 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2471 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2472 S.Diag(CDA->getLocation(),
2473 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2474 // Find the first declaration of the parameter.
2475 // FIXME: Should we build redeclaration chains for function parameters?
2476 const FunctionDecl *FirstFD =
2477 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2478 const ParmVarDecl *FirstVD =
2479 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2480 S.Diag(FirstVD->getLocation(),
2481 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2484 if (!oldDecl->hasAttrs())
2487 bool foundAny = newDecl->hasAttrs();
2489 // Ensure that any moving of objects within the allocated map is
2490 // done before we process them.
2491 if (!foundAny) newDecl->setAttrs(AttrVec());
2493 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2494 if (!DeclHasAttr(newDecl, I)) {
2495 InheritableAttr *newAttr =
2496 cast<InheritableParamAttr>(I->clone(S.Context));
2497 newAttr->setInherited(true);
2498 newDecl->addAttr(newAttr);
2503 if (!foundAny) newDecl->dropAttrs();
2506 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2507 const ParmVarDecl *OldParam,
2509 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2510 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2511 if (*Oldnullability != *Newnullability) {
2512 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2513 << DiagNullabilityKind(
2515 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2517 << DiagNullabilityKind(
2519 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2521 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2524 QualType NewT = NewParam->getType();
2525 NewT = S.Context.getAttributedType(
2526 AttributedType::getNullabilityAttrKind(*Oldnullability),
2528 NewParam->setType(NewT);
2535 /// Used in MergeFunctionDecl to keep track of function parameters in
2537 struct GNUCompatibleParamWarning {
2538 ParmVarDecl *OldParm;
2539 ParmVarDecl *NewParm;
2540 QualType PromotedType;
2543 } // end anonymous namespace
2545 /// getSpecialMember - get the special member enum for a method.
2546 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2547 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2548 if (Ctor->isDefaultConstructor())
2549 return Sema::CXXDefaultConstructor;
2551 if (Ctor->isCopyConstructor())
2552 return Sema::CXXCopyConstructor;
2554 if (Ctor->isMoveConstructor())
2555 return Sema::CXXMoveConstructor;
2556 } else if (isa<CXXDestructorDecl>(MD)) {
2557 return Sema::CXXDestructor;
2558 } else if (MD->isCopyAssignmentOperator()) {
2559 return Sema::CXXCopyAssignment;
2560 } else if (MD->isMoveAssignmentOperator()) {
2561 return Sema::CXXMoveAssignment;
2564 return Sema::CXXInvalid;
2567 // Determine whether the previous declaration was a definition, implicit
2568 // declaration, or a declaration.
2569 template <typename T>
2570 static std::pair<diag::kind, SourceLocation>
2571 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2572 diag::kind PrevDiag;
2573 SourceLocation OldLocation = Old->getLocation();
2574 if (Old->isThisDeclarationADefinition())
2575 PrevDiag = diag::note_previous_definition;
2576 else if (Old->isImplicit()) {
2577 PrevDiag = diag::note_previous_implicit_declaration;
2578 if (OldLocation.isInvalid())
2579 OldLocation = New->getLocation();
2581 PrevDiag = diag::note_previous_declaration;
2582 return std::make_pair(PrevDiag, OldLocation);
2585 /// canRedefineFunction - checks if a function can be redefined. Currently,
2586 /// only extern inline functions can be redefined, and even then only in
2588 static bool canRedefineFunction(const FunctionDecl *FD,
2589 const LangOptions& LangOpts) {
2590 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2591 !LangOpts.CPlusPlus &&
2592 FD->isInlineSpecified() &&
2593 FD->getStorageClass() == SC_Extern);
2596 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2597 const AttributedType *AT = T->getAs<AttributedType>();
2598 while (AT && !AT->isCallingConv())
2599 AT = AT->getModifiedType()->getAs<AttributedType>();
2603 template <typename T>
2604 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2605 const DeclContext *DC = Old->getDeclContext();
2609 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2610 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2612 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2617 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2618 static bool isExternC(VarTemplateDecl *) { return false; }
2620 /// \brief Check whether a redeclaration of an entity introduced by a
2621 /// using-declaration is valid, given that we know it's not an overload
2622 /// (nor a hidden tag declaration).
2623 template<typename ExpectedDecl>
2624 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2625 ExpectedDecl *New) {
2626 // C++11 [basic.scope.declarative]p4:
2627 // Given a set of declarations in a single declarative region, each of
2628 // which specifies the same unqualified name,
2629 // -- they shall all refer to the same entity, or all refer to functions
2630 // and function templates; or
2631 // -- exactly one declaration shall declare a class name or enumeration
2632 // name that is not a typedef name and the other declarations shall all
2633 // refer to the same variable or enumerator, or all refer to functions
2634 // and function templates; in this case the class name or enumeration
2635 // name is hidden (3.3.10).
2637 // C++11 [namespace.udecl]p14:
2638 // If a function declaration in namespace scope or block scope has the
2639 // same name and the same parameter-type-list as a function introduced
2640 // by a using-declaration, and the declarations do not declare the same
2641 // function, the program is ill-formed.
2643 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2645 !Old->getDeclContext()->getRedeclContext()->Equals(
2646 New->getDeclContext()->getRedeclContext()) &&
2647 !(isExternC(Old) && isExternC(New)))
2651 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2652 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2653 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2659 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2660 const FunctionDecl *B) {
2661 assert(A->getNumParams() == B->getNumParams());
2663 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2664 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2665 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2668 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2671 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2674 /// MergeFunctionDecl - We just parsed a function 'New' from
2675 /// declarator D which has the same name and scope as a previous
2676 /// declaration 'Old'. Figure out how to resolve this situation,
2677 /// merging decls or emitting diagnostics as appropriate.
2679 /// In C++, New and Old must be declarations that are not
2680 /// overloaded. Use IsOverload to determine whether New and Old are
2681 /// overloaded, and to select the Old declaration that New should be
2684 /// Returns true if there was an error, false otherwise.
2685 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2686 Scope *S, bool MergeTypeWithOld) {
2687 // Verify the old decl was also a function.
2688 FunctionDecl *Old = OldD->getAsFunction();
2690 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2691 if (New->getFriendObjectKind()) {
2692 Diag(New->getLocation(), diag::err_using_decl_friend);
2693 Diag(Shadow->getTargetDecl()->getLocation(),
2694 diag::note_using_decl_target);
2695 Diag(Shadow->getUsingDecl()->getLocation(),
2696 diag::note_using_decl) << 0;
2700 // Check whether the two declarations might declare the same function.
2701 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2703 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2705 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2706 << New->getDeclName();
2707 Diag(OldD->getLocation(), diag::note_previous_definition);
2712 // If the old declaration is invalid, just give up here.
2713 if (Old->isInvalidDecl())
2716 diag::kind PrevDiag;
2717 SourceLocation OldLocation;
2718 std::tie(PrevDiag, OldLocation) =
2719 getNoteDiagForInvalidRedeclaration(Old, New);
2721 // Don't complain about this if we're in GNU89 mode and the old function
2722 // is an extern inline function.
2723 // Don't complain about specializations. They are not supposed to have
2725 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2726 New->getStorageClass() == SC_Static &&
2727 Old->hasExternalFormalLinkage() &&
2728 !New->getTemplateSpecializationInfo() &&
2729 !canRedefineFunction(Old, getLangOpts())) {
2730 if (getLangOpts().MicrosoftExt) {
2731 Diag(New->getLocation(), diag::ext_static_non_static) << New;
2732 Diag(OldLocation, PrevDiag);
2734 Diag(New->getLocation(), diag::err_static_non_static) << New;
2735 Diag(OldLocation, PrevDiag);
2740 if (New->hasAttr<InternalLinkageAttr>() &&
2741 !Old->hasAttr<InternalLinkageAttr>()) {
2742 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2743 << New->getDeclName();
2744 Diag(Old->getLocation(), diag::note_previous_definition);
2745 New->dropAttr<InternalLinkageAttr>();
2748 // If a function is first declared with a calling convention, but is later
2749 // declared or defined without one, all following decls assume the calling
2750 // convention of the first.
2752 // It's OK if a function is first declared without a calling convention,
2753 // but is later declared or defined with the default calling convention.
2755 // To test if either decl has an explicit calling convention, we look for
2756 // AttributedType sugar nodes on the type as written. If they are missing or
2757 // were canonicalized away, we assume the calling convention was implicit.
2759 // Note also that we DO NOT return at this point, because we still have
2760 // other tests to run.
2761 QualType OldQType = Context.getCanonicalType(Old->getType());
2762 QualType NewQType = Context.getCanonicalType(New->getType());
2763 const FunctionType *OldType = cast<FunctionType>(OldQType);
2764 const FunctionType *NewType = cast<FunctionType>(NewQType);
2765 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2766 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2767 bool RequiresAdjustment = false;
2769 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2770 FunctionDecl *First = Old->getFirstDecl();
2771 const FunctionType *FT =
2772 First->getType().getCanonicalType()->castAs<FunctionType>();
2773 FunctionType::ExtInfo FI = FT->getExtInfo();
2774 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2775 if (!NewCCExplicit) {
2776 // Inherit the CC from the previous declaration if it was specified
2777 // there but not here.
2778 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2779 RequiresAdjustment = true;
2781 // Calling conventions aren't compatible, so complain.
2782 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2783 Diag(New->getLocation(), diag::err_cconv_change)
2784 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2786 << (!FirstCCExplicit ? "" :
2787 FunctionType::getNameForCallConv(FI.getCC()));
2789 // Put the note on the first decl, since it is the one that matters.
2790 Diag(First->getLocation(), diag::note_previous_declaration);
2795 // FIXME: diagnose the other way around?
2796 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2797 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2798 RequiresAdjustment = true;
2801 // Merge regparm attribute.
2802 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2803 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2804 if (NewTypeInfo.getHasRegParm()) {
2805 Diag(New->getLocation(), diag::err_regparm_mismatch)
2806 << NewType->getRegParmType()
2807 << OldType->getRegParmType();
2808 Diag(OldLocation, diag::note_previous_declaration);
2812 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2813 RequiresAdjustment = true;
2816 // Merge ns_returns_retained attribute.
2817 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2818 if (NewTypeInfo.getProducesResult()) {
2819 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2820 Diag(OldLocation, diag::note_previous_declaration);
2824 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2825 RequiresAdjustment = true;
2828 if (RequiresAdjustment) {
2829 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2830 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2831 New->setType(QualType(AdjustedType, 0));
2832 NewQType = Context.getCanonicalType(New->getType());
2833 NewType = cast<FunctionType>(NewQType);
2836 // If this redeclaration makes the function inline, we may need to add it to
2837 // UndefinedButUsed.
2838 if (!Old->isInlined() && New->isInlined() &&
2839 !New->hasAttr<GNUInlineAttr>() &&
2840 !getLangOpts().GNUInline &&
2841 Old->isUsed(false) &&
2842 !Old->isDefined() && !New->isThisDeclarationADefinition())
2843 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2846 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2848 if (New->hasAttr<GNUInlineAttr>() &&
2849 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2850 UndefinedButUsed.erase(Old->getCanonicalDecl());
2853 // If pass_object_size params don't match up perfectly, this isn't a valid
2855 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2856 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2857 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2858 << New->getDeclName();
2859 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2863 if (getLangOpts().CPlusPlus) {
2865 // Certain function declarations cannot be overloaded:
2866 // -- Function declarations that differ only in the return type
2867 // cannot be overloaded.
2869 // Go back to the type source info to compare the declared return types,
2870 // per C++1y [dcl.type.auto]p13:
2871 // Redeclarations or specializations of a function or function template
2872 // with a declared return type that uses a placeholder type shall also
2873 // use that placeholder, not a deduced type.
2874 QualType OldDeclaredReturnType =
2875 (Old->getTypeSourceInfo()
2876 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2877 : OldType)->getReturnType();
2878 QualType NewDeclaredReturnType =
2879 (New->getTypeSourceInfo()
2880 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2881 : NewType)->getReturnType();
2883 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2884 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2885 New->isLocalExternDecl())) {
2886 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2887 OldDeclaredReturnType->isObjCObjectPointerType())
2888 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2889 if (ResQT.isNull()) {
2890 if (New->isCXXClassMember() && New->isOutOfLine())
2891 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2892 << New << New->getReturnTypeSourceRange();
2894 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2895 << New->getReturnTypeSourceRange();
2896 Diag(OldLocation, PrevDiag) << Old << Old->getType()
2897 << Old->getReturnTypeSourceRange();
2904 QualType OldReturnType = OldType->getReturnType();
2905 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2906 if (OldReturnType != NewReturnType) {
2907 // If this function has a deduced return type and has already been
2908 // defined, copy the deduced value from the old declaration.
2909 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2910 if (OldAT && OldAT->isDeduced()) {
2912 SubstAutoType(New->getType(),
2913 OldAT->isDependentType() ? Context.DependentTy
2914 : OldAT->getDeducedType()));
2915 NewQType = Context.getCanonicalType(
2916 SubstAutoType(NewQType,
2917 OldAT->isDependentType() ? Context.DependentTy
2918 : OldAT->getDeducedType()));
2922 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2923 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2924 if (OldMethod && NewMethod) {
2925 // Preserve triviality.
2926 NewMethod->setTrivial(OldMethod->isTrivial());
2928 // MSVC allows explicit template specialization at class scope:
2929 // 2 CXXMethodDecls referring to the same function will be injected.
2930 // We don't want a redeclaration error.
2931 bool IsClassScopeExplicitSpecialization =
2932 OldMethod->isFunctionTemplateSpecialization() &&
2933 NewMethod->isFunctionTemplateSpecialization();
2934 bool isFriend = NewMethod->getFriendObjectKind();
2936 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2937 !IsClassScopeExplicitSpecialization) {
2938 // -- Member function declarations with the same name and the
2939 // same parameter types cannot be overloaded if any of them
2940 // is a static member function declaration.
2941 if (OldMethod->isStatic() != NewMethod->isStatic()) {
2942 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2943 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2947 // C++ [class.mem]p1:
2948 // [...] A member shall not be declared twice in the
2949 // member-specification, except that a nested class or member
2950 // class template can be declared and then later defined.
2951 if (ActiveTemplateInstantiations.empty()) {
2953 if (isa<CXXConstructorDecl>(OldMethod))
2954 NewDiag = diag::err_constructor_redeclared;
2955 else if (isa<CXXDestructorDecl>(NewMethod))
2956 NewDiag = diag::err_destructor_redeclared;
2957 else if (isa<CXXConversionDecl>(NewMethod))
2958 NewDiag = diag::err_conv_function_redeclared;
2960 NewDiag = diag::err_member_redeclared;
2962 Diag(New->getLocation(), NewDiag);
2964 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2965 << New << New->getType();
2967 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2970 // Complain if this is an explicit declaration of a special
2971 // member that was initially declared implicitly.
2973 // As an exception, it's okay to befriend such methods in order
2974 // to permit the implicit constructor/destructor/operator calls.
2975 } else if (OldMethod->isImplicit()) {
2977 NewMethod->setImplicit();
2979 Diag(NewMethod->getLocation(),
2980 diag::err_definition_of_implicitly_declared_member)
2981 << New << getSpecialMember(OldMethod);
2984 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2985 Diag(NewMethod->getLocation(),
2986 diag::err_definition_of_explicitly_defaulted_member)
2987 << getSpecialMember(OldMethod);
2992 // C++11 [dcl.attr.noreturn]p1:
2993 // The first declaration of a function shall specify the noreturn
2994 // attribute if any declaration of that function specifies the noreturn
2996 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2997 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2998 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2999 Diag(Old->getFirstDecl()->getLocation(),
3000 diag::note_noreturn_missing_first_decl);
3003 // C++11 [dcl.attr.depend]p2:
3004 // The first declaration of a function shall specify the
3005 // carries_dependency attribute for its declarator-id if any declaration
3006 // of the function specifies the carries_dependency attribute.
3007 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3008 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3009 Diag(CDA->getLocation(),
3010 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3011 Diag(Old->getFirstDecl()->getLocation(),
3012 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3016 // All declarations for a function shall agree exactly in both the
3017 // return type and the parameter-type-list.
3018 // We also want to respect all the extended bits except noreturn.
3020 // noreturn should now match unless the old type info didn't have it.
3021 QualType OldQTypeForComparison = OldQType;
3022 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3023 assert(OldQType == QualType(OldType, 0));
3024 const FunctionType *OldTypeForComparison
3025 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3026 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3027 assert(OldQTypeForComparison.isCanonical());
3030 if (haveIncompatibleLanguageLinkages(Old, New)) {
3031 // As a special case, retain the language linkage from previous
3032 // declarations of a friend function as an extension.
3034 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3035 // and is useful because there's otherwise no way to specify language
3036 // linkage within class scope.
3038 // Check cautiously as the friend object kind isn't yet complete.
3039 if (New->getFriendObjectKind() != Decl::FOK_None) {
3040 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3041 Diag(OldLocation, PrevDiag);
3043 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3044 Diag(OldLocation, PrevDiag);
3049 if (OldQTypeForComparison == NewQType)
3050 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3052 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3053 New->isLocalExternDecl()) {
3054 // It's OK if we couldn't merge types for a local function declaraton
3055 // if either the old or new type is dependent. We'll merge the types
3056 // when we instantiate the function.
3060 // Fall through for conflicting redeclarations and redefinitions.
3063 // C: Function types need to be compatible, not identical. This handles
3064 // duplicate function decls like "void f(int); void f(enum X);" properly.
3065 if (!getLangOpts().CPlusPlus &&
3066 Context.typesAreCompatible(OldQType, NewQType)) {
3067 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3068 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3069 const FunctionProtoType *OldProto = nullptr;
3070 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3071 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3072 // The old declaration provided a function prototype, but the
3073 // new declaration does not. Merge in the prototype.
3074 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3075 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3077 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3078 OldProto->getExtProtoInfo());
3079 New->setType(NewQType);
3080 New->setHasInheritedPrototype();
3082 // Synthesize parameters with the same types.
3083 SmallVector<ParmVarDecl*, 16> Params;
3084 for (const auto &ParamType : OldProto->param_types()) {
3085 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3086 SourceLocation(), nullptr,
3087 ParamType, /*TInfo=*/nullptr,
3089 Param->setScopeInfo(0, Params.size());
3090 Param->setImplicit();
3091 Params.push_back(Param);
3094 New->setParams(Params);
3097 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3100 // GNU C permits a K&R definition to follow a prototype declaration
3101 // if the declared types of the parameters in the K&R definition
3102 // match the types in the prototype declaration, even when the
3103 // promoted types of the parameters from the K&R definition differ
3104 // from the types in the prototype. GCC then keeps the types from
3107 // If a variadic prototype is followed by a non-variadic K&R definition,
3108 // the K&R definition becomes variadic. This is sort of an edge case, but
3109 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3111 if (!getLangOpts().CPlusPlus &&
3112 Old->hasPrototype() && !New->hasPrototype() &&
3113 New->getType()->getAs<FunctionProtoType>() &&
3114 Old->getNumParams() == New->getNumParams()) {
3115 SmallVector<QualType, 16> ArgTypes;
3116 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3117 const FunctionProtoType *OldProto
3118 = Old->getType()->getAs<FunctionProtoType>();
3119 const FunctionProtoType *NewProto
3120 = New->getType()->getAs<FunctionProtoType>();
3122 // Determine whether this is the GNU C extension.
3123 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3124 NewProto->getReturnType());
3125 bool LooseCompatible = !MergedReturn.isNull();
3126 for (unsigned Idx = 0, End = Old->getNumParams();
3127 LooseCompatible && Idx != End; ++Idx) {
3128 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3129 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3130 if (Context.typesAreCompatible(OldParm->getType(),
3131 NewProto->getParamType(Idx))) {
3132 ArgTypes.push_back(NewParm->getType());
3133 } else if (Context.typesAreCompatible(OldParm->getType(),
3135 /*CompareUnqualified=*/true)) {
3136 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3137 NewProto->getParamType(Idx) };
3138 Warnings.push_back(Warn);
3139 ArgTypes.push_back(NewParm->getType());
3141 LooseCompatible = false;
3144 if (LooseCompatible) {
3145 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3146 Diag(Warnings[Warn].NewParm->getLocation(),
3147 diag::ext_param_promoted_not_compatible_with_prototype)
3148 << Warnings[Warn].PromotedType
3149 << Warnings[Warn].OldParm->getType();
3150 if (Warnings[Warn].OldParm->getLocation().isValid())
3151 Diag(Warnings[Warn].OldParm->getLocation(),
3152 diag::note_previous_declaration);
3155 if (MergeTypeWithOld)
3156 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3157 OldProto->getExtProtoInfo()));
3158 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3161 // Fall through to diagnose conflicting types.
3164 // A function that has already been declared has been redeclared or
3165 // defined with a different type; show an appropriate diagnostic.
3167 // If the previous declaration was an implicitly-generated builtin
3168 // declaration, then at the very least we should use a specialized note.
3170 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3171 // If it's actually a library-defined builtin function like 'malloc'
3172 // or 'printf', just warn about the incompatible redeclaration.
3173 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3174 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3175 Diag(OldLocation, diag::note_previous_builtin_declaration)
3176 << Old << Old->getType();
3178 // If this is a global redeclaration, just forget hereafter
3179 // about the "builtin-ness" of the function.
3181 // Doing this for local extern declarations is problematic. If
3182 // the builtin declaration remains visible, a second invalid
3183 // local declaration will produce a hard error; if it doesn't
3184 // remain visible, a single bogus local redeclaration (which is
3185 // actually only a warning) could break all the downstream code.
3186 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3187 New->getIdentifier()->revertBuiltin();
3192 PrevDiag = diag::note_previous_builtin_declaration;
3195 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3196 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3200 /// \brief Completes the merge of two function declarations that are
3201 /// known to be compatible.
3203 /// This routine handles the merging of attributes and other
3204 /// properties of function declarations from the old declaration to
3205 /// the new declaration, once we know that New is in fact a
3206 /// redeclaration of Old.
3209 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3210 Scope *S, bool MergeTypeWithOld) {
3211 // Merge the attributes
3212 mergeDeclAttributes(New, Old);
3214 // Merge "pure" flag.
3218 // Merge "used" flag.
3219 if (Old->getMostRecentDecl()->isUsed(false))
3222 // Merge attributes from the parameters. These can mismatch with K&R
3224 if (New->getNumParams() == Old->getNumParams())
3225 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3226 ParmVarDecl *NewParam = New->getParamDecl(i);
3227 ParmVarDecl *OldParam = Old->getParamDecl(i);
3228 mergeParamDeclAttributes(NewParam, OldParam, *this);
3229 mergeParamDeclTypes(NewParam, OldParam, *this);
3232 if (getLangOpts().CPlusPlus)
3233 return MergeCXXFunctionDecl(New, Old, S);
3235 // Merge the function types so the we get the composite types for the return
3236 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3238 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3239 if (!Merged.isNull() && MergeTypeWithOld)
3240 New->setType(Merged);
3245 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3246 ObjCMethodDecl *oldMethod) {
3247 // Merge the attributes, including deprecated/unavailable
3248 AvailabilityMergeKind MergeKind =
3249 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3250 ? AMK_ProtocolImplementation
3251 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3254 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3256 // Merge attributes from the parameters.
3257 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3258 oe = oldMethod->param_end();
3259 for (ObjCMethodDecl::param_iterator
3260 ni = newMethod->param_begin(), ne = newMethod->param_end();
3261 ni != ne && oi != oe; ++ni, ++oi)
3262 mergeParamDeclAttributes(*ni, *oi, *this);
3264 CheckObjCMethodOverride(newMethod, oldMethod);
3267 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3268 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3270 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3271 ? diag::err_redefinition_different_type
3272 : diag::err_redeclaration_different_type)
3273 << New->getDeclName() << New->getType() << Old->getType();
3275 diag::kind PrevDiag;
3276 SourceLocation OldLocation;
3277 std::tie(PrevDiag, OldLocation)
3278 = getNoteDiagForInvalidRedeclaration(Old, New);
3279 S.Diag(OldLocation, PrevDiag);
3280 New->setInvalidDecl();
3283 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3284 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3285 /// emitting diagnostics as appropriate.
3287 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3288 /// to here in AddInitializerToDecl. We can't check them before the initializer
3290 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3291 bool MergeTypeWithOld) {
3292 if (New->isInvalidDecl() || Old->isInvalidDecl())
3296 if (getLangOpts().CPlusPlus) {
3297 if (New->getType()->isUndeducedType()) {
3298 // We don't know what the new type is until the initializer is attached.
3300 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3301 // These could still be something that needs exception specs checked.
3302 return MergeVarDeclExceptionSpecs(New, Old);
3304 // C++ [basic.link]p10:
3305 // [...] the types specified by all declarations referring to a given
3306 // object or function shall be identical, except that declarations for an
3307 // array object can specify array types that differ by the presence or
3308 // absence of a major array bound (8.3.4).
3309 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3310 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3311 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3313 // We are merging a variable declaration New into Old. If it has an array
3314 // bound, and that bound differs from Old's bound, we should diagnose the
3316 if (!NewArray->isIncompleteArrayType()) {
3317 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3318 PrevVD = PrevVD->getPreviousDecl()) {
3319 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3320 if (PrevVDTy->isIncompleteArrayType())
3323 if (!Context.hasSameType(NewArray, PrevVDTy))
3324 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3328 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3329 if (Context.hasSameType(OldArray->getElementType(),
3330 NewArray->getElementType()))
3331 MergedT = New->getType();
3333 // FIXME: Check visibility. New is hidden but has a complete type. If New
3334 // has no array bound, it should not inherit one from Old, if Old is not
3336 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3337 if (Context.hasSameType(OldArray->getElementType(),
3338 NewArray->getElementType()))
3339 MergedT = Old->getType();
3342 else if (New->getType()->isObjCObjectPointerType() &&
3343 Old->getType()->isObjCObjectPointerType()) {
3344 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3349 // All declarations that refer to the same object or function shall have
3351 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3353 if (MergedT.isNull()) {
3354 // It's OK if we couldn't merge types if either type is dependent, for a
3355 // block-scope variable. In other cases (static data members of class
3356 // templates, variable templates, ...), we require the types to be
3358 // FIXME: The C++ standard doesn't say anything about this.
3359 if ((New->getType()->isDependentType() ||
3360 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3361 // If the old type was dependent, we can't merge with it, so the new type
3362 // becomes dependent for now. We'll reproduce the original type when we
3363 // instantiate the TypeSourceInfo for the variable.
3364 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3365 New->setType(Context.DependentTy);
3368 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3371 // Don't actually update the type on the new declaration if the old
3372 // declaration was an extern declaration in a different scope.
3373 if (MergeTypeWithOld)
3374 New->setType(MergedT);
3377 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3378 LookupResult &Previous) {
3380 // For an identifier with internal or external linkage declared
3381 // in a scope in which a prior declaration of that identifier is
3382 // visible, if the prior declaration specifies internal or
3383 // external linkage, the type of the identifier at the later
3384 // declaration becomes the composite type.
3386 // If the variable isn't visible, we do not merge with its type.
3387 if (Previous.isShadowed())
3390 if (S.getLangOpts().CPlusPlus) {
3391 // C++11 [dcl.array]p3:
3392 // If there is a preceding declaration of the entity in the same
3393 // scope in which the bound was specified, an omitted array bound
3394 // is taken to be the same as in that earlier declaration.
3395 return NewVD->isPreviousDeclInSameBlockScope() ||
3396 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3397 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3399 // If the old declaration was function-local, don't merge with its
3400 // type unless we're in the same function.
3401 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3402 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3406 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3407 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3408 /// situation, merging decls or emitting diagnostics as appropriate.
3410 /// Tentative definition rules (C99 6.9.2p2) are checked by
3411 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3412 /// definitions here, since the initializer hasn't been attached.
3414 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3415 // If the new decl is already invalid, don't do any other checking.
3416 if (New->isInvalidDecl())
3419 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3422 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3424 // Verify the old decl was also a variable or variable template.
3425 VarDecl *Old = nullptr;
3426 VarTemplateDecl *OldTemplate = nullptr;
3427 if (Previous.isSingleResult()) {
3429 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3430 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3433 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3434 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3435 return New->setInvalidDecl();
3437 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3440 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3441 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3442 return New->setInvalidDecl();
3446 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3447 << New->getDeclName();
3448 Diag(Previous.getRepresentativeDecl()->getLocation(),
3449 diag::note_previous_definition);
3450 return New->setInvalidDecl();
3453 // Ensure the template parameters are compatible.
3455 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3456 OldTemplate->getTemplateParameters(),
3457 /*Complain=*/true, TPL_TemplateMatch))
3458 return New->setInvalidDecl();
3460 // C++ [class.mem]p1:
3461 // A member shall not be declared twice in the member-specification [...]
3463 // Here, we need only consider static data members.
3464 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3465 Diag(New->getLocation(), diag::err_duplicate_member)
3466 << New->getIdentifier();
3467 Diag(Old->getLocation(), diag::note_previous_declaration);
3468 New->setInvalidDecl();
3471 mergeDeclAttributes(New, Old);
3472 // Warn if an already-declared variable is made a weak_import in a subsequent
3474 if (New->hasAttr<WeakImportAttr>() &&
3475 Old->getStorageClass() == SC_None &&
3476 !Old->hasAttr<WeakImportAttr>()) {
3477 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3478 Diag(Old->getLocation(), diag::note_previous_definition);
3479 // Remove weak_import attribute on new declaration.
3480 New->dropAttr<WeakImportAttr>();
3483 if (New->hasAttr<InternalLinkageAttr>() &&
3484 !Old->hasAttr<InternalLinkageAttr>()) {
3485 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3486 << New->getDeclName();
3487 Diag(Old->getLocation(), diag::note_previous_definition);
3488 New->dropAttr<InternalLinkageAttr>();
3492 VarDecl *MostRecent = Old->getMostRecentDecl();
3493 if (MostRecent != Old) {
3494 MergeVarDeclTypes(New, MostRecent,
3495 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3496 if (New->isInvalidDecl())
3500 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3501 if (New->isInvalidDecl())
3504 diag::kind PrevDiag;
3505 SourceLocation OldLocation;
3506 std::tie(PrevDiag, OldLocation) =
3507 getNoteDiagForInvalidRedeclaration(Old, New);
3509 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3510 if (New->getStorageClass() == SC_Static &&
3511 !New->isStaticDataMember() &&
3512 Old->hasExternalFormalLinkage()) {
3513 if (getLangOpts().MicrosoftExt) {
3514 Diag(New->getLocation(), diag::ext_static_non_static)
3515 << New->getDeclName();
3516 Diag(OldLocation, PrevDiag);
3518 Diag(New->getLocation(), diag::err_static_non_static)
3519 << New->getDeclName();
3520 Diag(OldLocation, PrevDiag);
3521 return New->setInvalidDecl();
3525 // For an identifier declared with the storage-class specifier
3526 // extern in a scope in which a prior declaration of that
3527 // identifier is visible,23) if the prior declaration specifies
3528 // internal or external linkage, the linkage of the identifier at
3529 // the later declaration is the same as the linkage specified at
3530 // the prior declaration. If no prior declaration is visible, or
3531 // if the prior declaration specifies no linkage, then the
3532 // identifier has external linkage.
3533 if (New->hasExternalStorage() && Old->hasLinkage())
3535 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3536 !New->isStaticDataMember() &&
3537 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3538 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3539 Diag(OldLocation, PrevDiag);
3540 return New->setInvalidDecl();
3543 // Check if extern is followed by non-extern and vice-versa.
3544 if (New->hasExternalStorage() &&
3545 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3546 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3547 Diag(OldLocation, PrevDiag);
3548 return New->setInvalidDecl();
3550 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3551 !New->hasExternalStorage()) {
3552 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3553 Diag(OldLocation, PrevDiag);
3554 return New->setInvalidDecl();
3557 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3559 // FIXME: The test for external storage here seems wrong? We still
3560 // need to check for mismatches.
3561 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3562 // Don't complain about out-of-line definitions of static members.
3563 !(Old->getLexicalDeclContext()->isRecord() &&
3564 !New->getLexicalDeclContext()->isRecord())) {
3565 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3566 Diag(OldLocation, PrevDiag);
3567 return New->setInvalidDecl();
3570 if (New->getTLSKind() != Old->getTLSKind()) {
3571 if (!Old->getTLSKind()) {
3572 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3573 Diag(OldLocation, PrevDiag);
3574 } else if (!New->getTLSKind()) {
3575 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3576 Diag(OldLocation, PrevDiag);
3578 // Do not allow redeclaration to change the variable between requiring
3579 // static and dynamic initialization.
3580 // FIXME: GCC allows this, but uses the TLS keyword on the first
3581 // declaration to determine the kind. Do we need to be compatible here?
3582 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3583 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3584 Diag(OldLocation, PrevDiag);
3588 // C++ doesn't have tentative definitions, so go right ahead and check here.
3590 if (getLangOpts().CPlusPlus &&
3591 New->isThisDeclarationADefinition() == VarDecl::Definition &&
3592 (Def = Old->getDefinition())) {
3593 NamedDecl *Hidden = nullptr;
3594 if (!hasVisibleDefinition(Def, &Hidden) &&
3595 (New->getFormalLinkage() == InternalLinkage ||
3596 New->getDescribedVarTemplate() ||
3597 New->getNumTemplateParameterLists() ||
3598 New->getDeclContext()->isDependentContext())) {
3599 // The previous definition is hidden, and multiple definitions are
3600 // permitted (in separate TUs). Form another definition of it.
3602 Diag(New->getLocation(), diag::err_redefinition) << New;
3603 Diag(Def->getLocation(), diag::note_previous_definition);
3604 New->setInvalidDecl();
3609 if (haveIncompatibleLanguageLinkages(Old, New)) {
3610 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3611 Diag(OldLocation, PrevDiag);
3612 New->setInvalidDecl();
3616 // Merge "used" flag.
3617 if (Old->getMostRecentDecl()->isUsed(false))
3620 // Keep a chain of previous declarations.
3621 New->setPreviousDecl(Old);
3623 NewTemplate->setPreviousDecl(OldTemplate);
3625 // Inherit access appropriately.
3626 New->setAccess(Old->getAccess());
3628 NewTemplate->setAccess(New->getAccess());
3631 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3632 /// no declarator (e.g. "struct foo;") is parsed.
3634 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3635 RecordDecl *&AnonRecord) {
3636 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3640 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3641 // disambiguate entities defined in different scopes.
3642 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3644 // We will pick our mangling number depending on which version of MSVC is being
3646 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3647 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3648 ? S->getMSCurManglingNumber()
3649 : S->getMSLastManglingNumber();
3652 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3653 if (!Context.getLangOpts().CPlusPlus)
3656 if (isa<CXXRecordDecl>(Tag->getParent())) {
3657 // If this tag is the direct child of a class, number it if
3659 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3661 MangleNumberingContext &MCtx =
3662 Context.getManglingNumberContext(Tag->getParent());
3663 Context.setManglingNumber(
3664 Tag, MCtx.getManglingNumber(
3665 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3669 // If this tag isn't a direct child of a class, number it if it is local.
3670 Decl *ManglingContextDecl;
3671 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3672 Tag->getDeclContext(), ManglingContextDecl)) {
3673 Context.setManglingNumber(
3674 Tag, MCtx->getManglingNumber(
3675 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3679 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3680 TypedefNameDecl *NewTD) {
3681 if (TagFromDeclSpec->isInvalidDecl())
3684 // Do nothing if the tag already has a name for linkage purposes.
3685 if (TagFromDeclSpec->hasNameForLinkage())
3688 // A well-formed anonymous tag must always be a TUK_Definition.
3689 assert(TagFromDeclSpec->isThisDeclarationADefinition());
3691 // The type must match the tag exactly; no qualifiers allowed.
3692 if (!Context.hasSameType(NewTD->getUnderlyingType(),
3693 Context.getTagDeclType(TagFromDeclSpec))) {
3694 if (getLangOpts().CPlusPlus)
3695 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3699 // If we've already computed linkage for the anonymous tag, then
3700 // adding a typedef name for the anonymous decl can change that
3701 // linkage, which might be a serious problem. Diagnose this as
3702 // unsupported and ignore the typedef name. TODO: we should
3703 // pursue this as a language defect and establish a formal rule
3704 // for how to handle it.
3705 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3706 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3708 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3709 tagLoc = getLocForEndOfToken(tagLoc);
3711 llvm::SmallString<40> textToInsert;
3712 textToInsert += ' ';
3713 textToInsert += NewTD->getIdentifier()->getName();
3714 Diag(tagLoc, diag::note_typedef_changes_linkage)
3715 << FixItHint::CreateInsertion(tagLoc, textToInsert);
3719 // Otherwise, set this is the anon-decl typedef for the tag.
3720 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3723 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3725 case DeclSpec::TST_class:
3727 case DeclSpec::TST_struct:
3729 case DeclSpec::TST_interface:
3731 case DeclSpec::TST_union:
3733 case DeclSpec::TST_enum:
3736 llvm_unreachable("unexpected type specifier");
3740 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3741 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3742 /// parameters to cope with template friend declarations.
3744 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3745 MultiTemplateParamsArg TemplateParams,
3746 bool IsExplicitInstantiation,
3747 RecordDecl *&AnonRecord) {
3748 Decl *TagD = nullptr;
3749 TagDecl *Tag = nullptr;
3750 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3751 DS.getTypeSpecType() == DeclSpec::TST_struct ||
3752 DS.getTypeSpecType() == DeclSpec::TST_interface ||
3753 DS.getTypeSpecType() == DeclSpec::TST_union ||
3754 DS.getTypeSpecType() == DeclSpec::TST_enum) {
3755 TagD = DS.getRepAsDecl();
3757 if (!TagD) // We probably had an error
3760 // Note that the above type specs guarantee that the
3761 // type rep is a Decl, whereas in many of the others
3763 if (isa<TagDecl>(TagD))
3764 Tag = cast<TagDecl>(TagD);
3765 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3766 Tag = CTD->getTemplatedDecl();
3770 handleTagNumbering(Tag, S);
3771 Tag->setFreeStanding();
3772 if (Tag->isInvalidDecl())
3776 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3777 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3778 // or incomplete types shall not be restrict-qualified."
3779 if (TypeQuals & DeclSpec::TQ_restrict)
3780 Diag(DS.getRestrictSpecLoc(),
3781 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3782 << DS.getSourceRange();
3785 if (DS.isConstexprSpecified()) {
3786 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3787 // and definitions of functions and variables.
3789 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3790 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3792 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3793 // Don't emit warnings after this error.
3797 if (DS.isConceptSpecified()) {
3798 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3799 // either a function concept and its definition or a variable concept and
3801 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3805 DiagnoseFunctionSpecifiers(DS);
3807 if (DS.isFriendSpecified()) {
3808 // If we're dealing with a decl but not a TagDecl, assume that
3809 // whatever routines created it handled the friendship aspect.
3812 return ActOnFriendTypeDecl(S, DS, TemplateParams);
3815 const CXXScopeSpec &SS = DS.getTypeSpecScope();
3816 bool IsExplicitSpecialization =
3817 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3818 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3819 !IsExplicitInstantiation && !IsExplicitSpecialization &&
3820 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3821 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3822 // nested-name-specifier unless it is an explicit instantiation
3823 // or an explicit specialization.
3825 // FIXME: We allow class template partial specializations here too, per the
3826 // obvious intent of DR1819.
3828 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3829 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3830 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3834 // Track whether this decl-specifier declares anything.
3835 bool DeclaresAnything = true;
3837 // Handle anonymous struct definitions.
3838 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3839 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3840 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3841 if (getLangOpts().CPlusPlus ||
3842 Record->getDeclContext()->isRecord()) {
3843 // If CurContext is a DeclContext that can contain statements,
3844 // RecursiveASTVisitor won't visit the decls that
3845 // BuildAnonymousStructOrUnion() will put into CurContext.
3846 // Also store them here so that they can be part of the
3847 // DeclStmt that gets created in this case.
3848 // FIXME: Also return the IndirectFieldDecls created by
3849 // BuildAnonymousStructOr union, for the same reason?
3850 if (CurContext->isFunctionOrMethod())
3851 AnonRecord = Record;
3852 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3853 Context.getPrintingPolicy());
3856 DeclaresAnything = false;
3861 // A struct-declaration that does not declare an anonymous structure or
3862 // anonymous union shall contain a struct-declarator-list.
3864 // This rule also existed in C89 and C99; the grammar for struct-declaration
3865 // did not permit a struct-declaration without a struct-declarator-list.
3866 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3867 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3868 // Check for Microsoft C extension: anonymous struct/union member.
3869 // Handle 2 kinds of anonymous struct/union:
3873 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3874 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
3875 if ((Tag && Tag->getDeclName()) ||
3876 DS.getTypeSpecType() == DeclSpec::TST_typename) {
3877 RecordDecl *Record = nullptr;
3879 Record = dyn_cast<RecordDecl>(Tag);
3880 else if (const RecordType *RT =
3881 DS.getRepAsType().get()->getAsStructureType())
3882 Record = RT->getDecl();
3883 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3884 Record = UT->getDecl();
3886 if (Record && getLangOpts().MicrosoftExt) {
3887 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3888 << Record->isUnion() << DS.getSourceRange();
3889 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3892 DeclaresAnything = false;
3896 // Skip all the checks below if we have a type error.
3897 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3898 (TagD && TagD->isInvalidDecl()))
3901 if (getLangOpts().CPlusPlus &&
3902 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3903 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3904 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3905 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3906 DeclaresAnything = false;
3908 if (!DS.isMissingDeclaratorOk()) {
3909 // Customize diagnostic for a typedef missing a name.
3910 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3911 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3912 << DS.getSourceRange();
3914 DeclaresAnything = false;
3917 if (DS.isModulePrivateSpecified() &&
3918 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3919 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3920 << Tag->getTagKind()
3921 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3923 ActOnDocumentableDecl(TagD);
3926 // A declaration [...] shall declare at least a declarator [...], a tag,
3927 // or the members of an enumeration.
3929 // [If there are no declarators], and except for the declaration of an
3930 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3931 // names into the program, or shall redeclare a name introduced by a
3932 // previous declaration.
3933 if (!DeclaresAnything) {
3934 // In C, we allow this as a (popular) extension / bug. Don't bother
3935 // producing further diagnostics for redundant qualifiers after this.
3936 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3941 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3942 // init-declarator-list of the declaration shall not be empty.
3943 // C++ [dcl.fct.spec]p1:
3944 // If a cv-qualifier appears in a decl-specifier-seq, the
3945 // init-declarator-list of the declaration shall not be empty.
3947 // Spurious qualifiers here appear to be valid in C.
3948 unsigned DiagID = diag::warn_standalone_specifier;
3949 if (getLangOpts().CPlusPlus)
3950 DiagID = diag::ext_standalone_specifier;
3952 // Note that a linkage-specification sets a storage class, but
3953 // 'extern "C" struct foo;' is actually valid and not theoretically
3955 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3956 if (SCS == DeclSpec::SCS_mutable)
3957 // Since mutable is not a viable storage class specifier in C, there is
3958 // no reason to treat it as an extension. Instead, diagnose as an error.
3959 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3960 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3961 Diag(DS.getStorageClassSpecLoc(), DiagID)
3962 << DeclSpec::getSpecifierName(SCS);
3965 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3966 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3967 << DeclSpec::getSpecifierName(TSCS);
3968 if (DS.getTypeQualifiers()) {
3969 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3970 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3971 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3972 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3973 // Restrict is covered above.
3974 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3975 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3978 // Warn about ignored type attributes, for example:
3979 // __attribute__((aligned)) struct A;
3980 // Attributes should be placed after tag to apply to type declaration.
3981 if (!DS.getAttributes().empty()) {
3982 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3983 if (TypeSpecType == DeclSpec::TST_class ||
3984 TypeSpecType == DeclSpec::TST_struct ||
3985 TypeSpecType == DeclSpec::TST_interface ||
3986 TypeSpecType == DeclSpec::TST_union ||
3987 TypeSpecType == DeclSpec::TST_enum) {
3988 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3989 attrs = attrs->getNext())
3990 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3991 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3998 /// We are trying to inject an anonymous member into the given scope;
3999 /// check if there's an existing declaration that can't be overloaded.
4001 /// \return true if this is a forbidden redeclaration
4002 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4005 DeclarationName Name,
4006 SourceLocation NameLoc,
4008 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4009 Sema::ForRedeclaration);
4010 if (!SemaRef.LookupName(R, S)) return false;
4012 // Pick a representative declaration.
4013 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4014 assert(PrevDecl && "Expected a non-null Decl");
4016 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4019 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4021 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4026 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4027 /// anonymous struct or union AnonRecord into the owning context Owner
4028 /// and scope S. This routine will be invoked just after we realize
4029 /// that an unnamed union or struct is actually an anonymous union or
4036 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4037 /// // f into the surrounding scope.x
4040 /// This routine is recursive, injecting the names of nested anonymous
4041 /// structs/unions into the owning context and scope as well.
4043 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4044 RecordDecl *AnonRecord, AccessSpecifier AS,
4045 SmallVectorImpl<NamedDecl *> &Chaining) {
4046 bool Invalid = false;
4048 // Look every FieldDecl and IndirectFieldDecl with a name.
4049 for (auto *D : AnonRecord->decls()) {
4050 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4051 cast<NamedDecl>(D)->getDeclName()) {
4052 ValueDecl *VD = cast<ValueDecl>(D);
4053 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4055 AnonRecord->isUnion())) {
4056 // C++ [class.union]p2:
4057 // The names of the members of an anonymous union shall be
4058 // distinct from the names of any other entity in the
4059 // scope in which the anonymous union is declared.
4062 // C++ [class.union]p2:
4063 // For the purpose of name lookup, after the anonymous union
4064 // definition, the members of the anonymous union are
4065 // considered to have been defined in the scope in which the
4066 // anonymous union is declared.
4067 unsigned OldChainingSize = Chaining.size();
4068 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4069 Chaining.append(IF->chain_begin(), IF->chain_end());
4071 Chaining.push_back(VD);
4073 assert(Chaining.size() >= 2);
4074 NamedDecl **NamedChain =
4075 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4076 for (unsigned i = 0; i < Chaining.size(); i++)
4077 NamedChain[i] = Chaining[i];
4079 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4080 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4081 VD->getType(), NamedChain, Chaining.size());
4083 for (const auto *Attr : VD->attrs())
4084 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4086 IndirectField->setAccess(AS);
4087 IndirectField->setImplicit();
4088 SemaRef.PushOnScopeChains(IndirectField, S);
4090 // That includes picking up the appropriate access specifier.
4091 if (AS != AS_none) IndirectField->setAccess(AS);
4093 Chaining.resize(OldChainingSize);
4101 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4102 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4103 /// illegal input values are mapped to SC_None.
4105 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4106 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4107 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4108 "Parser allowed 'typedef' as storage class VarDecl.");
4109 switch (StorageClassSpec) {
4110 case DeclSpec::SCS_unspecified: return SC_None;
4111 case DeclSpec::SCS_extern:
4112 if (DS.isExternInLinkageSpec())
4115 case DeclSpec::SCS_static: return SC_Static;
4116 case DeclSpec::SCS_auto: return SC_Auto;
4117 case DeclSpec::SCS_register: return SC_Register;
4118 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4119 // Illegal SCSs map to None: error reporting is up to the caller.
4120 case DeclSpec::SCS_mutable: // Fall through.
4121 case DeclSpec::SCS_typedef: return SC_None;
4123 llvm_unreachable("unknown storage class specifier");
4126 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4127 assert(Record->hasInClassInitializer());
4129 for (const auto *I : Record->decls()) {
4130 const auto *FD = dyn_cast<FieldDecl>(I);
4131 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4132 FD = IFD->getAnonField();
4133 if (FD && FD->hasInClassInitializer())
4134 return FD->getLocation();
4137 llvm_unreachable("couldn't find in-class initializer");
4140 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4141 SourceLocation DefaultInitLoc) {
4142 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4145 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4146 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4149 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4150 CXXRecordDecl *AnonUnion) {
4151 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4154 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4157 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4158 /// anonymous structure or union. Anonymous unions are a C++ feature
4159 /// (C++ [class.union]) and a C11 feature; anonymous structures
4160 /// are a C11 feature and GNU C++ extension.
4161 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4164 const PrintingPolicy &Policy) {
4165 DeclContext *Owner = Record->getDeclContext();
4167 // Diagnose whether this anonymous struct/union is an extension.
4168 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4169 Diag(Record->getLocation(), diag::ext_anonymous_union);
4170 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4171 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4172 else if (!Record->isUnion() && !getLangOpts().C11)
4173 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4175 // C and C++ require different kinds of checks for anonymous
4177 bool Invalid = false;
4178 if (getLangOpts().CPlusPlus) {
4179 const char *PrevSpec = nullptr;
4181 if (Record->isUnion()) {
4182 // C++ [class.union]p6:
4183 // Anonymous unions declared in a named namespace or in the
4184 // global namespace shall be declared static.
4185 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4186 (isa<TranslationUnitDecl>(Owner) ||
4187 (isa<NamespaceDecl>(Owner) &&
4188 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4189 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4190 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4192 // Recover by adding 'static'.
4193 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4194 PrevSpec, DiagID, Policy);
4196 // C++ [class.union]p6:
4197 // A storage class is not allowed in a declaration of an
4198 // anonymous union in a class scope.
4199 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4200 isa<RecordDecl>(Owner)) {
4201 Diag(DS.getStorageClassSpecLoc(),
4202 diag::err_anonymous_union_with_storage_spec)
4203 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4205 // Recover by removing the storage specifier.
4206 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4208 PrevSpec, DiagID, Context.getPrintingPolicy());
4212 // Ignore const/volatile/restrict qualifiers.
4213 if (DS.getTypeQualifiers()) {
4214 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4215 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4216 << Record->isUnion() << "const"
4217 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4218 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4219 Diag(DS.getVolatileSpecLoc(),
4220 diag::ext_anonymous_struct_union_qualified)
4221 << Record->isUnion() << "volatile"
4222 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4223 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4224 Diag(DS.getRestrictSpecLoc(),
4225 diag::ext_anonymous_struct_union_qualified)
4226 << Record->isUnion() << "restrict"
4227 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4228 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4229 Diag(DS.getAtomicSpecLoc(),
4230 diag::ext_anonymous_struct_union_qualified)
4231 << Record->isUnion() << "_Atomic"
4232 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4234 DS.ClearTypeQualifiers();
4237 // C++ [class.union]p2:
4238 // The member-specification of an anonymous union shall only
4239 // define non-static data members. [Note: nested types and
4240 // functions cannot be declared within an anonymous union. ]
4241 for (auto *Mem : Record->decls()) {
4242 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4243 // C++ [class.union]p3:
4244 // An anonymous union shall not have private or protected
4245 // members (clause 11).
4246 assert(FD->getAccess() != AS_none);
4247 if (FD->getAccess() != AS_public) {
4248 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4249 << Record->isUnion() << (FD->getAccess() == AS_protected);
4253 // C++ [class.union]p1
4254 // An object of a class with a non-trivial constructor, a non-trivial
4255 // copy constructor, a non-trivial destructor, or a non-trivial copy
4256 // assignment operator cannot be a member of a union, nor can an
4257 // array of such objects.
4258 if (CheckNontrivialField(FD))
4260 } else if (Mem->isImplicit()) {
4261 // Any implicit members are fine.
4262 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4263 // This is a type that showed up in an
4264 // elaborated-type-specifier inside the anonymous struct or
4265 // union, but which actually declares a type outside of the
4266 // anonymous struct or union. It's okay.
4267 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4268 if (!MemRecord->isAnonymousStructOrUnion() &&
4269 MemRecord->getDeclName()) {
4270 // Visual C++ allows type definition in anonymous struct or union.
4271 if (getLangOpts().MicrosoftExt)
4272 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4273 << Record->isUnion();
4275 // This is a nested type declaration.
4276 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4277 << Record->isUnion();
4281 // This is an anonymous type definition within another anonymous type.
4282 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4283 // not part of standard C++.
4284 Diag(MemRecord->getLocation(),
4285 diag::ext_anonymous_record_with_anonymous_type)
4286 << Record->isUnion();
4288 } else if (isa<AccessSpecDecl>(Mem)) {
4289 // Any access specifier is fine.
4290 } else if (isa<StaticAssertDecl>(Mem)) {
4291 // In C++1z, static_assert declarations are also fine.
4293 // We have something that isn't a non-static data
4294 // member. Complain about it.
4295 unsigned DK = diag::err_anonymous_record_bad_member;
4296 if (isa<TypeDecl>(Mem))
4297 DK = diag::err_anonymous_record_with_type;
4298 else if (isa<FunctionDecl>(Mem))
4299 DK = diag::err_anonymous_record_with_function;
4300 else if (isa<VarDecl>(Mem))
4301 DK = diag::err_anonymous_record_with_static;
4303 // Visual C++ allows type definition in anonymous struct or union.
4304 if (getLangOpts().MicrosoftExt &&
4305 DK == diag::err_anonymous_record_with_type)
4306 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4307 << Record->isUnion();
4309 Diag(Mem->getLocation(), DK) << Record->isUnion();
4315 // C++11 [class.union]p8 (DR1460):
4316 // At most one variant member of a union may have a
4317 // brace-or-equal-initializer.
4318 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4320 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4321 cast<CXXRecordDecl>(Record));
4324 if (!Record->isUnion() && !Owner->isRecord()) {
4325 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4326 << getLangOpts().CPlusPlus;
4330 // Mock up a declarator.
4331 Declarator Dc(DS, Declarator::MemberContext);
4332 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4333 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4335 // Create a declaration for this anonymous struct/union.
4336 NamedDecl *Anon = nullptr;
4337 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4338 Anon = FieldDecl::Create(Context, OwningClass,
4340 Record->getLocation(),
4341 /*IdentifierInfo=*/nullptr,
4342 Context.getTypeDeclType(Record),
4344 /*BitWidth=*/nullptr, /*Mutable=*/false,
4345 /*InitStyle=*/ICIS_NoInit);
4346 Anon->setAccess(AS);
4347 if (getLangOpts().CPlusPlus)
4348 FieldCollector->Add(cast<FieldDecl>(Anon));
4350 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4351 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4352 if (SCSpec == DeclSpec::SCS_mutable) {
4353 // mutable can only appear on non-static class members, so it's always
4355 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4360 Anon = VarDecl::Create(Context, Owner,
4362 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4363 Context.getTypeDeclType(Record),
4366 // Default-initialize the implicit variable. This initialization will be
4367 // trivial in almost all cases, except if a union member has an in-class
4369 // union { int n = 0; };
4370 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4372 Anon->setImplicit();
4374 // Mark this as an anonymous struct/union type.
4375 Record->setAnonymousStructOrUnion(true);
4377 // Add the anonymous struct/union object to the current
4378 // context. We'll be referencing this object when we refer to one of
4380 Owner->addDecl(Anon);
4382 // Inject the members of the anonymous struct/union into the owning
4383 // context and into the identifier resolver chain for name lookup
4385 SmallVector<NamedDecl*, 2> Chain;
4386 Chain.push_back(Anon);
4388 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4391 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4392 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4393 Decl *ManglingContextDecl;
4394 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4395 NewVD->getDeclContext(), ManglingContextDecl)) {
4396 Context.setManglingNumber(
4397 NewVD, MCtx->getManglingNumber(
4398 NewVD, getMSManglingNumber(getLangOpts(), S)));
4399 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4405 Anon->setInvalidDecl();
4410 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4411 /// Microsoft C anonymous structure.
4412 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4415 /// struct A { int a; };
4416 /// struct B { struct A; int b; };
4423 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4424 RecordDecl *Record) {
4425 assert(Record && "expected a record!");
4427 // Mock up a declarator.
4428 Declarator Dc(DS, Declarator::TypeNameContext);
4429 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4430 assert(TInfo && "couldn't build declarator info for anonymous struct");
4432 auto *ParentDecl = cast<RecordDecl>(CurContext);
4433 QualType RecTy = Context.getTypeDeclType(Record);
4435 // Create a declaration for this anonymous struct.
4436 NamedDecl *Anon = FieldDecl::Create(Context,
4440 /*IdentifierInfo=*/nullptr,
4443 /*BitWidth=*/nullptr, /*Mutable=*/false,
4444 /*InitStyle=*/ICIS_NoInit);
4445 Anon->setImplicit();
4447 // Add the anonymous struct object to the current context.
4448 CurContext->addDecl(Anon);
4450 // Inject the members of the anonymous struct into the current
4451 // context and into the identifier resolver chain for name lookup
4453 SmallVector<NamedDecl*, 2> Chain;
4454 Chain.push_back(Anon);
4456 RecordDecl *RecordDef = Record->getDefinition();
4457 if (RequireCompleteType(Anon->getLocation(), RecTy,
4458 diag::err_field_incomplete) ||
4459 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4461 Anon->setInvalidDecl();
4462 ParentDecl->setInvalidDecl();
4468 /// GetNameForDeclarator - Determine the full declaration name for the
4469 /// given Declarator.
4470 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4471 return GetNameFromUnqualifiedId(D.getName());
4474 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4476 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4477 DeclarationNameInfo NameInfo;
4478 NameInfo.setLoc(Name.StartLocation);
4480 switch (Name.getKind()) {
4482 case UnqualifiedId::IK_ImplicitSelfParam:
4483 case UnqualifiedId::IK_Identifier:
4484 NameInfo.setName(Name.Identifier);
4485 NameInfo.setLoc(Name.StartLocation);
4488 case UnqualifiedId::IK_OperatorFunctionId:
4489 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4490 Name.OperatorFunctionId.Operator));
4491 NameInfo.setLoc(Name.StartLocation);
4492 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4493 = Name.OperatorFunctionId.SymbolLocations[0];
4494 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4495 = Name.EndLocation.getRawEncoding();
4498 case UnqualifiedId::IK_LiteralOperatorId:
4499 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4501 NameInfo.setLoc(Name.StartLocation);
4502 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4505 case UnqualifiedId::IK_ConversionFunctionId: {
4506 TypeSourceInfo *TInfo;
4507 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4509 return DeclarationNameInfo();
4510 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4511 Context.getCanonicalType(Ty)));
4512 NameInfo.setLoc(Name.StartLocation);
4513 NameInfo.setNamedTypeInfo(TInfo);
4517 case UnqualifiedId::IK_ConstructorName: {
4518 TypeSourceInfo *TInfo;
4519 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4521 return DeclarationNameInfo();
4522 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4523 Context.getCanonicalType(Ty)));
4524 NameInfo.setLoc(Name.StartLocation);
4525 NameInfo.setNamedTypeInfo(TInfo);
4529 case UnqualifiedId::IK_ConstructorTemplateId: {
4530 // In well-formed code, we can only have a constructor
4531 // template-id that refers to the current context, so go there
4532 // to find the actual type being constructed.
4533 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4534 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4535 return DeclarationNameInfo();
4537 // Determine the type of the class being constructed.
4538 QualType CurClassType = Context.getTypeDeclType(CurClass);
4540 // FIXME: Check two things: that the template-id names the same type as
4541 // CurClassType, and that the template-id does not occur when the name
4544 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4545 Context.getCanonicalType(CurClassType)));
4546 NameInfo.setLoc(Name.StartLocation);
4547 // FIXME: should we retrieve TypeSourceInfo?
4548 NameInfo.setNamedTypeInfo(nullptr);
4552 case UnqualifiedId::IK_DestructorName: {
4553 TypeSourceInfo *TInfo;
4554 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4556 return DeclarationNameInfo();
4557 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4558 Context.getCanonicalType(Ty)));
4559 NameInfo.setLoc(Name.StartLocation);
4560 NameInfo.setNamedTypeInfo(TInfo);
4564 case UnqualifiedId::IK_TemplateId: {
4565 TemplateName TName = Name.TemplateId->Template.get();
4566 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4567 return Context.getNameForTemplate(TName, TNameLoc);
4570 } // switch (Name.getKind())
4572 llvm_unreachable("Unknown name kind");
4575 static QualType getCoreType(QualType Ty) {
4577 if (Ty->isPointerType() || Ty->isReferenceType())
4578 Ty = Ty->getPointeeType();
4579 else if (Ty->isArrayType())
4580 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4582 return Ty.withoutLocalFastQualifiers();
4586 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4587 /// and Definition have "nearly" matching parameters. This heuristic is
4588 /// used to improve diagnostics in the case where an out-of-line function
4589 /// definition doesn't match any declaration within the class or namespace.
4590 /// Also sets Params to the list of indices to the parameters that differ
4591 /// between the declaration and the definition. If hasSimilarParameters
4592 /// returns true and Params is empty, then all of the parameters match.
4593 static bool hasSimilarParameters(ASTContext &Context,
4594 FunctionDecl *Declaration,
4595 FunctionDecl *Definition,
4596 SmallVectorImpl<unsigned> &Params) {
4598 if (Declaration->param_size() != Definition->param_size())
4600 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4601 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4602 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4604 // The parameter types are identical
4605 if (Context.hasSameType(DefParamTy, DeclParamTy))
4608 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4609 QualType DefParamBaseTy = getCoreType(DefParamTy);
4610 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4611 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4613 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4614 (DeclTyName && DeclTyName == DefTyName))
4615 Params.push_back(Idx);
4616 else // The two parameters aren't even close
4623 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4624 /// declarator needs to be rebuilt in the current instantiation.
4625 /// Any bits of declarator which appear before the name are valid for
4626 /// consideration here. That's specifically the type in the decl spec
4627 /// and the base type in any member-pointer chunks.
4628 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4629 DeclarationName Name) {
4630 // The types we specifically need to rebuild are:
4631 // - typenames, typeofs, and decltypes
4632 // - types which will become injected class names
4633 // Of course, we also need to rebuild any type referencing such a
4634 // type. It's safest to just say "dependent", but we call out a
4637 DeclSpec &DS = D.getMutableDeclSpec();
4638 switch (DS.getTypeSpecType()) {
4639 case DeclSpec::TST_typename:
4640 case DeclSpec::TST_typeofType:
4641 case DeclSpec::TST_underlyingType:
4642 case DeclSpec::TST_atomic: {
4643 // Grab the type from the parser.
4644 TypeSourceInfo *TSI = nullptr;
4645 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4646 if (T.isNull() || !T->isDependentType()) break;
4648 // Make sure there's a type source info. This isn't really much
4649 // of a waste; most dependent types should have type source info
4650 // attached already.
4652 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4654 // Rebuild the type in the current instantiation.
4655 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4656 if (!TSI) return true;
4658 // Store the new type back in the decl spec.
4659 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4660 DS.UpdateTypeRep(LocType);
4664 case DeclSpec::TST_decltype:
4665 case DeclSpec::TST_typeofExpr: {
4666 Expr *E = DS.getRepAsExpr();
4667 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4668 if (Result.isInvalid()) return true;
4669 DS.UpdateExprRep(Result.get());
4674 // Nothing to do for these decl specs.
4678 // It doesn't matter what order we do this in.
4679 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4680 DeclaratorChunk &Chunk = D.getTypeObject(I);
4682 // The only type information in the declarator which can come
4683 // before the declaration name is the base type of a member
4685 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4688 // Rebuild the scope specifier in-place.
4689 CXXScopeSpec &SS = Chunk.Mem.Scope();
4690 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4697 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4698 D.setFunctionDefinitionKind(FDK_Declaration);
4699 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4701 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4702 Dcl && Dcl->getDeclContext()->isFileContext())
4703 Dcl->setTopLevelDeclInObjCContainer();
4708 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4709 /// If T is the name of a class, then each of the following shall have a
4710 /// name different from T:
4711 /// - every static data member of class T;
4712 /// - every member function of class T
4713 /// - every member of class T that is itself a type;
4714 /// \returns true if the declaration name violates these rules.
4715 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4716 DeclarationNameInfo NameInfo) {
4717 DeclarationName Name = NameInfo.getName();
4719 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4720 while (Record && Record->isAnonymousStructOrUnion())
4721 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4722 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4723 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4730 /// \brief Diagnose a declaration whose declarator-id has the given
4731 /// nested-name-specifier.
4733 /// \param SS The nested-name-specifier of the declarator-id.
4735 /// \param DC The declaration context to which the nested-name-specifier
4738 /// \param Name The name of the entity being declared.
4740 /// \param Loc The location of the name of the entity being declared.
4742 /// \returns true if we cannot safely recover from this error, false otherwise.
4743 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4744 DeclarationName Name,
4745 SourceLocation Loc) {
4746 DeclContext *Cur = CurContext;
4747 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4748 Cur = Cur->getParent();
4750 // If the user provided a superfluous scope specifier that refers back to the
4751 // class in which the entity is already declared, diagnose and ignore it.
4757 // Note, it was once ill-formed to give redundant qualification in all
4758 // contexts, but that rule was removed by DR482.
4759 if (Cur->Equals(DC)) {
4760 if (Cur->isRecord()) {
4761 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4762 : diag::err_member_extra_qualification)
4763 << Name << FixItHint::CreateRemoval(SS.getRange());
4766 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4771 // Check whether the qualifying scope encloses the scope of the original
4773 if (!Cur->Encloses(DC)) {
4774 if (Cur->isRecord())
4775 Diag(Loc, diag::err_member_qualification)
4776 << Name << SS.getRange();
4777 else if (isa<TranslationUnitDecl>(DC))
4778 Diag(Loc, diag::err_invalid_declarator_global_scope)
4779 << Name << SS.getRange();
4780 else if (isa<FunctionDecl>(Cur))
4781 Diag(Loc, diag::err_invalid_declarator_in_function)
4782 << Name << SS.getRange();
4783 else if (isa<BlockDecl>(Cur))
4784 Diag(Loc, diag::err_invalid_declarator_in_block)
4785 << Name << SS.getRange();
4787 Diag(Loc, diag::err_invalid_declarator_scope)
4788 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4793 if (Cur->isRecord()) {
4794 // Cannot qualify members within a class.
4795 Diag(Loc, diag::err_member_qualification)
4796 << Name << SS.getRange();
4799 // C++ constructors and destructors with incorrect scopes can break
4800 // our AST invariants by having the wrong underlying types. If
4801 // that's the case, then drop this declaration entirely.
4802 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4803 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4804 !Context.hasSameType(Name.getCXXNameType(),
4805 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4811 // C++11 [dcl.meaning]p1:
4812 // [...] "The nested-name-specifier of the qualified declarator-id shall
4813 // not begin with a decltype-specifer"
4814 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4815 while (SpecLoc.getPrefix())
4816 SpecLoc = SpecLoc.getPrefix();
4817 if (dyn_cast_or_null<DecltypeType>(
4818 SpecLoc.getNestedNameSpecifier()->getAsType()))
4819 Diag(Loc, diag::err_decltype_in_declarator)
4820 << SpecLoc.getTypeLoc().getSourceRange();
4825 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4826 MultiTemplateParamsArg TemplateParamLists) {
4827 // TODO: consider using NameInfo for diagnostic.
4828 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4829 DeclarationName Name = NameInfo.getName();
4831 // All of these full declarators require an identifier. If it doesn't have
4832 // one, the ParsedFreeStandingDeclSpec action should be used.
4834 if (!D.isInvalidType()) // Reject this if we think it is valid.
4835 Diag(D.getDeclSpec().getLocStart(),
4836 diag::err_declarator_need_ident)
4837 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4839 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4842 // The scope passed in may not be a decl scope. Zip up the scope tree until
4843 // we find one that is.
4844 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4845 (S->getFlags() & Scope::TemplateParamScope) != 0)
4848 DeclContext *DC = CurContext;
4849 if (D.getCXXScopeSpec().isInvalid())
4851 else if (D.getCXXScopeSpec().isSet()) {
4852 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4853 UPPC_DeclarationQualifier))
4856 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4857 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4858 if (!DC || isa<EnumDecl>(DC)) {
4859 // If we could not compute the declaration context, it's because the
4860 // declaration context is dependent but does not refer to a class,
4861 // class template, or class template partial specialization. Complain
4862 // and return early, to avoid the coming semantic disaster.
4863 Diag(D.getIdentifierLoc(),
4864 diag::err_template_qualified_declarator_no_match)
4865 << D.getCXXScopeSpec().getScopeRep()
4866 << D.getCXXScopeSpec().getRange();
4869 bool IsDependentContext = DC->isDependentContext();
4871 if (!IsDependentContext &&
4872 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4875 // If a class is incomplete, do not parse entities inside it.
4876 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4877 Diag(D.getIdentifierLoc(),
4878 diag::err_member_def_undefined_record)
4879 << Name << DC << D.getCXXScopeSpec().getRange();
4882 if (!D.getDeclSpec().isFriendSpecified()) {
4883 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4884 Name, D.getIdentifierLoc())) {
4892 // Check whether we need to rebuild the type of the given
4893 // declaration in the current instantiation.
4894 if (EnteringContext && IsDependentContext &&
4895 TemplateParamLists.size() != 0) {
4896 ContextRAII SavedContext(*this, DC);
4897 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4902 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4903 QualType R = TInfo->getType();
4905 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4906 // If this is a typedef, we'll end up spewing multiple diagnostics.
4907 // Just return early; it's safer. If this is a function, let the
4908 // "constructor cannot have a return type" diagnostic handle it.
4909 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4912 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4913 UPPC_DeclarationType))
4916 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4919 // See if this is a redefinition of a variable in the same scope.
4920 if (!D.getCXXScopeSpec().isSet()) {
4921 bool IsLinkageLookup = false;
4922 bool CreateBuiltins = false;
4924 // If the declaration we're planning to build will be a function
4925 // or object with linkage, then look for another declaration with
4926 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4928 // If the declaration we're planning to build will be declared with
4929 // external linkage in the translation unit, create any builtin with
4931 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4933 else if (CurContext->isFunctionOrMethod() &&
4934 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4935 R->isFunctionType())) {
4936 IsLinkageLookup = true;
4938 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4939 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4940 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4941 CreateBuiltins = true;
4943 if (IsLinkageLookup)
4944 Previous.clear(LookupRedeclarationWithLinkage);
4946 LookupName(Previous, S, CreateBuiltins);
4947 } else { // Something like "int foo::x;"
4948 LookupQualifiedName(Previous, DC);
4950 // C++ [dcl.meaning]p1:
4951 // When the declarator-id is qualified, the declaration shall refer to a
4952 // previously declared member of the class or namespace to which the
4953 // qualifier refers (or, in the case of a namespace, of an element of the
4954 // inline namespace set of that namespace (7.3.1)) or to a specialization
4957 // Note that we already checked the context above, and that we do not have
4958 // enough information to make sure that Previous contains the declaration
4959 // we want to match. For example, given:
4966 // void X::f(int) { } // ill-formed
4968 // In this case, Previous will point to the overload set
4969 // containing the two f's declared in X, but neither of them
4972 // C++ [dcl.meaning]p1:
4973 // [...] the member shall not merely have been introduced by a
4974 // using-declaration in the scope of the class or namespace nominated by
4975 // the nested-name-specifier of the declarator-id.
4976 RemoveUsingDecls(Previous);
4979 if (Previous.isSingleResult() &&
4980 Previous.getFoundDecl()->isTemplateParameter()) {
4981 // Maybe we will complain about the shadowed template parameter.
4982 if (!D.isInvalidType())
4983 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4984 Previous.getFoundDecl());
4986 // Just pretend that we didn't see the previous declaration.
4990 // In C++, the previous declaration we find might be a tag type
4991 // (class or enum). In this case, the new declaration will hide the
4992 // tag type. Note that this does does not apply if we're declaring a
4993 // typedef (C++ [dcl.typedef]p4).
4994 if (Previous.isSingleTagDecl() &&
4995 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4998 // Check that there are no default arguments other than in the parameters
4999 // of a function declaration (C++ only).
5000 if (getLangOpts().CPlusPlus)
5001 CheckExtraCXXDefaultArguments(D);
5003 if (D.getDeclSpec().isConceptSpecified()) {
5004 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5005 // applied only to the definition of a function template or variable
5006 // template, declared in namespace scope
5007 if (!TemplateParamLists.size()) {
5008 Diag(D.getDeclSpec().getConceptSpecLoc(),
5009 diag:: err_concept_wrong_decl_kind);
5013 if (!DC->getRedeclContext()->isFileContext()) {
5014 Diag(D.getIdentifierLoc(),
5015 diag::err_concept_decls_may_only_appear_in_namespace_scope);
5022 bool AddToScope = true;
5023 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5024 if (TemplateParamLists.size()) {
5025 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5029 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5030 } else if (R->isFunctionType()) {
5031 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5035 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5042 // If this has an identifier and is not an invalid redeclaration or
5043 // function template specialization, add it to the scope stack.
5044 if (New->getDeclName() && AddToScope &&
5045 !(D.isRedeclaration() && New->isInvalidDecl())) {
5046 // Only make a locally-scoped extern declaration visible if it is the first
5047 // declaration of this entity. Qualified lookup for such an entity should
5048 // only find this declaration if there is no visible declaration of it.
5049 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5050 PushOnScopeChains(New, S, AddToContext);
5052 CurContext->addHiddenDecl(New);
5058 /// Helper method to turn variable array types into constant array
5059 /// types in certain situations which would otherwise be errors (for
5060 /// GCC compatibility).
5061 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5062 ASTContext &Context,
5063 bool &SizeIsNegative,
5064 llvm::APSInt &Oversized) {
5065 // This method tries to turn a variable array into a constant
5066 // array even when the size isn't an ICE. This is necessary
5067 // for compatibility with code that depends on gcc's buggy
5068 // constant expression folding, like struct {char x[(int)(char*)2];}
5069 SizeIsNegative = false;
5072 if (T->isDependentType())
5075 QualifierCollector Qs;
5076 const Type *Ty = Qs.strip(T);
5078 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5079 QualType Pointee = PTy->getPointeeType();
5080 QualType FixedType =
5081 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5083 if (FixedType.isNull()) return FixedType;
5084 FixedType = Context.getPointerType(FixedType);
5085 return Qs.apply(Context, FixedType);
5087 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5088 QualType Inner = PTy->getInnerType();
5089 QualType FixedType =
5090 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5092 if (FixedType.isNull()) return FixedType;
5093 FixedType = Context.getParenType(FixedType);
5094 return Qs.apply(Context, FixedType);
5097 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5100 // FIXME: We should probably handle this case
5101 if (VLATy->getElementType()->isVariablyModifiedType())
5105 if (!VLATy->getSizeExpr() ||
5106 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5109 // Check whether the array size is negative.
5110 if (Res.isSigned() && Res.isNegative()) {
5111 SizeIsNegative = true;
5115 // Check whether the array is too large to be addressed.
5116 unsigned ActiveSizeBits
5117 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5119 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5124 return Context.getConstantArrayType(VLATy->getElementType(),
5125 Res, ArrayType::Normal, 0);
5129 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5130 SrcTL = SrcTL.getUnqualifiedLoc();
5131 DstTL = DstTL.getUnqualifiedLoc();
5132 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5133 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5134 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5135 DstPTL.getPointeeLoc());
5136 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5139 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5140 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5141 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5142 DstPTL.getInnerLoc());
5143 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5144 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5147 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5148 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5149 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5150 TypeLoc DstElemTL = DstATL.getElementLoc();
5151 DstElemTL.initializeFullCopy(SrcElemTL);
5152 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5153 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5154 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5157 /// Helper method to turn variable array types into constant array
5158 /// types in certain situations which would otherwise be errors (for
5159 /// GCC compatibility).
5160 static TypeSourceInfo*
5161 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5162 ASTContext &Context,
5163 bool &SizeIsNegative,
5164 llvm::APSInt &Oversized) {
5166 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5167 SizeIsNegative, Oversized);
5168 if (FixedTy.isNull())
5170 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5171 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5172 FixedTInfo->getTypeLoc());
5176 /// \brief Register the given locally-scoped extern "C" declaration so
5177 /// that it can be found later for redeclarations. We include any extern "C"
5178 /// declaration that is not visible in the translation unit here, not just
5179 /// function-scope declarations.
5181 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5182 if (!getLangOpts().CPlusPlus &&
5183 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5184 // Don't need to track declarations in the TU in C.
5187 // Note that we have a locally-scoped external with this name.
5188 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5191 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5192 // FIXME: We can have multiple results via __attribute__((overloadable)).
5193 auto Result = Context.getExternCContextDecl()->lookup(Name);
5194 return Result.empty() ? nullptr : *Result.begin();
5197 /// \brief Diagnose function specifiers on a declaration of an identifier that
5198 /// does not identify a function.
5199 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5200 // FIXME: We should probably indicate the identifier in question to avoid
5201 // confusion for constructs like "inline int a(), b;"
5202 if (DS.isInlineSpecified())
5203 Diag(DS.getInlineSpecLoc(),
5204 diag::err_inline_non_function);
5206 if (DS.isVirtualSpecified())
5207 Diag(DS.getVirtualSpecLoc(),
5208 diag::err_virtual_non_function);
5210 if (DS.isExplicitSpecified())
5211 Diag(DS.getExplicitSpecLoc(),
5212 diag::err_explicit_non_function);
5214 if (DS.isNoreturnSpecified())
5215 Diag(DS.getNoreturnSpecLoc(),
5216 diag::err_noreturn_non_function);
5220 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5221 TypeSourceInfo *TInfo, LookupResult &Previous) {
5222 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5223 if (D.getCXXScopeSpec().isSet()) {
5224 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5225 << D.getCXXScopeSpec().getRange();
5227 // Pretend we didn't see the scope specifier.
5232 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5234 if (D.getDeclSpec().isConstexprSpecified())
5235 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5237 if (D.getDeclSpec().isConceptSpecified())
5238 Diag(D.getDeclSpec().getConceptSpecLoc(),
5239 diag::err_concept_wrong_decl_kind);
5241 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5242 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5243 << D.getName().getSourceRange();
5247 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5248 if (!NewTD) return nullptr;
5250 // Handle attributes prior to checking for duplicates in MergeVarDecl
5251 ProcessDeclAttributes(S, NewTD, D);
5253 CheckTypedefForVariablyModifiedType(S, NewTD);
5255 bool Redeclaration = D.isRedeclaration();
5256 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5257 D.setRedeclaration(Redeclaration);
5262 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5263 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5264 // then it shall have block scope.
5265 // Note that variably modified types must be fixed before merging the decl so
5266 // that redeclarations will match.
5267 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5268 QualType T = TInfo->getType();
5269 if (T->isVariablyModifiedType()) {
5270 getCurFunction()->setHasBranchProtectedScope();
5272 if (S->getFnParent() == nullptr) {
5273 bool SizeIsNegative;
5274 llvm::APSInt Oversized;
5275 TypeSourceInfo *FixedTInfo =
5276 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5280 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5281 NewTD->setTypeSourceInfo(FixedTInfo);
5284 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5285 else if (T->isVariableArrayType())
5286 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5287 else if (Oversized.getBoolValue())
5288 Diag(NewTD->getLocation(), diag::err_array_too_large)
5289 << Oversized.toString(10);
5291 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5292 NewTD->setInvalidDecl();
5298 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5299 /// declares a typedef-name, either using the 'typedef' type specifier or via
5300 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5302 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5303 LookupResult &Previous, bool &Redeclaration) {
5304 // Merge the decl with the existing one if appropriate. If the decl is
5305 // in an outer scope, it isn't the same thing.
5306 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5307 /*AllowInlineNamespace*/false);
5308 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5309 if (!Previous.empty()) {
5310 Redeclaration = true;
5311 MergeTypedefNameDecl(S, NewTD, Previous);
5314 // If this is the C FILE type, notify the AST context.
5315 if (IdentifierInfo *II = NewTD->getIdentifier())
5316 if (!NewTD->isInvalidDecl() &&
5317 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5318 if (II->isStr("FILE"))
5319 Context.setFILEDecl(NewTD);
5320 else if (II->isStr("jmp_buf"))
5321 Context.setjmp_bufDecl(NewTD);
5322 else if (II->isStr("sigjmp_buf"))
5323 Context.setsigjmp_bufDecl(NewTD);
5324 else if (II->isStr("ucontext_t"))
5325 Context.setucontext_tDecl(NewTD);
5331 /// \brief Determines whether the given declaration is an out-of-scope
5332 /// previous declaration.
5334 /// This routine should be invoked when name lookup has found a
5335 /// previous declaration (PrevDecl) that is not in the scope where a
5336 /// new declaration by the same name is being introduced. If the new
5337 /// declaration occurs in a local scope, previous declarations with
5338 /// linkage may still be considered previous declarations (C99
5339 /// 6.2.2p4-5, C++ [basic.link]p6).
5341 /// \param PrevDecl the previous declaration found by name
5344 /// \param DC the context in which the new declaration is being
5347 /// \returns true if PrevDecl is an out-of-scope previous declaration
5348 /// for a new delcaration with the same name.
5350 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5351 ASTContext &Context) {
5355 if (!PrevDecl->hasLinkage())
5358 if (Context.getLangOpts().CPlusPlus) {
5359 // C++ [basic.link]p6:
5360 // If there is a visible declaration of an entity with linkage
5361 // having the same name and type, ignoring entities declared
5362 // outside the innermost enclosing namespace scope, the block
5363 // scope declaration declares that same entity and receives the
5364 // linkage of the previous declaration.
5365 DeclContext *OuterContext = DC->getRedeclContext();
5366 if (!OuterContext->isFunctionOrMethod())
5367 // This rule only applies to block-scope declarations.
5370 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5371 if (PrevOuterContext->isRecord())
5372 // We found a member function: ignore it.
5375 // Find the innermost enclosing namespace for the new and
5376 // previous declarations.
5377 OuterContext = OuterContext->getEnclosingNamespaceContext();
5378 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5380 // The previous declaration is in a different namespace, so it
5381 // isn't the same function.
5382 if (!OuterContext->Equals(PrevOuterContext))
5389 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5390 CXXScopeSpec &SS = D.getCXXScopeSpec();
5391 if (!SS.isSet()) return;
5392 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5395 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5396 QualType type = decl->getType();
5397 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5398 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5399 // Various kinds of declaration aren't allowed to be __autoreleasing.
5400 unsigned kind = -1U;
5401 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5402 if (var->hasAttr<BlocksAttr>())
5403 kind = 0; // __block
5404 else if (!var->hasLocalStorage())
5406 } else if (isa<ObjCIvarDecl>(decl)) {
5408 } else if (isa<FieldDecl>(decl)) {
5413 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5416 } else if (lifetime == Qualifiers::OCL_None) {
5417 // Try to infer lifetime.
5418 if (!type->isObjCLifetimeType())
5421 lifetime = type->getObjCARCImplicitLifetime();
5422 type = Context.getLifetimeQualifiedType(type, lifetime);
5423 decl->setType(type);
5426 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5427 // Thread-local variables cannot have lifetime.
5428 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5429 var->getTLSKind()) {
5430 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5439 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5440 // Ensure that an auto decl is deduced otherwise the checks below might cache
5441 // the wrong linkage.
5442 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5444 // 'weak' only applies to declarations with external linkage.
5445 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5446 if (!ND.isExternallyVisible()) {
5447 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5448 ND.dropAttr<WeakAttr>();
5451 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5452 if (ND.isExternallyVisible()) {
5453 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5454 ND.dropAttr<WeakRefAttr>();
5455 ND.dropAttr<AliasAttr>();
5459 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5460 if (VD->hasInit()) {
5461 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5462 assert(VD->isThisDeclarationADefinition() &&
5463 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5464 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5465 VD->dropAttr<AliasAttr>();
5470 // 'selectany' only applies to externally visible variable declarations.
5471 // It does not apply to functions.
5472 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5473 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5474 S.Diag(Attr->getLocation(),
5475 diag::err_attribute_selectany_non_extern_data);
5476 ND.dropAttr<SelectAnyAttr>();
5480 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5481 // dll attributes require external linkage. Static locals may have external
5482 // linkage but still cannot be explicitly imported or exported.
5483 auto *VD = dyn_cast<VarDecl>(&ND);
5484 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5485 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5487 ND.setInvalidDecl();
5491 // Virtual functions cannot be marked as 'notail'.
5492 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5493 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5494 if (MD->isVirtual()) {
5495 S.Diag(ND.getLocation(),
5496 diag::err_invalid_attribute_on_virtual_function)
5498 ND.dropAttr<NotTailCalledAttr>();
5502 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5504 bool IsSpecialization) {
5505 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5506 OldDecl = OldTD->getTemplatedDecl();
5507 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5508 NewDecl = NewTD->getTemplatedDecl();
5510 if (!OldDecl || !NewDecl)
5513 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5514 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5515 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5516 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5518 // dllimport and dllexport are inheritable attributes so we have to exclude
5519 // inherited attribute instances.
5520 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5521 (NewExportAttr && !NewExportAttr->isInherited());
5523 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5524 // the only exception being explicit specializations.
5525 // Implicitly generated declarations are also excluded for now because there
5526 // is no other way to switch these to use dllimport or dllexport.
5527 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5529 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5530 // Allow with a warning for free functions and global variables.
5531 bool JustWarn = false;
5532 if (!OldDecl->isCXXClassMember()) {
5533 auto *VD = dyn_cast<VarDecl>(OldDecl);
5534 if (VD && !VD->getDescribedVarTemplate())
5536 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5537 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5541 // We cannot change a declaration that's been used because IR has already
5542 // been emitted. Dllimported functions will still work though (modulo
5543 // address equality) as they can use the thunk.
5544 if (OldDecl->isUsed())
5545 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5548 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5549 : diag::err_attribute_dll_redeclaration;
5550 S.Diag(NewDecl->getLocation(), DiagID)
5552 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5553 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5555 NewDecl->setInvalidDecl();
5560 // A redeclaration is not allowed to drop a dllimport attribute, the only
5561 // exceptions being inline function definitions, local extern declarations,
5562 // and qualified friend declarations.
5563 // NB: MSVC converts such a declaration to dllexport.
5564 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5565 if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5566 // Ignore static data because out-of-line definitions are diagnosed
5568 IsStaticDataMember = VD->isStaticDataMember();
5569 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5570 IsInline = FD->isInlined();
5571 IsQualifiedFriend = FD->getQualifier() &&
5572 FD->getFriendObjectKind() == Decl::FOK_Declared;
5575 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5576 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5577 S.Diag(NewDecl->getLocation(),
5578 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5579 << NewDecl << OldImportAttr;
5580 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5581 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5582 OldDecl->dropAttr<DLLImportAttr>();
5583 NewDecl->dropAttr<DLLImportAttr>();
5584 } else if (IsInline && OldImportAttr &&
5585 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5586 // In MinGW, seeing a function declared inline drops the dllimport attribute.
5587 OldDecl->dropAttr<DLLImportAttr>();
5588 NewDecl->dropAttr<DLLImportAttr>();
5589 S.Diag(NewDecl->getLocation(),
5590 diag::warn_dllimport_dropped_from_inline_function)
5591 << NewDecl << OldImportAttr;
5595 /// Given that we are within the definition of the given function,
5596 /// will that definition behave like C99's 'inline', where the
5597 /// definition is discarded except for optimization purposes?
5598 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5599 // Try to avoid calling GetGVALinkageForFunction.
5601 // All cases of this require the 'inline' keyword.
5602 if (!FD->isInlined()) return false;
5604 // This is only possible in C++ with the gnu_inline attribute.
5605 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5608 // Okay, go ahead and call the relatively-more-expensive function.
5611 // AST quite reasonably asserts that it's working on a function
5612 // definition. We don't really have a way to tell it that we're
5613 // currently defining the function, so just lie to it in +Asserts
5614 // builds. This is an awful hack.
5619 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5628 /// Determine whether a variable is extern "C" prior to attaching
5629 /// an initializer. We can't just call isExternC() here, because that
5630 /// will also compute and cache whether the declaration is externally
5631 /// visible, which might change when we attach the initializer.
5633 /// This can only be used if the declaration is known to not be a
5634 /// redeclaration of an internal linkage declaration.
5640 /// Attaching the initializer here makes this declaration not externally
5641 /// visible, because its type has internal linkage.
5643 /// FIXME: This is a hack.
5644 template<typename T>
5645 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5646 if (S.getLangOpts().CPlusPlus) {
5647 // In C++, the overloadable attribute negates the effects of extern "C".
5648 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5651 // So do CUDA's host/device attributes if overloading is enabled.
5652 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
5653 (D->template hasAttr<CUDADeviceAttr>() ||
5654 D->template hasAttr<CUDAHostAttr>()))
5657 return D->isExternC();
5660 static bool shouldConsiderLinkage(const VarDecl *VD) {
5661 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5662 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5663 return VD->hasExternalStorage();
5664 if (DC->isFileContext())
5668 llvm_unreachable("Unexpected context");
5671 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5672 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5673 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5674 isa<OMPDeclareReductionDecl>(DC))
5678 llvm_unreachable("Unexpected context");
5681 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5682 AttributeList::Kind Kind) {
5683 for (const AttributeList *L = AttrList; L; L = L->getNext())
5684 if (L->getKind() == Kind)
5689 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5690 AttributeList::Kind Kind) {
5691 // Check decl attributes on the DeclSpec.
5692 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5695 // Walk the declarator structure, checking decl attributes that were in a type
5696 // position to the decl itself.
5697 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5698 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5702 // Finally, check attributes on the decl itself.
5703 return hasParsedAttr(S, PD.getAttributes(), Kind);
5706 /// Adjust the \c DeclContext for a function or variable that might be a
5707 /// function-local external declaration.
5708 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5709 if (!DC->isFunctionOrMethod())
5712 // If this is a local extern function or variable declared within a function
5713 // template, don't add it into the enclosing namespace scope until it is
5714 // instantiated; it might have a dependent type right now.
5715 if (DC->isDependentContext())
5718 // C++11 [basic.link]p7:
5719 // When a block scope declaration of an entity with linkage is not found to
5720 // refer to some other declaration, then that entity is a member of the
5721 // innermost enclosing namespace.
5723 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5724 // semantically-enclosing namespace, not a lexically-enclosing one.
5725 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5726 DC = DC->getParent();
5730 /// \brief Returns true if given declaration has external C language linkage.
5731 static bool isDeclExternC(const Decl *D) {
5732 if (const auto *FD = dyn_cast<FunctionDecl>(D))
5733 return FD->isExternC();
5734 if (const auto *VD = dyn_cast<VarDecl>(D))
5735 return VD->isExternC();
5737 llvm_unreachable("Unknown type of decl!");
5741 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5742 TypeSourceInfo *TInfo, LookupResult &Previous,
5743 MultiTemplateParamsArg TemplateParamLists,
5745 QualType R = TInfo->getType();
5746 DeclarationName Name = GetNameForDeclarator(D).getName();
5748 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5749 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5751 if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5752 Diag(D.getIdentifierLoc(),
5753 diag::err_opencl_type_can_only_be_used_as_function_parameter)
5759 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5760 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5762 // dllimport globals without explicit storage class are treated as extern. We
5763 // have to change the storage class this early to get the right DeclContext.
5764 if (SC == SC_None && !DC->isRecord() &&
5765 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5766 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5769 DeclContext *OriginalDC = DC;
5770 bool IsLocalExternDecl = SC == SC_Extern &&
5771 adjustContextForLocalExternDecl(DC);
5773 if (getLangOpts().OpenCL) {
5774 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5776 while (NR->isPointerType()) {
5777 if (NR->isFunctionPointerType()) {
5778 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5782 NR = NR->getPointeeType();
5785 if (!getOpenCLOptions().cl_khr_fp16) {
5786 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5787 // half array type (unless the cl_khr_fp16 extension is enabled).
5788 if (Context.getBaseElementType(R)->isHalfType()) {
5789 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5795 if (SCSpec == DeclSpec::SCS_mutable) {
5796 // mutable can only appear on non-static class members, so it's always
5798 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5803 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5804 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5805 D.getDeclSpec().getStorageClassSpecLoc())) {
5806 // In C++11, the 'register' storage class specifier is deprecated.
5807 // Suppress the warning in system macros, it's used in macros in some
5808 // popular C system headers, such as in glibc's htonl() macro.
5809 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5810 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5811 : diag::warn_deprecated_register)
5812 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5815 IdentifierInfo *II = Name.getAsIdentifierInfo();
5817 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5822 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5824 if (!DC->isRecord() && S->getFnParent() == nullptr) {
5825 // C99 6.9p2: The storage-class specifiers auto and register shall not
5826 // appear in the declaration specifiers in an external declaration.
5827 // Global Register+Asm is a GNU extension we support.
5828 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5829 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5834 if (getLangOpts().OpenCL) {
5835 // OpenCL v1.2 s6.9.b p4:
5836 // The sampler type cannot be used with the __local and __global address
5837 // space qualifiers.
5838 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5839 R.getAddressSpace() == LangAS::opencl_global)) {
5840 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5843 // OpenCL 1.2 spec, p6.9 r:
5844 // The event type cannot be used to declare a program scope variable.
5845 // The event type cannot be used with the __local, __constant and __global
5846 // address space qualifiers.
5847 if (R->isEventT()) {
5848 if (S->getParent() == nullptr) {
5849 Diag(D.getLocStart(), diag::err_event_t_global_var);
5853 if (R.getAddressSpace()) {
5854 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5860 bool IsExplicitSpecialization = false;
5861 bool IsVariableTemplateSpecialization = false;
5862 bool IsPartialSpecialization = false;
5863 bool IsVariableTemplate = false;
5864 VarDecl *NewVD = nullptr;
5865 VarTemplateDecl *NewTemplate = nullptr;
5866 TemplateParameterList *TemplateParams = nullptr;
5867 if (!getLangOpts().CPlusPlus) {
5868 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5869 D.getIdentifierLoc(), II,
5872 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5873 ParsingInitForAutoVars.insert(NewVD);
5875 if (D.isInvalidType())
5876 NewVD->setInvalidDecl();
5878 bool Invalid = false;
5880 if (DC->isRecord() && !CurContext->isRecord()) {
5881 // This is an out-of-line definition of a static data member.
5886 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5887 diag::err_static_out_of_line)
5888 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5893 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5894 // to names of variables declared in a block or to function parameters.
5895 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5898 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5899 diag::err_storage_class_for_static_member)
5900 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5902 case SC_PrivateExtern:
5903 llvm_unreachable("C storage class in c++!");
5907 if (SC == SC_Static && CurContext->isRecord()) {
5908 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5909 if (RD->isLocalClass())
5910 Diag(D.getIdentifierLoc(),
5911 diag::err_static_data_member_not_allowed_in_local_class)
5912 << Name << RD->getDeclName();
5914 // C++98 [class.union]p1: If a union contains a static data member,
5915 // the program is ill-formed. C++11 drops this restriction.
5917 Diag(D.getIdentifierLoc(),
5918 getLangOpts().CPlusPlus11
5919 ? diag::warn_cxx98_compat_static_data_member_in_union
5920 : diag::ext_static_data_member_in_union) << Name;
5921 // We conservatively disallow static data members in anonymous structs.
5922 else if (!RD->getDeclName())
5923 Diag(D.getIdentifierLoc(),
5924 diag::err_static_data_member_not_allowed_in_anon_struct)
5925 << Name << RD->isUnion();
5929 // Match up the template parameter lists with the scope specifier, then
5930 // determine whether we have a template or a template specialization.
5931 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5932 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5933 D.getCXXScopeSpec(),
5934 D.getName().getKind() == UnqualifiedId::IK_TemplateId
5935 ? D.getName().TemplateId
5938 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5940 if (TemplateParams) {
5941 if (!TemplateParams->size() &&
5942 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5943 // There is an extraneous 'template<>' for this variable. Complain
5944 // about it, but allow the declaration of the variable.
5945 Diag(TemplateParams->getTemplateLoc(),
5946 diag::err_template_variable_noparams)
5948 << SourceRange(TemplateParams->getTemplateLoc(),
5949 TemplateParams->getRAngleLoc());
5950 TemplateParams = nullptr;
5952 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5953 // This is an explicit specialization or a partial specialization.
5954 // FIXME: Check that we can declare a specialization here.
5955 IsVariableTemplateSpecialization = true;
5956 IsPartialSpecialization = TemplateParams->size() > 0;
5957 } else { // if (TemplateParams->size() > 0)
5958 // This is a template declaration.
5959 IsVariableTemplate = true;
5961 // Check that we can declare a template here.
5962 if (CheckTemplateDeclScope(S, TemplateParams))
5965 // Only C++1y supports variable templates (N3651).
5966 Diag(D.getIdentifierLoc(),
5967 getLangOpts().CPlusPlus14
5968 ? diag::warn_cxx11_compat_variable_template
5969 : diag::ext_variable_template);
5974 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5975 "should have a 'template<>' for this decl");
5978 if (IsVariableTemplateSpecialization) {
5979 SourceLocation TemplateKWLoc =
5980 TemplateParamLists.size() > 0
5981 ? TemplateParamLists[0]->getTemplateLoc()
5983 DeclResult Res = ActOnVarTemplateSpecialization(
5984 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5985 IsPartialSpecialization);
5986 if (Res.isInvalid())
5988 NewVD = cast<VarDecl>(Res.get());
5991 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5992 D.getIdentifierLoc(), II, R, TInfo, SC);
5994 // If this is supposed to be a variable template, create it as such.
5995 if (IsVariableTemplate) {
5997 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5998 TemplateParams, NewVD);
5999 NewVD->setDescribedVarTemplate(NewTemplate);
6002 // If this decl has an auto type in need of deduction, make a note of the
6003 // Decl so we can diagnose uses of it in its own initializer.
6004 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6005 ParsingInitForAutoVars.insert(NewVD);
6007 if (D.isInvalidType() || Invalid) {
6008 NewVD->setInvalidDecl();
6010 NewTemplate->setInvalidDecl();
6013 SetNestedNameSpecifier(NewVD, D);
6015 // If we have any template parameter lists that don't directly belong to
6016 // the variable (matching the scope specifier), store them.
6017 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6018 if (TemplateParamLists.size() > VDTemplateParamLists)
6019 NewVD->setTemplateParameterListsInfo(
6020 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6022 if (D.getDeclSpec().isConstexprSpecified())
6023 NewVD->setConstexpr(true);
6025 if (D.getDeclSpec().isConceptSpecified()) {
6026 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6029 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6030 // be declared with the thread_local, inline, friend, or constexpr
6031 // specifiers, [...]
6032 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6033 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6034 diag::err_concept_decl_invalid_specifiers)
6036 NewVD->setInvalidDecl(true);
6039 if (D.getDeclSpec().isConstexprSpecified()) {
6040 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6041 diag::err_concept_decl_invalid_specifiers)
6043 NewVD->setInvalidDecl(true);
6046 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6047 // applied only to the definition of a function template or variable
6048 // template, declared in namespace scope.
6049 if (IsVariableTemplateSpecialization) {
6050 Diag(D.getDeclSpec().getConceptSpecLoc(),
6051 diag::err_concept_specified_specialization)
6052 << (IsPartialSpecialization ? 2 : 1);
6055 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6056 // following restrictions:
6057 // - The declared type shall have the type bool.
6058 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6059 !NewVD->isInvalidDecl()) {
6060 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6061 NewVD->setInvalidDecl(true);
6066 // Set the lexical context. If the declarator has a C++ scope specifier, the
6067 // lexical context will be different from the semantic context.
6068 NewVD->setLexicalDeclContext(CurContext);
6070 NewTemplate->setLexicalDeclContext(CurContext);
6072 if (IsLocalExternDecl)
6073 NewVD->setLocalExternDecl();
6075 bool EmitTLSUnsupportedError = false;
6076 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6077 // C++11 [dcl.stc]p4:
6078 // When thread_local is applied to a variable of block scope the
6079 // storage-class-specifier static is implied if it does not appear
6081 // Core issue: 'static' is not implied if the variable is declared
6083 if (NewVD->hasLocalStorage() &&
6084 (SCSpec != DeclSpec::SCS_unspecified ||
6085 TSCS != DeclSpec::TSCS_thread_local ||
6086 !DC->isFunctionOrMethod()))
6087 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6088 diag::err_thread_non_global)
6089 << DeclSpec::getSpecifierName(TSCS);
6090 else if (!Context.getTargetInfo().isTLSSupported()) {
6091 if (getLangOpts().CUDA) {
6092 // Postpone error emission until we've collected attributes required to
6093 // figure out whether it's a host or device variable and whether the
6094 // error should be ignored.
6095 EmitTLSUnsupportedError = true;
6096 // We still need to mark the variable as TLS so it shows up in AST with
6097 // proper storage class for other tools to use even if we're not going
6098 // to emit any code for it.
6099 NewVD->setTSCSpec(TSCS);
6101 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6102 diag::err_thread_unsupported);
6104 NewVD->setTSCSpec(TSCS);
6108 // An inline definition of a function with external linkage shall
6109 // not contain a definition of a modifiable object with static or
6110 // thread storage duration...
6111 // We only apply this when the function is required to be defined
6112 // elsewhere, i.e. when the function is not 'extern inline'. Note
6113 // that a local variable with thread storage duration still has to
6114 // be marked 'static'. Also note that it's possible to get these
6115 // semantics in C++ using __attribute__((gnu_inline)).
6116 if (SC == SC_Static && S->getFnParent() != nullptr &&
6117 !NewVD->getType().isConstQualified()) {
6118 FunctionDecl *CurFD = getCurFunctionDecl();
6119 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6120 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6121 diag::warn_static_local_in_extern_inline);
6122 MaybeSuggestAddingStaticToDecl(CurFD);
6126 if (D.getDeclSpec().isModulePrivateSpecified()) {
6127 if (IsVariableTemplateSpecialization)
6128 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6129 << (IsPartialSpecialization ? 1 : 0)
6130 << FixItHint::CreateRemoval(
6131 D.getDeclSpec().getModulePrivateSpecLoc());
6132 else if (IsExplicitSpecialization)
6133 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6135 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6136 else if (NewVD->hasLocalStorage())
6137 Diag(NewVD->getLocation(), diag::err_module_private_local)
6138 << 0 << NewVD->getDeclName()
6139 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6140 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6142 NewVD->setModulePrivate();
6144 NewTemplate->setModulePrivate();
6148 // Handle attributes prior to checking for duplicates in MergeVarDecl
6149 ProcessDeclAttributes(S, NewVD, D);
6151 if (getLangOpts().CUDA) {
6152 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6153 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6154 diag::err_thread_unsupported);
6155 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6156 // storage [duration]."
6157 if (SC == SC_None && S->getFnParent() != nullptr &&
6158 (NewVD->hasAttr<CUDASharedAttr>() ||
6159 NewVD->hasAttr<CUDAConstantAttr>())) {
6160 NewVD->setStorageClass(SC_Static);
6164 // Ensure that dllimport globals without explicit storage class are treated as
6165 // extern. The storage class is set above using parsed attributes. Now we can
6166 // check the VarDecl itself.
6167 assert(!NewVD->hasAttr<DLLImportAttr>() ||
6168 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6169 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6171 // In auto-retain/release, infer strong retension for variables of
6173 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6174 NewVD->setInvalidDecl();
6176 // Handle GNU asm-label extension (encoded as an attribute).
6177 if (Expr *E = (Expr*)D.getAsmLabel()) {
6178 // The parser guarantees this is a string.
6179 StringLiteral *SE = cast<StringLiteral>(E);
6180 StringRef Label = SE->getString();
6181 if (S->getFnParent() != nullptr) {
6185 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6188 // Local Named register
6189 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6190 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6191 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6195 case SC_PrivateExtern:
6198 } else if (SC == SC_Register) {
6199 // Global Named register
6200 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6201 const auto &TI = Context.getTargetInfo();
6202 bool HasSizeMismatch;
6204 if (!TI.isValidGCCRegisterName(Label))
6205 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6206 else if (!TI.validateGlobalRegisterVariable(Label,
6207 Context.getTypeSize(R),
6209 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6210 else if (HasSizeMismatch)
6211 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6214 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6215 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6216 NewVD->setInvalidDecl(true);
6220 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6221 Context, Label, 0));
6222 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6223 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6224 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6225 if (I != ExtnameUndeclaredIdentifiers.end()) {
6226 if (isDeclExternC(NewVD)) {
6227 NewVD->addAttr(I->second);
6228 ExtnameUndeclaredIdentifiers.erase(I);
6230 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6231 << /*Variable*/1 << NewVD;
6235 // Diagnose shadowed variables before filtering for scope.
6236 if (D.getCXXScopeSpec().isEmpty())
6237 CheckShadow(S, NewVD, Previous);
6239 // Don't consider existing declarations that are in a different
6240 // scope and are out-of-semantic-context declarations (if the new
6241 // declaration has linkage).
6242 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6243 D.getCXXScopeSpec().isNotEmpty() ||
6244 IsExplicitSpecialization ||
6245 IsVariableTemplateSpecialization);
6247 // Check whether the previous declaration is in the same block scope. This
6248 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6249 if (getLangOpts().CPlusPlus &&
6250 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6251 NewVD->setPreviousDeclInSameBlockScope(
6252 Previous.isSingleResult() && !Previous.isShadowed() &&
6253 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6255 if (!getLangOpts().CPlusPlus) {
6256 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6258 // If this is an explicit specialization of a static data member, check it.
6259 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6260 CheckMemberSpecialization(NewVD, Previous))
6261 NewVD->setInvalidDecl();
6263 // Merge the decl with the existing one if appropriate.
6264 if (!Previous.empty()) {
6265 if (Previous.isSingleResult() &&
6266 isa<FieldDecl>(Previous.getFoundDecl()) &&
6267 D.getCXXScopeSpec().isSet()) {
6268 // The user tried to define a non-static data member
6269 // out-of-line (C++ [dcl.meaning]p1).
6270 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6271 << D.getCXXScopeSpec().getRange();
6273 NewVD->setInvalidDecl();
6275 } else if (D.getCXXScopeSpec().isSet()) {
6276 // No previous declaration in the qualifying scope.
6277 Diag(D.getIdentifierLoc(), diag::err_no_member)
6278 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6279 << D.getCXXScopeSpec().getRange();
6280 NewVD->setInvalidDecl();
6283 if (!IsVariableTemplateSpecialization)
6284 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6287 VarTemplateDecl *PrevVarTemplate =
6288 NewVD->getPreviousDecl()
6289 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6292 // Check the template parameter list of this declaration, possibly
6293 // merging in the template parameter list from the previous variable
6294 // template declaration.
6295 if (CheckTemplateParameterList(
6297 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6299 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6300 DC->isDependentContext())
6301 ? TPC_ClassTemplateMember
6303 NewVD->setInvalidDecl();
6305 // If we are providing an explicit specialization of a static variable
6306 // template, make a note of that.
6307 if (PrevVarTemplate &&
6308 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6309 PrevVarTemplate->setMemberSpecialization();
6313 ProcessPragmaWeak(S, NewVD);
6315 // If this is the first declaration of an extern C variable, update
6316 // the map of such variables.
6317 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6318 isIncompleteDeclExternC(*this, NewVD))
6319 RegisterLocallyScopedExternCDecl(NewVD, S);
6321 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6322 Decl *ManglingContextDecl;
6323 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6324 NewVD->getDeclContext(), ManglingContextDecl)) {
6325 Context.setManglingNumber(
6326 NewVD, MCtx->getManglingNumber(
6327 NewVD, getMSManglingNumber(getLangOpts(), S)));
6328 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6332 // Special handling of variable named 'main'.
6333 if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6334 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6335 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6337 // C++ [basic.start.main]p3
6338 // A program that declares a variable main at global scope is ill-formed.
6339 if (getLangOpts().CPlusPlus)
6340 Diag(D.getLocStart(), diag::err_main_global_variable);
6342 // In C, and external-linkage variable named main results in undefined
6344 else if (NewVD->hasExternalFormalLinkage())
6345 Diag(D.getLocStart(), diag::warn_main_redefined);
6348 if (D.isRedeclaration() && !Previous.empty()) {
6349 checkDLLAttributeRedeclaration(
6350 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6351 IsExplicitSpecialization);
6355 if (NewVD->isInvalidDecl())
6356 NewTemplate->setInvalidDecl();
6357 ActOnDocumentableDecl(NewTemplate);
6364 /// \brief Diagnose variable or built-in function shadowing. Implements
6367 /// This method is called whenever a VarDecl is added to a "useful"
6370 /// \param S the scope in which the shadowing name is being declared
6371 /// \param R the lookup of the name
6373 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6374 // Return if warning is ignored.
6375 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6378 // Don't diagnose declarations at file scope.
6379 if (D->hasGlobalStorage())
6382 DeclContext *NewDC = D->getDeclContext();
6384 // Only diagnose if we're shadowing an unambiguous field or variable.
6385 if (R.getResultKind() != LookupResult::Found)
6388 NamedDecl* ShadowedDecl = R.getFoundDecl();
6389 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6392 // Fields are not shadowed by variables in C++ static methods.
6393 if (isa<FieldDecl>(ShadowedDecl))
6394 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6398 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6399 if (shadowedVar->isExternC()) {
6400 // For shadowing external vars, make sure that we point to the global
6401 // declaration, not a locally scoped extern declaration.
6402 for (auto I : shadowedVar->redecls())
6403 if (I->isFileVarDecl()) {
6409 DeclContext *OldDC = ShadowedDecl->getDeclContext();
6411 // Only warn about certain kinds of shadowing for class members.
6412 if (NewDC && NewDC->isRecord()) {
6413 // In particular, don't warn about shadowing non-class members.
6414 if (!OldDC->isRecord())
6417 // TODO: should we warn about static data members shadowing
6418 // static data members from base classes?
6420 // TODO: don't diagnose for inaccessible shadowed members.
6421 // This is hard to do perfectly because we might friend the
6422 // shadowing context, but that's just a false negative.
6425 // Determine what kind of declaration we're shadowing.
6427 // The order must be consistent with the %select in the warning message.
6428 enum ShadowedDeclKind { Local, Global, StaticMember, Field };
6429 ShadowedDeclKind Kind;
6430 if (isa<RecordDecl>(OldDC)) {
6431 if (isa<FieldDecl>(ShadowedDecl))
6434 Kind = StaticMember;
6435 } else if (OldDC->isFileContext()) {
6441 DeclarationName Name = R.getLookupName();
6443 // Emit warning and note.
6444 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6446 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6447 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6450 /// \brief Check -Wshadow without the advantage of a previous lookup.
6451 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6452 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6455 LookupResult R(*this, D->getDeclName(), D->getLocation(),
6456 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6458 CheckShadow(S, D, R);
6461 /// Check for conflict between this global or extern "C" declaration and
6462 /// previous global or extern "C" declarations. This is only used in C++.
6463 template<typename T>
6464 static bool checkGlobalOrExternCConflict(
6465 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6466 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6467 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6469 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6470 // The common case: this global doesn't conflict with any extern "C"
6476 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6477 // Both the old and new declarations have C language linkage. This is a
6480 Previous.addDecl(Prev);
6484 // This is a global, non-extern "C" declaration, and there is a previous
6485 // non-global extern "C" declaration. Diagnose if this is a variable
6487 if (!isa<VarDecl>(ND))
6490 // The declaration is extern "C". Check for any declaration in the
6491 // translation unit which might conflict.
6493 // We have already performed the lookup into the translation unit.
6495 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6497 if (isa<VarDecl>(*I)) {
6503 DeclContext::lookup_result R =
6504 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6505 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6507 if (isa<VarDecl>(*I)) {
6511 // FIXME: If we have any other entity with this name in global scope,
6512 // the declaration is ill-formed, but that is a defect: it breaks the
6513 // 'stat' hack, for instance. Only variables can have mangled name
6514 // clashes with extern "C" declarations, so only they deserve a
6523 // Use the first declaration's location to ensure we point at something which
6524 // is lexically inside an extern "C" linkage-spec.
6525 assert(Prev && "should have found a previous declaration to diagnose");
6526 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6527 Prev = FD->getFirstDecl();
6529 Prev = cast<VarDecl>(Prev)->getFirstDecl();
6531 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6533 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6538 /// Apply special rules for handling extern "C" declarations. Returns \c true
6539 /// if we have found that this is a redeclaration of some prior entity.
6541 /// Per C++ [dcl.link]p6:
6542 /// Two declarations [for a function or variable] with C language linkage
6543 /// with the same name that appear in different scopes refer to the same
6544 /// [entity]. An entity with C language linkage shall not be declared with
6545 /// the same name as an entity in global scope.
6546 template<typename T>
6547 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6548 LookupResult &Previous) {
6549 if (!S.getLangOpts().CPlusPlus) {
6550 // In C, when declaring a global variable, look for a corresponding 'extern'
6551 // variable declared in function scope. We don't need this in C++, because
6552 // we find local extern decls in the surrounding file-scope DeclContext.
6553 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6554 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6556 Previous.addDecl(Prev);
6563 // A declaration in the translation unit can conflict with an extern "C"
6565 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6566 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6568 // An extern "C" declaration can conflict with a declaration in the
6569 // translation unit or can be a redeclaration of an extern "C" declaration
6570 // in another scope.
6571 if (isIncompleteDeclExternC(S,ND))
6572 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6574 // Neither global nor extern "C": nothing to do.
6578 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6579 // If the decl is already known invalid, don't check it.
6580 if (NewVD->isInvalidDecl())
6583 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6584 QualType T = TInfo->getType();
6586 // Defer checking an 'auto' type until its initializer is attached.
6587 if (T->isUndeducedType())
6590 if (NewVD->hasAttrs())
6591 CheckAlignasUnderalignment(NewVD);
6593 if (T->isObjCObjectType()) {
6594 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6595 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6596 T = Context.getObjCObjectPointerType(T);
6600 // Emit an error if an address space was applied to decl with local storage.
6601 // This includes arrays of objects with address space qualifiers, but not
6602 // automatic variables that point to other address spaces.
6603 // ISO/IEC TR 18037 S5.1.2
6604 if (!getLangOpts().OpenCL
6605 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6606 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6607 NewVD->setInvalidDecl();
6611 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6613 if (getLangOpts().OpenCLVersion == 120 &&
6614 !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6615 NewVD->isStaticLocal()) {
6616 Diag(NewVD->getLocation(), diag::err_static_function_scope);
6617 NewVD->setInvalidDecl();
6621 if (getLangOpts().OpenCL) {
6622 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6623 if (NewVD->hasAttr<BlocksAttr>()) {
6624 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6628 if (T->isBlockPointerType()) {
6629 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6630 // can't use 'extern' storage class.
6631 if (!T.isConstQualified()) {
6632 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6634 NewVD->setInvalidDecl();
6637 if (NewVD->hasExternalStorage()) {
6638 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6639 NewVD->setInvalidDecl();
6642 // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6643 // TODO: this check is not enough as it doesn't diagnose the typedef
6644 const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6645 const FunctionProtoType *FTy =
6646 BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6647 if (FTy && FTy->isVariadic()) {
6648 Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6649 << T << NewVD->getSourceRange();
6650 NewVD->setInvalidDecl();
6654 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6655 // __constant address space.
6656 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6657 // variables inside a function can also be declared in the global
6659 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6660 NewVD->hasExternalStorage()) {
6661 if (!T->isSamplerT() &&
6662 !(T.getAddressSpace() == LangAS::opencl_constant ||
6663 (T.getAddressSpace() == LangAS::opencl_global &&
6664 getLangOpts().OpenCLVersion == 200))) {
6665 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6666 if (getLangOpts().OpenCLVersion == 200)
6667 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6668 << Scope << "global or constant";
6670 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6671 << Scope << "constant";
6672 NewVD->setInvalidDecl();
6676 if (T.getAddressSpace() == LangAS::opencl_global) {
6677 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6678 << 1 /*is any function*/ << "global";
6679 NewVD->setInvalidDecl();
6682 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6684 if (T.getAddressSpace() == LangAS::opencl_constant ||
6685 T.getAddressSpace() == LangAS::opencl_local) {
6686 FunctionDecl *FD = getCurFunctionDecl();
6687 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6688 if (T.getAddressSpace() == LangAS::opencl_constant)
6689 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6690 << 0 /*non-kernel only*/ << "constant";
6692 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6693 << 0 /*non-kernel only*/ << "local";
6694 NewVD->setInvalidDecl();
6701 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6702 && !NewVD->hasAttr<BlocksAttr>()) {
6703 if (getLangOpts().getGC() != LangOptions::NonGC)
6704 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6706 assert(!getLangOpts().ObjCAutoRefCount);
6707 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6711 bool isVM = T->isVariablyModifiedType();
6712 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6713 NewVD->hasAttr<BlocksAttr>())
6714 getCurFunction()->setHasBranchProtectedScope();
6716 if ((isVM && NewVD->hasLinkage()) ||
6717 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6718 bool SizeIsNegative;
6719 llvm::APSInt Oversized;
6720 TypeSourceInfo *FixedTInfo =
6721 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6722 SizeIsNegative, Oversized);
6723 if (!FixedTInfo && T->isVariableArrayType()) {
6724 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6725 // FIXME: This won't give the correct result for
6727 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6729 if (NewVD->isFileVarDecl())
6730 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6732 else if (NewVD->isStaticLocal())
6733 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6736 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6738 NewVD->setInvalidDecl();
6743 if (NewVD->isFileVarDecl())
6744 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6746 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6747 NewVD->setInvalidDecl();
6751 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6752 NewVD->setType(FixedTInfo->getType());
6753 NewVD->setTypeSourceInfo(FixedTInfo);
6756 if (T->isVoidType()) {
6757 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6758 // of objects and functions.
6759 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6760 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6762 NewVD->setInvalidDecl();
6767 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6768 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6769 NewVD->setInvalidDecl();
6773 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6774 Diag(NewVD->getLocation(), diag::err_block_on_vm);
6775 NewVD->setInvalidDecl();
6779 if (NewVD->isConstexpr() && !T->isDependentType() &&
6780 RequireLiteralType(NewVD->getLocation(), T,
6781 diag::err_constexpr_var_non_literal)) {
6782 NewVD->setInvalidDecl();
6787 /// \brief Perform semantic checking on a newly-created variable
6790 /// This routine performs all of the type-checking required for a
6791 /// variable declaration once it has been built. It is used both to
6792 /// check variables after they have been parsed and their declarators
6793 /// have been translated into a declaration, and to check variables
6794 /// that have been instantiated from a template.
6796 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6798 /// Returns true if the variable declaration is a redeclaration.
6799 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6800 CheckVariableDeclarationType(NewVD);
6802 // If the decl is already known invalid, don't check it.
6803 if (NewVD->isInvalidDecl())
6806 // If we did not find anything by this name, look for a non-visible
6807 // extern "C" declaration with the same name.
6808 if (Previous.empty() &&
6809 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6810 Previous.setShadowed();
6812 if (!Previous.empty()) {
6813 MergeVarDecl(NewVD, Previous);
6820 struct FindOverriddenMethod {
6822 CXXMethodDecl *Method;
6824 /// Member lookup function that determines whether a given C++
6825 /// method overrides a method in a base class, to be used with
6826 /// CXXRecordDecl::lookupInBases().
6827 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6828 RecordDecl *BaseRecord =
6829 Specifier->getType()->getAs<RecordType>()->getDecl();
6831 DeclarationName Name = Method->getDeclName();
6833 // FIXME: Do we care about other names here too?
6834 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6835 // We really want to find the base class destructor here.
6836 QualType T = S->Context.getTypeDeclType(BaseRecord);
6837 CanQualType CT = S->Context.getCanonicalType(T);
6839 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6842 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6843 Path.Decls = Path.Decls.slice(1)) {
6844 NamedDecl *D = Path.Decls.front();
6845 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6846 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6855 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6856 } // end anonymous namespace
6858 /// \brief Report an error regarding overriding, along with any relevant
6859 /// overriden methods.
6861 /// \param DiagID the primary error to report.
6862 /// \param MD the overriding method.
6863 /// \param OEK which overrides to include as notes.
6864 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6865 OverrideErrorKind OEK = OEK_All) {
6866 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6867 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6868 E = MD->end_overridden_methods();
6870 // This check (& the OEK parameter) could be replaced by a predicate, but
6871 // without lambdas that would be overkill. This is still nicer than writing
6872 // out the diag loop 3 times.
6873 if ((OEK == OEK_All) ||
6874 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6875 (OEK == OEK_Deleted && (*I)->isDeleted()))
6876 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6880 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6881 /// and if so, check that it's a valid override and remember it.
6882 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6883 // Look for methods in base classes that this method might override.
6885 FindOverriddenMethod FOM;
6888 bool hasDeletedOverridenMethods = false;
6889 bool hasNonDeletedOverridenMethods = false;
6890 bool AddedAny = false;
6891 if (DC->lookupInBases(FOM, Paths)) {
6892 for (auto *I : Paths.found_decls()) {
6893 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6894 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6895 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6896 !CheckOverridingFunctionAttributes(MD, OldMD) &&
6897 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6898 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6899 hasDeletedOverridenMethods |= OldMD->isDeleted();
6900 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6907 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6908 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6910 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6911 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6918 // Struct for holding all of the extra arguments needed by
6919 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6920 struct ActOnFDArgs {
6923 MultiTemplateParamsArg TemplateParamLists;
6926 } // end anonymous namespace
6930 // Callback to only accept typo corrections that have a non-zero edit distance.
6931 // Also only accept corrections that have the same parent decl.
6932 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6934 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6935 CXXRecordDecl *Parent)
6936 : Context(Context), OriginalFD(TypoFD),
6937 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6939 bool ValidateCandidate(const TypoCorrection &candidate) override {
6940 if (candidate.getEditDistance() == 0)
6943 SmallVector<unsigned, 1> MismatchedParams;
6944 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6945 CDeclEnd = candidate.end();
6946 CDecl != CDeclEnd; ++CDecl) {
6947 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6949 if (FD && !FD->hasBody() &&
6950 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6951 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6952 CXXRecordDecl *Parent = MD->getParent();
6953 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6955 } else if (!ExpectedParent) {
6965 ASTContext &Context;
6966 FunctionDecl *OriginalFD;
6967 CXXRecordDecl *ExpectedParent;
6970 } // end anonymous namespace
6972 /// \brief Generate diagnostics for an invalid function redeclaration.
6974 /// This routine handles generating the diagnostic messages for an invalid
6975 /// function redeclaration, including finding possible similar declarations
6976 /// or performing typo correction if there are no previous declarations with
6979 /// Returns a NamedDecl iff typo correction was performed and substituting in
6980 /// the new declaration name does not cause new errors.
6981 static NamedDecl *DiagnoseInvalidRedeclaration(
6982 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6983 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6984 DeclarationName Name = NewFD->getDeclName();
6985 DeclContext *NewDC = NewFD->getDeclContext();
6986 SmallVector<unsigned, 1> MismatchedParams;
6987 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6988 TypoCorrection Correction;
6989 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6990 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6991 : diag::err_member_decl_does_not_match;
6992 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6993 IsLocalFriend ? Sema::LookupLocalFriendName
6994 : Sema::LookupOrdinaryName,
6995 Sema::ForRedeclaration);
6997 NewFD->setInvalidDecl();
6999 SemaRef.LookupName(Prev, S);
7001 SemaRef.LookupQualifiedName(Prev, NewDC);
7002 assert(!Prev.isAmbiguous() &&
7003 "Cannot have an ambiguity in previous-declaration lookup");
7004 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7005 if (!Prev.empty()) {
7006 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7007 Func != FuncEnd; ++Func) {
7008 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7010 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7011 // Add 1 to the index so that 0 can mean the mismatch didn't
7012 // involve a parameter
7014 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7015 NearMatches.push_back(std::make_pair(FD, ParamNum));
7018 // If the qualified name lookup yielded nothing, try typo correction
7019 } else if ((Correction = SemaRef.CorrectTypo(
7020 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7021 &ExtraArgs.D.getCXXScopeSpec(),
7022 llvm::make_unique<DifferentNameValidatorCCC>(
7023 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7024 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7025 // Set up everything for the call to ActOnFunctionDeclarator
7026 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7027 ExtraArgs.D.getIdentifierLoc());
7029 Previous.setLookupName(Correction.getCorrection());
7030 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7031 CDeclEnd = Correction.end();
7032 CDecl != CDeclEnd; ++CDecl) {
7033 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7034 if (FD && !FD->hasBody() &&
7035 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7036 Previous.addDecl(FD);
7039 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7042 // Retry building the function declaration with the new previous
7043 // declarations, and with errors suppressed.
7046 Sema::SFINAETrap Trap(SemaRef);
7048 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7049 // pieces need to verify the typo-corrected C++ declaration and hopefully
7050 // eliminate the need for the parameter pack ExtraArgs.
7051 Result = SemaRef.ActOnFunctionDeclarator(
7052 ExtraArgs.S, ExtraArgs.D,
7053 Correction.getCorrectionDecl()->getDeclContext(),
7054 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7055 ExtraArgs.AddToScope);
7057 if (Trap.hasErrorOccurred())
7062 // Determine which correction we picked.
7063 Decl *Canonical = Result->getCanonicalDecl();
7064 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7066 if ((*I)->getCanonicalDecl() == Canonical)
7067 Correction.setCorrectionDecl(*I);
7069 SemaRef.diagnoseTypo(
7071 SemaRef.PDiag(IsLocalFriend
7072 ? diag::err_no_matching_local_friend_suggest
7073 : diag::err_member_decl_does_not_match_suggest)
7074 << Name << NewDC << IsDefinition);
7078 // Pretend the typo correction never occurred
7079 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7080 ExtraArgs.D.getIdentifierLoc());
7081 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7083 Previous.setLookupName(Name);
7086 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7087 << Name << NewDC << IsDefinition << NewFD->getLocation();
7089 bool NewFDisConst = false;
7090 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7091 NewFDisConst = NewMD->isConst();
7093 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7094 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7095 NearMatch != NearMatchEnd; ++NearMatch) {
7096 FunctionDecl *FD = NearMatch->first;
7097 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7098 bool FDisConst = MD && MD->isConst();
7099 bool IsMember = MD || !IsLocalFriend;
7101 // FIXME: These notes are poorly worded for the local friend case.
7102 if (unsigned Idx = NearMatch->second) {
7103 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7104 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7105 if (Loc.isInvalid()) Loc = FD->getLocation();
7106 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7107 : diag::note_local_decl_close_param_match)
7108 << Idx << FDParam->getType()
7109 << NewFD->getParamDecl(Idx - 1)->getType();
7110 } else if (FDisConst != NewFDisConst) {
7111 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7112 << NewFDisConst << FD->getSourceRange().getEnd();
7114 SemaRef.Diag(FD->getLocation(),
7115 IsMember ? diag::note_member_def_close_match
7116 : diag::note_local_decl_close_match);
7121 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7122 switch (D.getDeclSpec().getStorageClassSpec()) {
7123 default: llvm_unreachable("Unknown storage class!");
7124 case DeclSpec::SCS_auto:
7125 case DeclSpec::SCS_register:
7126 case DeclSpec::SCS_mutable:
7127 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7128 diag::err_typecheck_sclass_func);
7131 case DeclSpec::SCS_unspecified: break;
7132 case DeclSpec::SCS_extern:
7133 if (D.getDeclSpec().isExternInLinkageSpec())
7136 case DeclSpec::SCS_static: {
7137 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7139 // The declaration of an identifier for a function that has
7140 // block scope shall have no explicit storage-class specifier
7141 // other than extern
7142 // See also (C++ [dcl.stc]p4).
7143 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7144 diag::err_static_block_func);
7149 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7152 // No explicit storage class has already been returned
7156 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7157 DeclContext *DC, QualType &R,
7158 TypeSourceInfo *TInfo,
7160 bool &IsVirtualOkay) {
7161 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7162 DeclarationName Name = NameInfo.getName();
7164 FunctionDecl *NewFD = nullptr;
7165 bool isInline = D.getDeclSpec().isInlineSpecified();
7167 if (!SemaRef.getLangOpts().CPlusPlus) {
7168 // Determine whether the function was written with a
7169 // prototype. This true when:
7170 // - there is a prototype in the declarator, or
7171 // - the type R of the function is some kind of typedef or other reference
7172 // to a type name (which eventually refers to a function type).
7174 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7175 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7177 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7178 D.getLocStart(), NameInfo, R,
7179 TInfo, SC, isInline,
7180 HasPrototype, false);
7181 if (D.isInvalidType())
7182 NewFD->setInvalidDecl();
7187 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7188 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7190 // Check that the return type is not an abstract class type.
7191 // For record types, this is done by the AbstractClassUsageDiagnoser once
7192 // the class has been completely parsed.
7193 if (!DC->isRecord() &&
7194 SemaRef.RequireNonAbstractType(
7195 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7196 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7199 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7200 // This is a C++ constructor declaration.
7201 assert(DC->isRecord() &&
7202 "Constructors can only be declared in a member context");
7204 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7205 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7206 D.getLocStart(), NameInfo,
7207 R, TInfo, isExplicit, isInline,
7208 /*isImplicitlyDeclared=*/false,
7211 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7212 // This is a C++ destructor declaration.
7213 if (DC->isRecord()) {
7214 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7215 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7216 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7217 SemaRef.Context, Record,
7219 NameInfo, R, TInfo, isInline,
7220 /*isImplicitlyDeclared=*/false);
7222 // If the class is complete, then we now create the implicit exception
7223 // specification. If the class is incomplete or dependent, we can't do
7225 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7226 Record->getDefinition() && !Record->isBeingDefined() &&
7227 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7228 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7231 IsVirtualOkay = true;
7235 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7238 // Create a FunctionDecl to satisfy the function definition parsing
7240 return FunctionDecl::Create(SemaRef.Context, DC,
7242 D.getIdentifierLoc(), Name, R, TInfo,
7244 /*hasPrototype=*/true, isConstexpr);
7247 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7248 if (!DC->isRecord()) {
7249 SemaRef.Diag(D.getIdentifierLoc(),
7250 diag::err_conv_function_not_member);
7254 SemaRef.CheckConversionDeclarator(D, R, SC);
7255 IsVirtualOkay = true;
7256 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7257 D.getLocStart(), NameInfo,
7258 R, TInfo, isInline, isExplicit,
7259 isConstexpr, SourceLocation());
7261 } else if (DC->isRecord()) {
7262 // If the name of the function is the same as the name of the record,
7263 // then this must be an invalid constructor that has a return type.
7264 // (The parser checks for a return type and makes the declarator a
7265 // constructor if it has no return type).
7266 if (Name.getAsIdentifierInfo() &&
7267 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7268 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7269 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7270 << SourceRange(D.getIdentifierLoc());
7274 // This is a C++ method declaration.
7275 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7276 cast<CXXRecordDecl>(DC),
7277 D.getLocStart(), NameInfo, R,
7278 TInfo, SC, isInline,
7279 isConstexpr, SourceLocation());
7280 IsVirtualOkay = !Ret->isStatic();
7284 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7285 if (!isFriend && SemaRef.CurContext->isRecord())
7288 // Determine whether the function was written with a
7289 // prototype. This true when:
7290 // - we're in C++ (where every function has a prototype),
7291 return FunctionDecl::Create(SemaRef.Context, DC,
7293 NameInfo, R, TInfo, SC, isInline,
7294 true/*HasPrototype*/, isConstexpr);
7298 enum OpenCLParamType {
7302 PrivatePtrKernelParam,
7307 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7308 if (PT->isPointerType()) {
7309 QualType PointeeType = PT->getPointeeType();
7310 if (PointeeType->isPointerType())
7311 return PtrPtrKernelParam;
7312 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7316 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7317 // be used as builtin types.
7319 if (PT->isImageType())
7320 return PtrKernelParam;
7322 if (PT->isBooleanType())
7323 return InvalidKernelParam;
7326 return InvalidKernelParam;
7328 if (PT->isHalfType())
7329 return InvalidKernelParam;
7331 if (PT->isRecordType())
7332 return RecordKernelParam;
7334 return ValidKernelParam;
7337 static void checkIsValidOpenCLKernelParameter(
7341 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7342 QualType PT = Param->getType();
7344 // Cache the valid types we encounter to avoid rechecking structs that are
7346 if (ValidTypes.count(PT.getTypePtr()))
7349 switch (getOpenCLKernelParameterType(PT)) {
7350 case PtrPtrKernelParam:
7351 // OpenCL v1.2 s6.9.a:
7352 // A kernel function argument cannot be declared as a
7353 // pointer to a pointer type.
7354 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7358 case PrivatePtrKernelParam:
7359 // OpenCL v1.2 s6.9.a:
7360 // A kernel function argument cannot be declared as a
7361 // pointer to the private address space.
7362 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7366 // OpenCL v1.2 s6.9.k:
7367 // Arguments to kernel functions in a program cannot be declared with the
7368 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7369 // uintptr_t or a struct and/or union that contain fields declared to be
7370 // one of these built-in scalar types.
7372 case InvalidKernelParam:
7373 // OpenCL v1.2 s6.8 n:
7374 // A kernel function argument cannot be declared
7376 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7380 case PtrKernelParam:
7381 case ValidKernelParam:
7382 ValidTypes.insert(PT.getTypePtr());
7385 case RecordKernelParam:
7389 // Track nested structs we will inspect
7390 SmallVector<const Decl *, 4> VisitStack;
7392 // Track where we are in the nested structs. Items will migrate from
7393 // VisitStack to HistoryStack as we do the DFS for bad field.
7394 SmallVector<const FieldDecl *, 4> HistoryStack;
7395 HistoryStack.push_back(nullptr);
7397 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7398 VisitStack.push_back(PD);
7400 assert(VisitStack.back() && "First decl null?");
7403 const Decl *Next = VisitStack.pop_back_val();
7405 assert(!HistoryStack.empty());
7406 // Found a marker, we have gone up a level
7407 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7408 ValidTypes.insert(Hist->getType().getTypePtr());
7413 // Adds everything except the original parameter declaration (which is not a
7414 // field itself) to the history stack.
7415 const RecordDecl *RD;
7416 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7417 HistoryStack.push_back(Field);
7418 RD = Field->getType()->castAs<RecordType>()->getDecl();
7420 RD = cast<RecordDecl>(Next);
7423 // Add a null marker so we know when we've gone back up a level
7424 VisitStack.push_back(nullptr);
7426 for (const auto *FD : RD->fields()) {
7427 QualType QT = FD->getType();
7429 if (ValidTypes.count(QT.getTypePtr()))
7432 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7433 if (ParamType == ValidKernelParam)
7436 if (ParamType == RecordKernelParam) {
7437 VisitStack.push_back(FD);
7441 // OpenCL v1.2 s6.9.p:
7442 // Arguments to kernel functions that are declared to be a struct or union
7443 // do not allow OpenCL objects to be passed as elements of the struct or
7445 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7446 ParamType == PrivatePtrKernelParam) {
7447 S.Diag(Param->getLocation(),
7448 diag::err_record_with_pointers_kernel_param)
7449 << PT->isUnionType()
7452 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7455 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7456 << PD->getDeclName();
7458 // We have an error, now let's go back up through history and show where
7459 // the offending field came from
7460 for (ArrayRef<const FieldDecl *>::const_iterator
7461 I = HistoryStack.begin() + 1,
7462 E = HistoryStack.end();
7464 const FieldDecl *OuterField = *I;
7465 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7466 << OuterField->getType();
7469 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7470 << QT->isPointerType()
7475 } while (!VisitStack.empty());
7479 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7480 TypeSourceInfo *TInfo, LookupResult &Previous,
7481 MultiTemplateParamsArg TemplateParamLists,
7483 QualType R = TInfo->getType();
7485 assert(R.getTypePtr()->isFunctionType());
7487 // TODO: consider using NameInfo for diagnostic.
7488 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7489 DeclarationName Name = NameInfo.getName();
7490 StorageClass SC = getFunctionStorageClass(*this, D);
7492 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7493 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7494 diag::err_invalid_thread)
7495 << DeclSpec::getSpecifierName(TSCS);
7497 if (D.isFirstDeclarationOfMember())
7498 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7499 D.getIdentifierLoc());
7501 bool isFriend = false;
7502 FunctionTemplateDecl *FunctionTemplate = nullptr;
7503 bool isExplicitSpecialization = false;
7504 bool isFunctionTemplateSpecialization = false;
7506 bool isDependentClassScopeExplicitSpecialization = false;
7507 bool HasExplicitTemplateArgs = false;
7508 TemplateArgumentListInfo TemplateArgs;
7510 bool isVirtualOkay = false;
7512 DeclContext *OriginalDC = DC;
7513 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7515 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7517 if (!NewFD) return nullptr;
7519 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7520 NewFD->setTopLevelDeclInObjCContainer();
7522 // Set the lexical context. If this is a function-scope declaration, or has a
7523 // C++ scope specifier, or is the object of a friend declaration, the lexical
7524 // context will be different from the semantic context.
7525 NewFD->setLexicalDeclContext(CurContext);
7527 if (IsLocalExternDecl)
7528 NewFD->setLocalExternDecl();
7530 if (getLangOpts().CPlusPlus) {
7531 bool isInline = D.getDeclSpec().isInlineSpecified();
7532 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7533 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7534 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7535 bool isConcept = D.getDeclSpec().isConceptSpecified();
7536 isFriend = D.getDeclSpec().isFriendSpecified();
7537 if (isFriend && !isInline && D.isFunctionDefinition()) {
7538 // C++ [class.friend]p5
7539 // A function can be defined in a friend declaration of a
7540 // class . . . . Such a function is implicitly inline.
7541 NewFD->setImplicitlyInline();
7544 // If this is a method defined in an __interface, and is not a constructor
7545 // or an overloaded operator, then set the pure flag (isVirtual will already
7547 if (const CXXRecordDecl *Parent =
7548 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7549 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7550 NewFD->setPure(true);
7552 // C++ [class.union]p2
7553 // A union can have member functions, but not virtual functions.
7554 if (isVirtual && Parent->isUnion())
7555 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7558 SetNestedNameSpecifier(NewFD, D);
7559 isExplicitSpecialization = false;
7560 isFunctionTemplateSpecialization = false;
7561 if (D.isInvalidType())
7562 NewFD->setInvalidDecl();
7564 // Match up the template parameter lists with the scope specifier, then
7565 // determine whether we have a template or a template specialization.
7566 bool Invalid = false;
7567 if (TemplateParameterList *TemplateParams =
7568 MatchTemplateParametersToScopeSpecifier(
7569 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7570 D.getCXXScopeSpec(),
7571 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7572 ? D.getName().TemplateId
7574 TemplateParamLists, isFriend, isExplicitSpecialization,
7576 if (TemplateParams->size() > 0) {
7577 // This is a function template
7579 // Check that we can declare a template here.
7580 if (CheckTemplateDeclScope(S, TemplateParams))
7581 NewFD->setInvalidDecl();
7583 // A destructor cannot be a template.
7584 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7585 Diag(NewFD->getLocation(), diag::err_destructor_template);
7586 NewFD->setInvalidDecl();
7589 // If we're adding a template to a dependent context, we may need to
7590 // rebuilding some of the types used within the template parameter list,
7591 // now that we know what the current instantiation is.
7592 if (DC->isDependentContext()) {
7593 ContextRAII SavedContext(*this, DC);
7594 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7598 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7599 NewFD->getLocation(),
7600 Name, TemplateParams,
7602 FunctionTemplate->setLexicalDeclContext(CurContext);
7603 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7605 // For source fidelity, store the other template param lists.
7606 if (TemplateParamLists.size() > 1) {
7607 NewFD->setTemplateParameterListsInfo(Context,
7608 TemplateParamLists.drop_back(1));
7611 // This is a function template specialization.
7612 isFunctionTemplateSpecialization = true;
7613 // For source fidelity, store all the template param lists.
7614 if (TemplateParamLists.size() > 0)
7615 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7617 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7619 // We want to remove the "template<>", found here.
7620 SourceRange RemoveRange = TemplateParams->getSourceRange();
7622 // If we remove the template<> and the name is not a
7623 // template-id, we're actually silently creating a problem:
7624 // the friend declaration will refer to an untemplated decl,
7625 // and clearly the user wants a template specialization. So
7626 // we need to insert '<>' after the name.
7627 SourceLocation InsertLoc;
7628 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7629 InsertLoc = D.getName().getSourceRange().getEnd();
7630 InsertLoc = getLocForEndOfToken(InsertLoc);
7633 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7634 << Name << RemoveRange
7635 << FixItHint::CreateRemoval(RemoveRange)
7636 << FixItHint::CreateInsertion(InsertLoc, "<>");
7641 // All template param lists were matched against the scope specifier:
7642 // this is NOT (an explicit specialization of) a template.
7643 if (TemplateParamLists.size() > 0)
7644 // For source fidelity, store all the template param lists.
7645 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7649 NewFD->setInvalidDecl();
7650 if (FunctionTemplate)
7651 FunctionTemplate->setInvalidDecl();
7654 // C++ [dcl.fct.spec]p5:
7655 // The virtual specifier shall only be used in declarations of
7656 // nonstatic class member functions that appear within a
7657 // member-specification of a class declaration; see 10.3.
7659 if (isVirtual && !NewFD->isInvalidDecl()) {
7660 if (!isVirtualOkay) {
7661 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7662 diag::err_virtual_non_function);
7663 } else if (!CurContext->isRecord()) {
7664 // 'virtual' was specified outside of the class.
7665 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7666 diag::err_virtual_out_of_class)
7667 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7668 } else if (NewFD->getDescribedFunctionTemplate()) {
7669 // C++ [temp.mem]p3:
7670 // A member function template shall not be virtual.
7671 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7672 diag::err_virtual_member_function_template)
7673 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7675 // Okay: Add virtual to the method.
7676 NewFD->setVirtualAsWritten(true);
7679 if (getLangOpts().CPlusPlus14 &&
7680 NewFD->getReturnType()->isUndeducedType())
7681 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7684 if (getLangOpts().CPlusPlus14 &&
7685 (NewFD->isDependentContext() ||
7686 (isFriend && CurContext->isDependentContext())) &&
7687 NewFD->getReturnType()->isUndeducedType()) {
7688 // If the function template is referenced directly (for instance, as a
7689 // member of the current instantiation), pretend it has a dependent type.
7690 // This is not really justified by the standard, but is the only sane
7692 // FIXME: For a friend function, we have not marked the function as being
7693 // a friend yet, so 'isDependentContext' on the FD doesn't work.
7694 const FunctionProtoType *FPT =
7695 NewFD->getType()->castAs<FunctionProtoType>();
7697 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7698 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7699 FPT->getExtProtoInfo()));
7702 // C++ [dcl.fct.spec]p3:
7703 // The inline specifier shall not appear on a block scope function
7705 if (isInline && !NewFD->isInvalidDecl()) {
7706 if (CurContext->isFunctionOrMethod()) {
7707 // 'inline' is not allowed on block scope function declaration.
7708 Diag(D.getDeclSpec().getInlineSpecLoc(),
7709 diag::err_inline_declaration_block_scope) << Name
7710 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7714 // C++ [dcl.fct.spec]p6:
7715 // The explicit specifier shall be used only in the declaration of a
7716 // constructor or conversion function within its class definition;
7717 // see 12.3.1 and 12.3.2.
7718 if (isExplicit && !NewFD->isInvalidDecl()) {
7719 if (!CurContext->isRecord()) {
7720 // 'explicit' was specified outside of the class.
7721 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7722 diag::err_explicit_out_of_class)
7723 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7724 } else if (!isa<CXXConstructorDecl>(NewFD) &&
7725 !isa<CXXConversionDecl>(NewFD)) {
7726 // 'explicit' was specified on a function that wasn't a constructor
7727 // or conversion function.
7728 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7729 diag::err_explicit_non_ctor_or_conv_function)
7730 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7735 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7736 // are implicitly inline.
7737 NewFD->setImplicitlyInline();
7739 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7740 // be either constructors or to return a literal type. Therefore,
7741 // destructors cannot be declared constexpr.
7742 if (isa<CXXDestructorDecl>(NewFD))
7743 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7747 // This is a function concept.
7748 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7751 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7752 // applied only to the definition of a function template [...]
7753 if (!D.isFunctionDefinition()) {
7754 Diag(D.getDeclSpec().getConceptSpecLoc(),
7755 diag::err_function_concept_not_defined);
7756 NewFD->setInvalidDecl();
7759 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7760 // have no exception-specification and is treated as if it were specified
7761 // with noexcept(true) (15.4). [...]
7762 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7763 if (FPT->hasExceptionSpec()) {
7765 if (D.isFunctionDeclarator())
7766 Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7767 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7768 << FixItHint::CreateRemoval(Range);
7769 NewFD->setInvalidDecl();
7771 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7774 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7775 // following restrictions:
7776 // - The declared return type shall have the type bool.
7777 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7778 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7779 NewFD->setInvalidDecl();
7782 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7783 // following restrictions:
7784 // - The declaration's parameter list shall be equivalent to an empty
7786 if (FPT->getNumParams() > 0 || FPT->isVariadic())
7787 Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7790 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7791 // implicity defined to be a constexpr declaration (implicitly inline)
7792 NewFD->setImplicitlyInline();
7794 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7795 // be declared with the thread_local, inline, friend, or constexpr
7796 // specifiers, [...]
7798 Diag(D.getDeclSpec().getInlineSpecLoc(),
7799 diag::err_concept_decl_invalid_specifiers)
7801 NewFD->setInvalidDecl(true);
7805 Diag(D.getDeclSpec().getFriendSpecLoc(),
7806 diag::err_concept_decl_invalid_specifiers)
7808 NewFD->setInvalidDecl(true);
7812 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7813 diag::err_concept_decl_invalid_specifiers)
7815 NewFD->setInvalidDecl(true);
7818 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7819 // applied only to the definition of a function template or variable
7820 // template, declared in namespace scope.
7821 if (isFunctionTemplateSpecialization) {
7822 Diag(D.getDeclSpec().getConceptSpecLoc(),
7823 diag::err_concept_specified_specialization) << 1;
7827 // If __module_private__ was specified, mark the function accordingly.
7828 if (D.getDeclSpec().isModulePrivateSpecified()) {
7829 if (isFunctionTemplateSpecialization) {
7830 SourceLocation ModulePrivateLoc
7831 = D.getDeclSpec().getModulePrivateSpecLoc();
7832 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7834 << FixItHint::CreateRemoval(ModulePrivateLoc);
7836 NewFD->setModulePrivate();
7837 if (FunctionTemplate)
7838 FunctionTemplate->setModulePrivate();
7843 if (FunctionTemplate) {
7844 FunctionTemplate->setObjectOfFriendDecl();
7845 FunctionTemplate->setAccess(AS_public);
7847 NewFD->setObjectOfFriendDecl();
7848 NewFD->setAccess(AS_public);
7851 // If a function is defined as defaulted or deleted, mark it as such now.
7852 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7853 // definition kind to FDK_Definition.
7854 switch (D.getFunctionDefinitionKind()) {
7855 case FDK_Declaration:
7856 case FDK_Definition:
7860 NewFD->setDefaulted();
7864 NewFD->setDeletedAsWritten();
7868 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7869 D.isFunctionDefinition()) {
7870 // C++ [class.mfct]p2:
7871 // A member function may be defined (8.4) in its class definition, in
7872 // which case it is an inline member function (7.1.2)
7873 NewFD->setImplicitlyInline();
7876 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7877 !CurContext->isRecord()) {
7878 // C++ [class.static]p1:
7879 // A data or function member of a class may be declared static
7880 // in a class definition, in which case it is a static member of
7883 // Complain about the 'static' specifier if it's on an out-of-line
7884 // member function definition.
7885 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7886 diag::err_static_out_of_line)
7887 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7890 // C++11 [except.spec]p15:
7891 // A deallocation function with no exception-specification is treated
7892 // as if it were specified with noexcept(true).
7893 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7894 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7895 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7896 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7897 NewFD->setType(Context.getFunctionType(
7898 FPT->getReturnType(), FPT->getParamTypes(),
7899 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7902 // Filter out previous declarations that don't match the scope.
7903 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7904 D.getCXXScopeSpec().isNotEmpty() ||
7905 isExplicitSpecialization ||
7906 isFunctionTemplateSpecialization);
7908 // Handle GNU asm-label extension (encoded as an attribute).
7909 if (Expr *E = (Expr*) D.getAsmLabel()) {
7910 // The parser guarantees this is a string.
7911 StringLiteral *SE = cast<StringLiteral>(E);
7912 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7913 SE->getString(), 0));
7914 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7915 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7916 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7917 if (I != ExtnameUndeclaredIdentifiers.end()) {
7918 if (isDeclExternC(NewFD)) {
7919 NewFD->addAttr(I->second);
7920 ExtnameUndeclaredIdentifiers.erase(I);
7922 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7923 << /*Variable*/0 << NewFD;
7927 // Copy the parameter declarations from the declarator D to the function
7928 // declaration NewFD, if they are available. First scavenge them into Params.
7929 SmallVector<ParmVarDecl*, 16> Params;
7930 if (D.isFunctionDeclarator()) {
7931 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7933 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7934 // function that takes no arguments, not a function that takes a
7935 // single void argument.
7936 // We let through "const void" here because Sema::GetTypeForDeclarator
7937 // already checks for that case.
7938 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7939 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7940 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7941 assert(Param->getDeclContext() != NewFD && "Was set before ?");
7942 Param->setDeclContext(NewFD);
7943 Params.push_back(Param);
7945 if (Param->isInvalidDecl())
7946 NewFD->setInvalidDecl();
7949 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7950 // When we're declaring a function with a typedef, typeof, etc as in the
7951 // following example, we'll need to synthesize (unnamed)
7952 // parameters for use in the declaration.
7955 // typedef void fn(int);
7959 // Synthesize a parameter for each argument type.
7960 for (const auto &AI : FT->param_types()) {
7961 ParmVarDecl *Param =
7962 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7963 Param->setScopeInfo(0, Params.size());
7964 Params.push_back(Param);
7967 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7968 "Should not need args for typedef of non-prototype fn");
7971 // Finally, we know we have the right number of parameters, install them.
7972 NewFD->setParams(Params);
7974 // Find all anonymous symbols defined during the declaration of this function
7975 // and add to NewFD. This lets us track decls such 'enum Y' in:
7977 // void f(enum Y {AA} x) {}
7979 // which would otherwise incorrectly end up in the translation unit scope.
7980 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7981 DeclsInPrototypeScope.clear();
7983 if (D.getDeclSpec().isNoreturnSpecified())
7985 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7988 // Functions returning a variably modified type violate C99 6.7.5.2p2
7989 // because all functions have linkage.
7990 if (!NewFD->isInvalidDecl() &&
7991 NewFD->getReturnType()->isVariablyModifiedType()) {
7992 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7993 NewFD->setInvalidDecl();
7996 // Apply an implicit SectionAttr if #pragma code_seg is active.
7997 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7998 !NewFD->hasAttr<SectionAttr>()) {
8000 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8001 CodeSegStack.CurrentValue->getString(),
8002 CodeSegStack.CurrentPragmaLocation));
8003 if (UnifySection(CodeSegStack.CurrentValue->getString(),
8004 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8005 ASTContext::PSF_Read,
8007 NewFD->dropAttr<SectionAttr>();
8010 // Handle attributes.
8011 ProcessDeclAttributes(S, NewFD, D);
8013 if (getLangOpts().OpenCL) {
8014 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8015 // type declaration will generate a compilation error.
8016 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8017 if (AddressSpace == LangAS::opencl_local ||
8018 AddressSpace == LangAS::opencl_global ||
8019 AddressSpace == LangAS::opencl_constant) {
8020 Diag(NewFD->getLocation(),
8021 diag::err_opencl_return_value_with_address_space);
8022 NewFD->setInvalidDecl();
8026 if (!getLangOpts().CPlusPlus) {
8027 // Perform semantic checking on the function declaration.
8028 bool isExplicitSpecialization=false;
8029 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8030 CheckMain(NewFD, D.getDeclSpec());
8032 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8033 CheckMSVCRTEntryPoint(NewFD);
8035 if (!NewFD->isInvalidDecl())
8036 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8037 isExplicitSpecialization));
8038 else if (!Previous.empty())
8039 // Recover gracefully from an invalid redeclaration.
8040 D.setRedeclaration(true);
8041 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8042 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8043 "previous declaration set still overloaded");
8045 // Diagnose no-prototype function declarations with calling conventions that
8046 // don't support variadic calls. Only do this in C and do it after merging
8047 // possibly prototyped redeclarations.
8048 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8049 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8050 CallingConv CC = FT->getExtInfo().getCC();
8051 if (!supportsVariadicCall(CC)) {
8052 // Windows system headers sometimes accidentally use stdcall without
8053 // (void) parameters, so we relax this to a warning.
8055 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8056 Diag(NewFD->getLocation(), DiagID)
8057 << FunctionType::getNameForCallConv(CC);
8061 // C++11 [replacement.functions]p3:
8062 // The program's definitions shall not be specified as inline.
8064 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8066 // Suppress the diagnostic if the function is __attribute__((used)), since
8067 // that forces an external definition to be emitted.
8068 if (D.getDeclSpec().isInlineSpecified() &&
8069 NewFD->isReplaceableGlobalAllocationFunction() &&
8070 !NewFD->hasAttr<UsedAttr>())
8071 Diag(D.getDeclSpec().getInlineSpecLoc(),
8072 diag::ext_operator_new_delete_declared_inline)
8073 << NewFD->getDeclName();
8075 // If the declarator is a template-id, translate the parser's template
8076 // argument list into our AST format.
8077 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8078 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8079 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8080 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8081 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8082 TemplateId->NumArgs);
8083 translateTemplateArguments(TemplateArgsPtr,
8086 HasExplicitTemplateArgs = true;
8088 if (NewFD->isInvalidDecl()) {
8089 HasExplicitTemplateArgs = false;
8090 } else if (FunctionTemplate) {
8091 // Function template with explicit template arguments.
8092 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8093 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8095 HasExplicitTemplateArgs = false;
8097 assert((isFunctionTemplateSpecialization ||
8098 D.getDeclSpec().isFriendSpecified()) &&
8099 "should have a 'template<>' for this decl");
8100 // "friend void foo<>(int);" is an implicit specialization decl.
8101 isFunctionTemplateSpecialization = true;
8103 } else if (isFriend && isFunctionTemplateSpecialization) {
8104 // This combination is only possible in a recovery case; the user
8105 // wrote something like:
8106 // template <> friend void foo(int);
8107 // which we're recovering from as if the user had written:
8108 // friend void foo<>(int);
8109 // Go ahead and fake up a template id.
8110 HasExplicitTemplateArgs = true;
8111 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8112 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8115 // If it's a friend (and only if it's a friend), it's possible
8116 // that either the specialized function type or the specialized
8117 // template is dependent, and therefore matching will fail. In
8118 // this case, don't check the specialization yet.
8119 bool InstantiationDependent = false;
8120 if (isFunctionTemplateSpecialization && isFriend &&
8121 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8122 TemplateSpecializationType::anyDependentTemplateArguments(
8123 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8124 InstantiationDependent))) {
8125 assert(HasExplicitTemplateArgs &&
8126 "friend function specialization without template args");
8127 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8129 NewFD->setInvalidDecl();
8130 } else if (isFunctionTemplateSpecialization) {
8131 if (CurContext->isDependentContext() && CurContext->isRecord()
8133 isDependentClassScopeExplicitSpecialization = true;
8134 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8135 diag::ext_function_specialization_in_class :
8136 diag::err_function_specialization_in_class)
8137 << NewFD->getDeclName();
8138 } else if (CheckFunctionTemplateSpecialization(NewFD,
8139 (HasExplicitTemplateArgs ? &TemplateArgs
8142 NewFD->setInvalidDecl();
8145 // A storage-class-specifier shall not be specified in an explicit
8146 // specialization (14.7.3)
8147 FunctionTemplateSpecializationInfo *Info =
8148 NewFD->getTemplateSpecializationInfo();
8149 if (Info && SC != SC_None) {
8150 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8151 Diag(NewFD->getLocation(),
8152 diag::err_explicit_specialization_inconsistent_storage_class)
8154 << FixItHint::CreateRemoval(
8155 D.getDeclSpec().getStorageClassSpecLoc());
8158 Diag(NewFD->getLocation(),
8159 diag::ext_explicit_specialization_storage_class)
8160 << FixItHint::CreateRemoval(
8161 D.getDeclSpec().getStorageClassSpecLoc());
8163 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8164 if (CheckMemberSpecialization(NewFD, Previous))
8165 NewFD->setInvalidDecl();
8168 // Perform semantic checking on the function declaration.
8169 if (!isDependentClassScopeExplicitSpecialization) {
8170 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8171 CheckMain(NewFD, D.getDeclSpec());
8173 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8174 CheckMSVCRTEntryPoint(NewFD);
8176 if (!NewFD->isInvalidDecl())
8177 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8178 isExplicitSpecialization));
8179 else if (!Previous.empty())
8180 // Recover gracefully from an invalid redeclaration.
8181 D.setRedeclaration(true);
8184 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8185 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8186 "previous declaration set still overloaded");
8188 NamedDecl *PrincipalDecl = (FunctionTemplate
8189 ? cast<NamedDecl>(FunctionTemplate)
8192 if (isFriend && D.isRedeclaration()) {
8193 AccessSpecifier Access = AS_public;
8194 if (!NewFD->isInvalidDecl())
8195 Access = NewFD->getPreviousDecl()->getAccess();
8197 NewFD->setAccess(Access);
8198 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8201 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8202 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8203 PrincipalDecl->setNonMemberOperator();
8205 // If we have a function template, check the template parameter
8206 // list. This will check and merge default template arguments.
8207 if (FunctionTemplate) {
8208 FunctionTemplateDecl *PrevTemplate =
8209 FunctionTemplate->getPreviousDecl();
8210 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8211 PrevTemplate ? PrevTemplate->getTemplateParameters()
8213 D.getDeclSpec().isFriendSpecified()
8214 ? (D.isFunctionDefinition()
8215 ? TPC_FriendFunctionTemplateDefinition
8216 : TPC_FriendFunctionTemplate)
8217 : (D.getCXXScopeSpec().isSet() &&
8218 DC && DC->isRecord() &&
8219 DC->isDependentContext())
8220 ? TPC_ClassTemplateMember
8221 : TPC_FunctionTemplate);
8224 if (NewFD->isInvalidDecl()) {
8225 // Ignore all the rest of this.
8226 } else if (!D.isRedeclaration()) {
8227 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8229 // Fake up an access specifier if it's supposed to be a class member.
8230 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8231 NewFD->setAccess(AS_public);
8233 // Qualified decls generally require a previous declaration.
8234 if (D.getCXXScopeSpec().isSet()) {
8235 // ...with the major exception of templated-scope or
8236 // dependent-scope friend declarations.
8238 // TODO: we currently also suppress this check in dependent
8239 // contexts because (1) the parameter depth will be off when
8240 // matching friend templates and (2) we might actually be
8241 // selecting a friend based on a dependent factor. But there
8242 // are situations where these conditions don't apply and we
8243 // can actually do this check immediately.
8245 (TemplateParamLists.size() ||
8246 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8247 CurContext->isDependentContext())) {
8250 // The user tried to provide an out-of-line definition for a
8251 // function that is a member of a class or namespace, but there
8252 // was no such member function declared (C++ [class.mfct]p2,
8253 // C++ [namespace.memdef]p2). For example:
8259 // void X::f() { } // ill-formed
8261 // Complain about this problem, and attempt to suggest close
8262 // matches (e.g., those that differ only in cv-qualifiers and
8263 // whether the parameter types are references).
8265 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8266 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8267 AddToScope = ExtraArgs.AddToScope;
8272 // Unqualified local friend declarations are required to resolve
8274 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8275 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8276 *this, Previous, NewFD, ExtraArgs, true, S)) {
8277 AddToScope = ExtraArgs.AddToScope;
8281 } else if (!D.isFunctionDefinition() &&
8282 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8283 !isFriend && !isFunctionTemplateSpecialization &&
8284 !isExplicitSpecialization) {
8285 // An out-of-line member function declaration must also be a
8286 // definition (C++ [class.mfct]p2).
8287 // Note that this is not the case for explicit specializations of
8288 // function templates or member functions of class templates, per
8289 // C++ [temp.expl.spec]p2. We also allow these declarations as an
8290 // extension for compatibility with old SWIG code which likes to
8292 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8293 << D.getCXXScopeSpec().getRange();
8297 ProcessPragmaWeak(S, NewFD);
8298 checkAttributesAfterMerging(*this, *NewFD);
8300 AddKnownFunctionAttributes(NewFD);
8302 if (NewFD->hasAttr<OverloadableAttr>() &&
8303 !NewFD->getType()->getAs<FunctionProtoType>()) {
8304 Diag(NewFD->getLocation(),
8305 diag::err_attribute_overloadable_no_prototype)
8308 // Turn this into a variadic function with no parameters.
8309 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8310 FunctionProtoType::ExtProtoInfo EPI(
8311 Context.getDefaultCallingConvention(true, false));
8312 EPI.Variadic = true;
8313 EPI.ExtInfo = FT->getExtInfo();
8315 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8319 // If there's a #pragma GCC visibility in scope, and this isn't a class
8320 // member, set the visibility of this function.
8321 if (!DC->isRecord() && NewFD->isExternallyVisible())
8322 AddPushedVisibilityAttribute(NewFD);
8324 // If there's a #pragma clang arc_cf_code_audited in scope, consider
8325 // marking the function.
8326 AddCFAuditedAttribute(NewFD);
8328 // If this is a function definition, check if we have to apply optnone due to
8330 if(D.isFunctionDefinition())
8331 AddRangeBasedOptnone(NewFD);
8333 // If this is the first declaration of an extern C variable, update
8334 // the map of such variables.
8335 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8336 isIncompleteDeclExternC(*this, NewFD))
8337 RegisterLocallyScopedExternCDecl(NewFD, S);
8339 // Set this FunctionDecl's range up to the right paren.
8340 NewFD->setRangeEnd(D.getSourceRange().getEnd());
8342 if (D.isRedeclaration() && !Previous.empty()) {
8343 checkDLLAttributeRedeclaration(
8344 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8345 isExplicitSpecialization || isFunctionTemplateSpecialization);
8348 if (getLangOpts().CUDA) {
8349 IdentifierInfo *II = NewFD->getIdentifier();
8350 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8351 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8352 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8353 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8355 Context.setcudaConfigureCallDecl(NewFD);
8358 // Variadic functions, other than a *declaration* of printf, are not allowed
8359 // in device-side CUDA code, unless someone passed
8360 // -fcuda-allow-variadic-functions.
8361 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8362 (NewFD->hasAttr<CUDADeviceAttr>() ||
8363 NewFD->hasAttr<CUDAGlobalAttr>()) &&
8364 !(II && II->isStr("printf") && NewFD->isExternC() &&
8365 !D.isFunctionDefinition())) {
8366 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8370 if (getLangOpts().CPlusPlus) {
8371 if (FunctionTemplate) {
8372 if (NewFD->isInvalidDecl())
8373 FunctionTemplate->setInvalidDecl();
8374 return FunctionTemplate;
8378 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8379 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8380 if ((getLangOpts().OpenCLVersion >= 120)
8381 && (SC == SC_Static)) {
8382 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8386 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8387 if (!NewFD->getReturnType()->isVoidType()) {
8388 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8389 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8390 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8395 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8396 for (auto Param : NewFD->params())
8397 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8399 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
8400 PE = NewFD->param_end(); PI != PE; ++PI) {
8401 ParmVarDecl *Param = *PI;
8402 QualType PT = Param->getType();
8404 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8406 if (getLangOpts().OpenCLVersion >= 200) {
8407 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8408 QualType ElemTy = PipeTy->getElementType();
8409 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8410 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8417 MarkUnusedFileScopedDecl(NewFD);
8419 // Here we have an function template explicit specialization at class scope.
8420 // The actually specialization will be postponed to template instatiation
8421 // time via the ClassScopeFunctionSpecializationDecl node.
8422 if (isDependentClassScopeExplicitSpecialization) {
8423 ClassScopeFunctionSpecializationDecl *NewSpec =
8424 ClassScopeFunctionSpecializationDecl::Create(
8425 Context, CurContext, SourceLocation(),
8426 cast<CXXMethodDecl>(NewFD),
8427 HasExplicitTemplateArgs, TemplateArgs);
8428 CurContext->addDecl(NewSpec);
8435 /// \brief Perform semantic checking of a new function declaration.
8437 /// Performs semantic analysis of the new function declaration
8438 /// NewFD. This routine performs all semantic checking that does not
8439 /// require the actual declarator involved in the declaration, and is
8440 /// used both for the declaration of functions as they are parsed
8441 /// (called via ActOnDeclarator) and for the declaration of functions
8442 /// that have been instantiated via C++ template instantiation (called
8443 /// via InstantiateDecl).
8445 /// \param IsExplicitSpecialization whether this new function declaration is
8446 /// an explicit specialization of the previous declaration.
8448 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8450 /// \returns true if the function declaration is a redeclaration.
8451 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8452 LookupResult &Previous,
8453 bool IsExplicitSpecialization) {
8454 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8455 "Variably modified return types are not handled here");
8457 // Determine whether the type of this function should be merged with
8458 // a previous visible declaration. This never happens for functions in C++,
8459 // and always happens in C if the previous declaration was visible.
8460 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8461 !Previous.isShadowed();
8463 bool Redeclaration = false;
8464 NamedDecl *OldDecl = nullptr;
8466 // Merge or overload the declaration with an existing declaration of
8467 // the same name, if appropriate.
8468 if (!Previous.empty()) {
8469 // Determine whether NewFD is an overload of PrevDecl or
8470 // a declaration that requires merging. If it's an overload,
8471 // there's no more work to do here; we'll just add the new
8472 // function to the scope.
8473 if (!AllowOverloadingOfFunction(Previous, Context)) {
8474 NamedDecl *Candidate = Previous.getRepresentativeDecl();
8475 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8476 Redeclaration = true;
8477 OldDecl = Candidate;
8480 switch (CheckOverload(S, NewFD, Previous, OldDecl,
8481 /*NewIsUsingDecl*/ false)) {
8483 Redeclaration = true;
8486 case Ovl_NonFunction:
8487 Redeclaration = true;
8491 Redeclaration = false;
8495 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8496 // If a function name is overloadable in C, then every function
8497 // with that name must be marked "overloadable".
8498 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8499 << Redeclaration << NewFD;
8500 NamedDecl *OverloadedDecl = nullptr;
8502 OverloadedDecl = OldDecl;
8503 else if (!Previous.empty())
8504 OverloadedDecl = Previous.getRepresentativeDecl();
8506 Diag(OverloadedDecl->getLocation(),
8507 diag::note_attribute_overloadable_prev_overload);
8508 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8513 // Check for a previous extern "C" declaration with this name.
8514 if (!Redeclaration &&
8515 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8516 if (!Previous.empty()) {
8517 // This is an extern "C" declaration with the same name as a previous
8518 // declaration, and thus redeclares that entity...
8519 Redeclaration = true;
8520 OldDecl = Previous.getFoundDecl();
8521 MergeTypeWithPrevious = false;
8523 // ... except in the presence of __attribute__((overloadable)).
8524 if (OldDecl->hasAttr<OverloadableAttr>()) {
8525 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8526 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8527 << Redeclaration << NewFD;
8528 Diag(Previous.getFoundDecl()->getLocation(),
8529 diag::note_attribute_overloadable_prev_overload);
8530 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8532 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8533 Redeclaration = false;
8540 // C++11 [dcl.constexpr]p8:
8541 // A constexpr specifier for a non-static member function that is not
8542 // a constructor declares that member function to be const.
8544 // This needs to be delayed until we know whether this is an out-of-line
8545 // definition of a static member function.
8547 // This rule is not present in C++1y, so we produce a backwards
8548 // compatibility warning whenever it happens in C++11.
8549 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8550 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8551 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8552 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8553 CXXMethodDecl *OldMD = nullptr;
8555 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8556 if (!OldMD || !OldMD->isStatic()) {
8557 const FunctionProtoType *FPT =
8558 MD->getType()->castAs<FunctionProtoType>();
8559 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8560 EPI.TypeQuals |= Qualifiers::Const;
8561 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8562 FPT->getParamTypes(), EPI));
8564 // Warn that we did this, if we're not performing template instantiation.
8565 // In that case, we'll have warned already when the template was defined.
8566 if (ActiveTemplateInstantiations.empty()) {
8567 SourceLocation AddConstLoc;
8568 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8569 .IgnoreParens().getAs<FunctionTypeLoc>())
8570 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8572 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8573 << FixItHint::CreateInsertion(AddConstLoc, " const");
8578 if (Redeclaration) {
8579 // NewFD and OldDecl represent declarations that need to be
8581 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8582 NewFD->setInvalidDecl();
8583 return Redeclaration;
8587 Previous.addDecl(OldDecl);
8589 if (FunctionTemplateDecl *OldTemplateDecl
8590 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8591 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8592 FunctionTemplateDecl *NewTemplateDecl
8593 = NewFD->getDescribedFunctionTemplate();
8594 assert(NewTemplateDecl && "Template/non-template mismatch");
8595 if (CXXMethodDecl *Method
8596 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8597 Method->setAccess(OldTemplateDecl->getAccess());
8598 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8601 // If this is an explicit specialization of a member that is a function
8602 // template, mark it as a member specialization.
8603 if (IsExplicitSpecialization &&
8604 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8605 NewTemplateDecl->setMemberSpecialization();
8606 assert(OldTemplateDecl->isMemberSpecialization());
8610 // This needs to happen first so that 'inline' propagates.
8611 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8613 if (isa<CXXMethodDecl>(NewFD))
8614 NewFD->setAccess(OldDecl->getAccess());
8618 // Semantic checking for this function declaration (in isolation).
8620 if (getLangOpts().CPlusPlus) {
8621 // C++-specific checks.
8622 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8623 CheckConstructor(Constructor);
8624 } else if (CXXDestructorDecl *Destructor =
8625 dyn_cast<CXXDestructorDecl>(NewFD)) {
8626 CXXRecordDecl *Record = Destructor->getParent();
8627 QualType ClassType = Context.getTypeDeclType(Record);
8629 // FIXME: Shouldn't we be able to perform this check even when the class
8630 // type is dependent? Both gcc and edg can handle that.
8631 if (!ClassType->isDependentType()) {
8632 DeclarationName Name
8633 = Context.DeclarationNames.getCXXDestructorName(
8634 Context.getCanonicalType(ClassType));
8635 if (NewFD->getDeclName() != Name) {
8636 Diag(NewFD->getLocation(), diag::err_destructor_name);
8637 NewFD->setInvalidDecl();
8638 return Redeclaration;
8641 } else if (CXXConversionDecl *Conversion
8642 = dyn_cast<CXXConversionDecl>(NewFD)) {
8643 ActOnConversionDeclarator(Conversion);
8646 // Find any virtual functions that this function overrides.
8647 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8648 if (!Method->isFunctionTemplateSpecialization() &&
8649 !Method->getDescribedFunctionTemplate() &&
8650 Method->isCanonicalDecl()) {
8651 if (AddOverriddenMethods(Method->getParent(), Method)) {
8652 // If the function was marked as "static", we have a problem.
8653 if (NewFD->getStorageClass() == SC_Static) {
8654 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8659 if (Method->isStatic())
8660 checkThisInStaticMemberFunctionType(Method);
8663 // Extra checking for C++ overloaded operators (C++ [over.oper]).
8664 if (NewFD->isOverloadedOperator() &&
8665 CheckOverloadedOperatorDeclaration(NewFD)) {
8666 NewFD->setInvalidDecl();
8667 return Redeclaration;
8670 // Extra checking for C++0x literal operators (C++0x [over.literal]).
8671 if (NewFD->getLiteralIdentifier() &&
8672 CheckLiteralOperatorDeclaration(NewFD)) {
8673 NewFD->setInvalidDecl();
8674 return Redeclaration;
8677 // In C++, check default arguments now that we have merged decls. Unless
8678 // the lexical context is the class, because in this case this is done
8679 // during delayed parsing anyway.
8680 if (!CurContext->isRecord())
8681 CheckCXXDefaultArguments(NewFD);
8683 // If this function declares a builtin function, check the type of this
8684 // declaration against the expected type for the builtin.
8685 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8686 ASTContext::GetBuiltinTypeError Error;
8687 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8688 QualType T = Context.GetBuiltinType(BuiltinID, Error);
8689 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8690 // The type of this function differs from the type of the builtin,
8691 // so forget about the builtin entirely.
8692 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8696 // If this function is declared as being extern "C", then check to see if
8697 // the function returns a UDT (class, struct, or union type) that is not C
8698 // compatible, and if it does, warn the user.
8699 // But, issue any diagnostic on the first declaration only.
8700 if (Previous.empty() && NewFD->isExternC()) {
8701 QualType R = NewFD->getReturnType();
8702 if (R->isIncompleteType() && !R->isVoidType())
8703 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8705 else if (!R.isPODType(Context) && !R->isVoidType() &&
8706 !R->isObjCObjectPointerType())
8707 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8710 return Redeclaration;
8713 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8714 // C++11 [basic.start.main]p3:
8715 // A program that [...] declares main to be inline, static or
8716 // constexpr is ill-formed.
8717 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
8718 // appear in a declaration of main.
8719 // static main is not an error under C99, but we should warn about it.
8720 // We accept _Noreturn main as an extension.
8721 if (FD->getStorageClass() == SC_Static)
8722 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8723 ? diag::err_static_main : diag::warn_static_main)
8724 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8725 if (FD->isInlineSpecified())
8726 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8727 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8728 if (DS.isNoreturnSpecified()) {
8729 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8730 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8731 Diag(NoreturnLoc, diag::ext_noreturn_main);
8732 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8733 << FixItHint::CreateRemoval(NoreturnRange);
8735 if (FD->isConstexpr()) {
8736 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8737 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8738 FD->setConstexpr(false);
8741 if (getLangOpts().OpenCL) {
8742 Diag(FD->getLocation(), diag::err_opencl_no_main)
8743 << FD->hasAttr<OpenCLKernelAttr>();
8744 FD->setInvalidDecl();
8748 QualType T = FD->getType();
8749 assert(T->isFunctionType() && "function decl is not of function type");
8750 const FunctionType* FT = T->castAs<FunctionType>();
8752 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8753 // In C with GNU extensions we allow main() to have non-integer return
8754 // type, but we should warn about the extension, and we disable the
8755 // implicit-return-zero rule.
8757 // GCC in C mode accepts qualified 'int'.
8758 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8759 FD->setHasImplicitReturnZero(true);
8761 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8762 SourceRange RTRange = FD->getReturnTypeSourceRange();
8763 if (RTRange.isValid())
8764 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8765 << FixItHint::CreateReplacement(RTRange, "int");
8768 // In C and C++, main magically returns 0 if you fall off the end;
8769 // set the flag which tells us that.
8770 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8772 // All the standards say that main() should return 'int'.
8773 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8774 FD->setHasImplicitReturnZero(true);
8776 // Otherwise, this is just a flat-out error.
8777 SourceRange RTRange = FD->getReturnTypeSourceRange();
8778 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8779 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8781 FD->setInvalidDecl(true);
8785 // Treat protoless main() as nullary.
8786 if (isa<FunctionNoProtoType>(FT)) return;
8788 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8789 unsigned nparams = FTP->getNumParams();
8790 assert(FD->getNumParams() == nparams);
8792 bool HasExtraParameters = (nparams > 3);
8794 if (FTP->isVariadic()) {
8795 Diag(FD->getLocation(), diag::ext_variadic_main);
8796 // FIXME: if we had information about the location of the ellipsis, we
8797 // could add a FixIt hint to remove it as a parameter.
8800 // Darwin passes an undocumented fourth argument of type char**. If
8801 // other platforms start sprouting these, the logic below will start
8803 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8804 HasExtraParameters = false;
8806 if (HasExtraParameters) {
8807 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8808 FD->setInvalidDecl(true);
8812 // FIXME: a lot of the following diagnostics would be improved
8813 // if we had some location information about types.
8816 Context.getPointerType(Context.getPointerType(Context.CharTy));
8817 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8819 for (unsigned i = 0; i < nparams; ++i) {
8820 QualType AT = FTP->getParamType(i);
8822 bool mismatch = true;
8824 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8826 else if (Expected[i] == CharPP) {
8827 // As an extension, the following forms are okay:
8829 // char const * const *
8832 QualifierCollector qs;
8833 const PointerType* PT;
8834 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8835 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8836 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8839 mismatch = !qs.empty();
8844 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8845 // TODO: suggest replacing given type with expected type
8846 FD->setInvalidDecl(true);
8850 if (nparams == 1 && !FD->isInvalidDecl()) {
8851 Diag(FD->getLocation(), diag::warn_main_one_arg);
8854 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8855 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8856 FD->setInvalidDecl();
8860 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8861 QualType T = FD->getType();
8862 assert(T->isFunctionType() && "function decl is not of function type");
8863 const FunctionType *FT = T->castAs<FunctionType>();
8865 // Set an implicit return of 'zero' if the function can return some integral,
8866 // enumeration, pointer or nullptr type.
8867 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8868 FT->getReturnType()->isAnyPointerType() ||
8869 FT->getReturnType()->isNullPtrType())
8870 // DllMain is exempt because a return value of zero means it failed.
8871 if (FD->getName() != "DllMain")
8872 FD->setHasImplicitReturnZero(true);
8874 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8875 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8876 FD->setInvalidDecl();
8880 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8881 // FIXME: Need strict checking. In C89, we need to check for
8882 // any assignment, increment, decrement, function-calls, or
8883 // commas outside of a sizeof. In C99, it's the same list,
8884 // except that the aforementioned are allowed in unevaluated
8885 // expressions. Everything else falls under the
8886 // "may accept other forms of constant expressions" exception.
8887 // (We never end up here for C++, so the constant expression
8888 // rules there don't matter.)
8889 const Expr *Culprit;
8890 if (Init->isConstantInitializer(Context, false, &Culprit))
8892 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8893 << Culprit->getSourceRange();
8898 // Visits an initialization expression to see if OrigDecl is evaluated in
8899 // its own initialization and throws a warning if it does.
8900 class SelfReferenceChecker
8901 : public EvaluatedExprVisitor<SelfReferenceChecker> {
8906 bool isReferenceType;
8909 llvm::SmallVector<unsigned, 4> InitFieldIndex;
8912 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8914 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8915 S(S), OrigDecl(OrigDecl) {
8917 isRecordType = false;
8918 isReferenceType = false;
8920 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8921 isPODType = VD->getType().isPODType(S.Context);
8922 isRecordType = VD->getType()->isRecordType();
8923 isReferenceType = VD->getType()->isReferenceType();
8927 // For most expressions, just call the visitor. For initializer lists,
8928 // track the index of the field being initialized since fields are
8929 // initialized in order allowing use of previously initialized fields.
8930 void CheckExpr(Expr *E) {
8931 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8937 // Track and increment the index here.
8939 InitFieldIndex.push_back(0);
8940 for (auto Child : InitList->children()) {
8941 CheckExpr(cast<Expr>(Child));
8942 ++InitFieldIndex.back();
8944 InitFieldIndex.pop_back();
8947 // Returns true if MemberExpr is checked and no futher checking is needed.
8948 // Returns false if additional checking is required.
8949 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8950 llvm::SmallVector<FieldDecl*, 4> Fields;
8952 bool ReferenceField = false;
8954 // Get the field memebers used.
8955 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8956 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8959 Fields.push_back(FD);
8960 if (FD->getType()->isReferenceType())
8961 ReferenceField = true;
8962 Base = ME->getBase()->IgnoreParenImpCasts();
8965 // Keep checking only if the base Decl is the same.
8966 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8967 if (!DRE || DRE->getDecl() != OrigDecl)
8970 // A reference field can be bound to an unininitialized field.
8971 if (CheckReference && !ReferenceField)
8974 // Convert FieldDecls to their index number.
8975 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8976 for (const FieldDecl *I : llvm::reverse(Fields))
8977 UsedFieldIndex.push_back(I->getFieldIndex());
8979 // See if a warning is needed by checking the first difference in index
8980 // numbers. If field being used has index less than the field being
8981 // initialized, then the use is safe.
8982 for (auto UsedIter = UsedFieldIndex.begin(),
8983 UsedEnd = UsedFieldIndex.end(),
8984 OrigIter = InitFieldIndex.begin(),
8985 OrigEnd = InitFieldIndex.end();
8986 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8987 if (*UsedIter < *OrigIter)
8989 if (*UsedIter > *OrigIter)
8993 // TODO: Add a different warning which will print the field names.
8994 HandleDeclRefExpr(DRE);
8998 // For most expressions, the cast is directly above the DeclRefExpr.
8999 // For conditional operators, the cast can be outside the conditional
9000 // operator if both expressions are DeclRefExpr's.
9001 void HandleValue(Expr *E) {
9002 E = E->IgnoreParens();
9003 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9004 HandleDeclRefExpr(DRE);
9008 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9009 Visit(CO->getCond());
9010 HandleValue(CO->getTrueExpr());
9011 HandleValue(CO->getFalseExpr());
9015 if (BinaryConditionalOperator *BCO =
9016 dyn_cast<BinaryConditionalOperator>(E)) {
9017 Visit(BCO->getCond());
9018 HandleValue(BCO->getFalseExpr());
9022 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9023 HandleValue(OVE->getSourceExpr());
9027 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9028 if (BO->getOpcode() == BO_Comma) {
9029 Visit(BO->getLHS());
9030 HandleValue(BO->getRHS());
9035 if (isa<MemberExpr>(E)) {
9037 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9038 false /*CheckReference*/))
9042 Expr *Base = E->IgnoreParenImpCasts();
9043 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9044 // Check for static member variables and don't warn on them.
9045 if (!isa<FieldDecl>(ME->getMemberDecl()))
9047 Base = ME->getBase()->IgnoreParenImpCasts();
9049 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9050 HandleDeclRefExpr(DRE);
9057 // Reference types not handled in HandleValue are handled here since all
9058 // uses of references are bad, not just r-value uses.
9059 void VisitDeclRefExpr(DeclRefExpr *E) {
9060 if (isReferenceType)
9061 HandleDeclRefExpr(E);
9064 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9065 if (E->getCastKind() == CK_LValueToRValue) {
9066 HandleValue(E->getSubExpr());
9070 Inherited::VisitImplicitCastExpr(E);
9073 void VisitMemberExpr(MemberExpr *E) {
9075 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9079 // Don't warn on arrays since they can be treated as pointers.
9080 if (E->getType()->canDecayToPointerType()) return;
9082 // Warn when a non-static method call is followed by non-static member
9083 // field accesses, which is followed by a DeclRefExpr.
9084 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9085 bool Warn = (MD && !MD->isStatic());
9086 Expr *Base = E->getBase()->IgnoreParenImpCasts();
9087 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9088 if (!isa<FieldDecl>(ME->getMemberDecl()))
9090 Base = ME->getBase()->IgnoreParenImpCasts();
9093 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9095 HandleDeclRefExpr(DRE);
9099 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9100 // Visit that expression.
9104 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9105 Expr *Callee = E->getCallee();
9107 if (isa<UnresolvedLookupExpr>(Callee))
9108 return Inherited::VisitCXXOperatorCallExpr(E);
9111 for (auto Arg: E->arguments())
9112 HandleValue(Arg->IgnoreParenImpCasts());
9115 void VisitUnaryOperator(UnaryOperator *E) {
9116 // For POD record types, addresses of its own members are well-defined.
9117 if (E->getOpcode() == UO_AddrOf && isRecordType &&
9118 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9120 HandleValue(E->getSubExpr());
9124 if (E->isIncrementDecrementOp()) {
9125 HandleValue(E->getSubExpr());
9129 Inherited::VisitUnaryOperator(E);
9132 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9134 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9135 if (E->getConstructor()->isCopyConstructor()) {
9136 Expr *ArgExpr = E->getArg(0);
9137 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9138 if (ILE->getNumInits() == 1)
9139 ArgExpr = ILE->getInit(0);
9140 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9141 if (ICE->getCastKind() == CK_NoOp)
9142 ArgExpr = ICE->getSubExpr();
9143 HandleValue(ArgExpr);
9146 Inherited::VisitCXXConstructExpr(E);
9149 void VisitCallExpr(CallExpr *E) {
9150 // Treat std::move as a use.
9151 if (E->getNumArgs() == 1) {
9152 if (FunctionDecl *FD = E->getDirectCallee()) {
9153 if (FD->isInStdNamespace() && FD->getIdentifier() &&
9154 FD->getIdentifier()->isStr("move")) {
9155 HandleValue(E->getArg(0));
9161 Inherited::VisitCallExpr(E);
9164 void VisitBinaryOperator(BinaryOperator *E) {
9165 if (E->isCompoundAssignmentOp()) {
9166 HandleValue(E->getLHS());
9171 Inherited::VisitBinaryOperator(E);
9174 // A custom visitor for BinaryConditionalOperator is needed because the
9175 // regular visitor would check the condition and true expression separately
9176 // but both point to the same place giving duplicate diagnostics.
9177 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9178 Visit(E->getCond());
9179 Visit(E->getFalseExpr());
9182 void HandleDeclRefExpr(DeclRefExpr *DRE) {
9183 Decl* ReferenceDecl = DRE->getDecl();
9184 if (OrigDecl != ReferenceDecl) return;
9186 if (isReferenceType) {
9187 diag = diag::warn_uninit_self_reference_in_reference_init;
9188 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9189 diag = diag::warn_static_self_reference_in_init;
9190 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9191 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9192 DRE->getDecl()->getType()->isRecordType()) {
9193 diag = diag::warn_uninit_self_reference_in_init;
9195 // Local variables will be handled by the CFG analysis.
9199 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9201 << DRE->getNameInfo().getName()
9202 << OrigDecl->getLocation()
9203 << DRE->getSourceRange());
9207 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9208 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9210 // Parameters arguments are occassionially constructed with itself,
9211 // for instance, in recursive functions. Skip them.
9212 if (isa<ParmVarDecl>(OrigDecl))
9215 E = E->IgnoreParens();
9217 // Skip checking T a = a where T is not a record or reference type.
9218 // Doing so is a way to silence uninitialized warnings.
9219 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9220 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9221 if (ICE->getCastKind() == CK_LValueToRValue)
9222 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9223 if (DRE->getDecl() == OrigDecl)
9226 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9228 } // end anonymous namespace
9230 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9231 DeclarationName Name, QualType Type,
9232 TypeSourceInfo *TSI,
9233 SourceRange Range, bool DirectInit,
9235 bool IsInitCapture = !VDecl;
9236 assert((!VDecl || !VDecl->isInitCapture()) &&
9237 "init captures are expected to be deduced prior to initialization");
9239 ArrayRef<Expr *> DeduceInits = Init;
9241 if (auto *PL = dyn_cast<ParenListExpr>(Init))
9242 DeduceInits = PL->exprs();
9243 else if (auto *IL = dyn_cast<InitListExpr>(Init))
9244 DeduceInits = IL->inits();
9247 // Deduction only works if we have exactly one source expression.
9248 if (DeduceInits.empty()) {
9249 // It isn't possible to write this directly, but it is possible to
9250 // end up in this situation with "auto x(some_pack...);"
9251 Diag(Init->getLocStart(), IsInitCapture
9252 ? diag::err_init_capture_no_expression
9253 : diag::err_auto_var_init_no_expression)
9254 << Name << Type << Range;
9258 if (DeduceInits.size() > 1) {
9259 Diag(DeduceInits[1]->getLocStart(),
9260 IsInitCapture ? diag::err_init_capture_multiple_expressions
9261 : diag::err_auto_var_init_multiple_expressions)
9262 << Name << Type << Range;
9266 Expr *DeduceInit = DeduceInits[0];
9267 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9268 Diag(Init->getLocStart(), IsInitCapture
9269 ? diag::err_init_capture_paren_braces
9270 : diag::err_auto_var_init_paren_braces)
9271 << isa<InitListExpr>(Init) << Name << Type << Range;
9275 // Expressions default to 'id' when we're in a debugger.
9276 bool DefaultedAnyToId = false;
9277 if (getLangOpts().DebuggerCastResultToId &&
9278 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9279 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9280 if (Result.isInvalid()) {
9283 Init = Result.get();
9284 DefaultedAnyToId = true;
9287 QualType DeducedType;
9288 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9290 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9291 else if (isa<InitListExpr>(Init))
9292 Diag(Range.getBegin(),
9293 diag::err_init_capture_deduction_failure_from_init_list)
9295 << (DeduceInit->getType().isNull() ? TSI->getType()
9296 : DeduceInit->getType())
9297 << DeduceInit->getSourceRange();
9299 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9300 << Name << TSI->getType()
9301 << (DeduceInit->getType().isNull() ? TSI->getType()
9302 : DeduceInit->getType())
9303 << DeduceInit->getSourceRange();
9306 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9307 // 'id' instead of a specific object type prevents most of our usual
9309 // We only want to warn outside of template instantiations, though:
9310 // inside a template, the 'id' could have come from a parameter.
9311 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9312 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9313 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9314 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9320 /// AddInitializerToDecl - Adds the initializer Init to the
9321 /// declaration dcl. If DirectInit is true, this is C++ direct
9322 /// initialization rather than copy initialization.
9323 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9324 bool DirectInit, bool TypeMayContainAuto) {
9325 // If there is no declaration, there was an error parsing it. Just ignore
9327 if (!RealDecl || RealDecl->isInvalidDecl()) {
9328 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9332 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9333 // Pure-specifiers are handled in ActOnPureSpecifier.
9334 Diag(Method->getLocation(), diag::err_member_function_initialization)
9335 << Method->getDeclName() << Init->getSourceRange();
9336 Method->setInvalidDecl();
9340 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9342 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9343 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9344 RealDecl->setInvalidDecl();
9348 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9349 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9350 // Attempt typo correction early so that the type of the init expression can
9351 // be deduced based on the chosen correction if the original init contains a
9353 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9354 if (!Res.isUsable()) {
9355 RealDecl->setInvalidDecl();
9360 QualType DeducedType = deduceVarTypeFromInitializer(
9361 VDecl, VDecl->getDeclName(), VDecl->getType(),
9362 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9363 if (DeducedType.isNull()) {
9364 RealDecl->setInvalidDecl();
9368 VDecl->setType(DeducedType);
9369 assert(VDecl->isLinkageValid());
9371 // In ARC, infer lifetime.
9372 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9373 VDecl->setInvalidDecl();
9375 // If this is a redeclaration, check that the type we just deduced matches
9376 // the previously declared type.
9377 if (VarDecl *Old = VDecl->getPreviousDecl()) {
9378 // We never need to merge the type, because we cannot form an incomplete
9379 // array of auto, nor deduce such a type.
9380 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9383 // Check the deduced type is valid for a variable declaration.
9384 CheckVariableDeclarationType(VDecl);
9385 if (VDecl->isInvalidDecl())
9389 // dllimport cannot be used on variable definitions.
9390 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9391 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9392 VDecl->setInvalidDecl();
9396 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9397 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9398 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9399 VDecl->setInvalidDecl();
9403 if (!VDecl->getType()->isDependentType()) {
9404 // A definition must end up with a complete type, which means it must be
9405 // complete with the restriction that an array type might be completed by
9406 // the initializer; note that later code assumes this restriction.
9407 QualType BaseDeclType = VDecl->getType();
9408 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9409 BaseDeclType = Array->getElementType();
9410 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9411 diag::err_typecheck_decl_incomplete_type)) {
9412 RealDecl->setInvalidDecl();
9416 // The variable can not have an abstract class type.
9417 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9418 diag::err_abstract_type_in_decl,
9419 AbstractVariableType))
9420 VDecl->setInvalidDecl();
9424 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9425 NamedDecl *Hidden = nullptr;
9426 if (!hasVisibleDefinition(Def, &Hidden) &&
9427 (VDecl->getFormalLinkage() == InternalLinkage ||
9428 VDecl->getDescribedVarTemplate() ||
9429 VDecl->getNumTemplateParameterLists() ||
9430 VDecl->getDeclContext()->isDependentContext())) {
9431 // The previous definition is hidden, and multiple definitions are
9432 // permitted (in separate TUs). Form another definition of it.
9434 Diag(VDecl->getLocation(), diag::err_redefinition)
9435 << VDecl->getDeclName();
9436 Diag(Def->getLocation(), diag::note_previous_definition);
9437 VDecl->setInvalidDecl();
9442 if (getLangOpts().CPlusPlus) {
9443 // C++ [class.static.data]p4
9444 // If a static data member is of const integral or const
9445 // enumeration type, its declaration in the class definition can
9446 // specify a constant-initializer which shall be an integral
9447 // constant expression (5.19). In that case, the member can appear
9448 // in integral constant expressions. The member shall still be
9449 // defined in a namespace scope if it is used in the program and the
9450 // namespace scope definition shall not contain an initializer.
9452 // We already performed a redefinition check above, but for static
9453 // data members we also need to check whether there was an in-class
9454 // declaration with an initializer.
9455 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9456 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9457 << VDecl->getDeclName();
9458 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9459 diag::note_previous_initializer)
9464 if (VDecl->hasLocalStorage())
9465 getCurFunction()->setHasBranchProtectedScope();
9467 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9468 VDecl->setInvalidDecl();
9473 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9474 // a kernel function cannot be initialized."
9475 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9476 Diag(VDecl->getLocation(), diag::err_local_cant_init);
9477 VDecl->setInvalidDecl();
9481 // Get the decls type and save a reference for later, since
9482 // CheckInitializerTypes may change it.
9483 QualType DclT = VDecl->getType(), SavT = DclT;
9485 // Expressions default to 'id' when we're in a debugger
9486 // and we are assigning it to a variable of Objective-C pointer type.
9487 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9488 Init->getType() == Context.UnknownAnyTy) {
9489 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9490 if (Result.isInvalid()) {
9491 VDecl->setInvalidDecl();
9494 Init = Result.get();
9497 // Perform the initialization.
9498 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9499 if (!VDecl->isInvalidDecl()) {
9500 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9501 InitializationKind Kind =
9504 ? InitializationKind::CreateDirect(VDecl->getLocation(),
9505 Init->getLocStart(),
9507 : InitializationKind::CreateDirectList(VDecl->getLocation())
9508 : InitializationKind::CreateCopy(VDecl->getLocation(),
9509 Init->getLocStart());
9511 MultiExprArg Args = Init;
9513 Args = MultiExprArg(CXXDirectInit->getExprs(),
9514 CXXDirectInit->getNumExprs());
9516 // Try to correct any TypoExprs in the initialization arguments.
9517 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9518 ExprResult Res = CorrectDelayedTyposInExpr(
9519 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9520 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9521 return Init.Failed() ? ExprError() : E;
9523 if (Res.isInvalid()) {
9524 VDecl->setInvalidDecl();
9525 } else if (Res.get() != Args[Idx]) {
9526 Args[Idx] = Res.get();
9529 if (VDecl->isInvalidDecl())
9532 InitializationSequence InitSeq(*this, Entity, Kind, Args,
9533 /*TopLevelOfInitList=*/false,
9534 /*TreatUnavailableAsInvalid=*/false);
9535 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9536 if (Result.isInvalid()) {
9537 VDecl->setInvalidDecl();
9541 Init = Result.getAs<Expr>();
9544 // Check for self-references within variable initializers.
9545 // Variables declared within a function/method body (except for references)
9546 // are handled by a dataflow analysis.
9547 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9548 VDecl->getType()->isReferenceType()) {
9549 CheckSelfReference(*this, RealDecl, Init, DirectInit);
9552 // If the type changed, it means we had an incomplete type that was
9553 // completed by the initializer. For example:
9554 // int ary[] = { 1, 3, 5 };
9555 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9556 if (!VDecl->isInvalidDecl() && (DclT != SavT))
9557 VDecl->setType(DclT);
9559 if (!VDecl->isInvalidDecl()) {
9560 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9562 if (VDecl->hasAttr<BlocksAttr>())
9563 checkRetainCycles(VDecl, Init);
9565 // It is safe to assign a weak reference into a strong variable.
9566 // Although this code can still have problems:
9567 // id x = self.weakProp;
9568 // id y = self.weakProp;
9569 // we do not warn to warn spuriously when 'x' and 'y' are on separate
9570 // paths through the function. This should be revisited if
9571 // -Wrepeated-use-of-weak is made flow-sensitive.
9572 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9573 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9574 Init->getLocStart()))
9575 getCurFunction()->markSafeWeakUse(Init);
9578 // The initialization is usually a full-expression.
9580 // FIXME: If this is a braced initialization of an aggregate, it is not
9581 // an expression, and each individual field initializer is a separate
9582 // full-expression. For instance, in:
9584 // struct Temp { ~Temp(); };
9585 // struct S { S(Temp); };
9586 // struct T { S a, b; } t = { Temp(), Temp() }
9588 // we should destroy the first Temp before constructing the second.
9589 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9591 VDecl->isConstexpr());
9592 if (Result.isInvalid()) {
9593 VDecl->setInvalidDecl();
9596 Init = Result.get();
9598 // Attach the initializer to the decl.
9599 VDecl->setInit(Init);
9601 if (VDecl->isLocalVarDecl()) {
9602 // C99 6.7.8p4: All the expressions in an initializer for an object that has
9603 // static storage duration shall be constant expressions or string literals.
9604 // C++ does not have this restriction.
9605 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9606 const Expr *Culprit;
9607 if (VDecl->getStorageClass() == SC_Static)
9608 CheckForConstantInitializer(Init, DclT);
9609 // C89 is stricter than C99 for non-static aggregate types.
9610 // C89 6.5.7p3: All the expressions [...] in an initializer list
9611 // for an object that has aggregate or union type shall be
9612 // constant expressions.
9613 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9614 isa<InitListExpr>(Init) &&
9615 !Init->isConstantInitializer(Context, false, &Culprit))
9616 Diag(Culprit->getExprLoc(),
9617 diag::ext_aggregate_init_not_constant)
9618 << Culprit->getSourceRange();
9620 } else if (VDecl->isStaticDataMember() &&
9621 VDecl->getLexicalDeclContext()->isRecord()) {
9622 // This is an in-class initialization for a static data member, e.g.,
9625 // static const int value = 17;
9628 // C++ [class.mem]p4:
9629 // A member-declarator can contain a constant-initializer only
9630 // if it declares a static member (9.4) of const integral or
9631 // const enumeration type, see 9.4.2.
9633 // C++11 [class.static.data]p3:
9634 // If a non-volatile const static data member is of integral or
9635 // enumeration type, its declaration in the class definition can
9636 // specify a brace-or-equal-initializer in which every initalizer-clause
9637 // that is an assignment-expression is a constant expression. A static
9638 // data member of literal type can be declared in the class definition
9639 // with the constexpr specifier; if so, its declaration shall specify a
9640 // brace-or-equal-initializer in which every initializer-clause that is
9641 // an assignment-expression is a constant expression.
9643 // Do nothing on dependent types.
9644 if (DclT->isDependentType()) {
9646 // Allow any 'static constexpr' members, whether or not they are of literal
9647 // type. We separately check that every constexpr variable is of literal
9649 } else if (VDecl->isConstexpr()) {
9651 // Require constness.
9652 } else if (!DclT.isConstQualified()) {
9653 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9654 << Init->getSourceRange();
9655 VDecl->setInvalidDecl();
9657 // We allow integer constant expressions in all cases.
9658 } else if (DclT->isIntegralOrEnumerationType()) {
9659 // Check whether the expression is a constant expression.
9661 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9662 // In C++11, a non-constexpr const static data member with an
9663 // in-class initializer cannot be volatile.
9664 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9665 else if (Init->isValueDependent())
9666 ; // Nothing to check.
9667 else if (Init->isIntegerConstantExpr(Context, &Loc))
9668 ; // Ok, it's an ICE!
9669 else if (Init->isEvaluatable(Context)) {
9670 // If we can constant fold the initializer through heroics, accept it,
9671 // but report this as a use of an extension for -pedantic.
9672 Diag(Loc, diag::ext_in_class_initializer_non_constant)
9673 << Init->getSourceRange();
9675 // Otherwise, this is some crazy unknown case. Report the issue at the
9676 // location provided by the isIntegerConstantExpr failed check.
9677 Diag(Loc, diag::err_in_class_initializer_non_constant)
9678 << Init->getSourceRange();
9679 VDecl->setInvalidDecl();
9682 // We allow foldable floating-point constants as an extension.
9683 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9684 // In C++98, this is a GNU extension. In C++11, it is not, but we support
9685 // it anyway and provide a fixit to add the 'constexpr'.
9686 if (getLangOpts().CPlusPlus11) {
9687 Diag(VDecl->getLocation(),
9688 diag::ext_in_class_initializer_float_type_cxx11)
9689 << DclT << Init->getSourceRange();
9690 Diag(VDecl->getLocStart(),
9691 diag::note_in_class_initializer_float_type_cxx11)
9692 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9694 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9695 << DclT << Init->getSourceRange();
9697 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9698 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9699 << Init->getSourceRange();
9700 VDecl->setInvalidDecl();
9704 // Suggest adding 'constexpr' in C++11 for literal types.
9705 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9706 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9707 << DclT << Init->getSourceRange()
9708 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9709 VDecl->setConstexpr(true);
9712 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9713 << DclT << Init->getSourceRange();
9714 VDecl->setInvalidDecl();
9716 } else if (VDecl->isFileVarDecl()) {
9717 if (VDecl->getStorageClass() == SC_Extern &&
9718 (!getLangOpts().CPlusPlus ||
9719 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9720 VDecl->isExternC())) &&
9721 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9722 Diag(VDecl->getLocation(), diag::warn_extern_init);
9724 // C99 6.7.8p4. All file scoped initializers need to be constant.
9725 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9726 CheckForConstantInitializer(Init, DclT);
9729 // We will represent direct-initialization similarly to copy-initialization:
9730 // int x(1); -as-> int x = 1;
9731 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9733 // Clients that want to distinguish between the two forms, can check for
9734 // direct initializer using VarDecl::getInitStyle().
9735 // A major benefit is that clients that don't particularly care about which
9736 // exactly form was it (like the CodeGen) can handle both cases without
9737 // special case code.
9740 // The form of initialization (using parentheses or '=') is generally
9741 // insignificant, but does matter when the entity being initialized has a
9743 if (CXXDirectInit) {
9744 assert(DirectInit && "Call-style initializer must be direct init.");
9745 VDecl->setInitStyle(VarDecl::CallInit);
9746 } else if (DirectInit) {
9747 // This must be list-initialization. No other way is direct-initialization.
9748 VDecl->setInitStyle(VarDecl::ListInit);
9751 CheckCompleteVariableDeclaration(VDecl);
9754 /// ActOnInitializerError - Given that there was an error parsing an
9755 /// initializer for the given declaration, try to return to some form
9757 void Sema::ActOnInitializerError(Decl *D) {
9758 // Our main concern here is re-establishing invariants like "a
9759 // variable's type is either dependent or complete".
9760 if (!D || D->isInvalidDecl()) return;
9762 VarDecl *VD = dyn_cast<VarDecl>(D);
9765 // Auto types are meaningless if we can't make sense of the initializer.
9766 if (ParsingInitForAutoVars.count(D)) {
9767 D->setInvalidDecl();
9771 QualType Ty = VD->getType();
9772 if (Ty->isDependentType()) return;
9774 // Require a complete type.
9775 if (RequireCompleteType(VD->getLocation(),
9776 Context.getBaseElementType(Ty),
9777 diag::err_typecheck_decl_incomplete_type)) {
9778 VD->setInvalidDecl();
9782 // Require a non-abstract type.
9783 if (RequireNonAbstractType(VD->getLocation(), Ty,
9784 diag::err_abstract_type_in_decl,
9785 AbstractVariableType)) {
9786 VD->setInvalidDecl();
9790 // Don't bother complaining about constructors or destructors,
9794 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9795 bool TypeMayContainAuto) {
9796 // If there is no declaration, there was an error parsing it. Just ignore it.
9800 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9801 QualType Type = Var->getType();
9803 // C++11 [dcl.spec.auto]p3
9804 if (TypeMayContainAuto && Type->getContainedAutoType()) {
9805 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9806 << Var->getDeclName() << Type;
9807 Var->setInvalidDecl();
9811 // C++11 [class.static.data]p3: A static data member can be declared with
9812 // the constexpr specifier; if so, its declaration shall specify
9813 // a brace-or-equal-initializer.
9814 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9815 // the definition of a variable [...] or the declaration of a static data
9817 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9818 if (Var->isStaticDataMember())
9819 Diag(Var->getLocation(),
9820 diag::err_constexpr_static_mem_var_requires_init)
9821 << Var->getDeclName();
9823 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9824 Var->setInvalidDecl();
9828 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
9829 // definition having the concept specifier is called a variable concept. A
9830 // concept definition refers to [...] a variable concept and its initializer.
9831 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
9832 if (VTD->isConcept()) {
9833 Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9834 Var->setInvalidDecl();
9839 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9841 if (!Var->isInvalidDecl() &&
9842 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9843 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9844 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9845 Var->setInvalidDecl();
9849 switch (Var->isThisDeclarationADefinition()) {
9850 case VarDecl::Definition:
9851 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9854 // We have an out-of-line definition of a static data member
9855 // that has an in-class initializer, so we type-check this like
9860 case VarDecl::DeclarationOnly:
9861 // It's only a declaration.
9863 // Block scope. C99 6.7p7: If an identifier for an object is
9864 // declared with no linkage (C99 6.2.2p6), the type for the
9865 // object shall be complete.
9866 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9867 !Var->hasLinkage() && !Var->isInvalidDecl() &&
9868 RequireCompleteType(Var->getLocation(), Type,
9869 diag::err_typecheck_decl_incomplete_type))
9870 Var->setInvalidDecl();
9872 // Make sure that the type is not abstract.
9873 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9874 RequireNonAbstractType(Var->getLocation(), Type,
9875 diag::err_abstract_type_in_decl,
9876 AbstractVariableType))
9877 Var->setInvalidDecl();
9878 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9879 Var->getStorageClass() == SC_PrivateExtern) {
9880 Diag(Var->getLocation(), diag::warn_private_extern);
9881 Diag(Var->getLocation(), diag::note_private_extern);
9886 case VarDecl::TentativeDefinition:
9887 // File scope. C99 6.9.2p2: A declaration of an identifier for an
9888 // object that has file scope without an initializer, and without a
9889 // storage-class specifier or with the storage-class specifier "static",
9890 // constitutes a tentative definition. Note: A tentative definition with
9891 // external linkage is valid (C99 6.2.2p5).
9892 if (!Var->isInvalidDecl()) {
9893 if (const IncompleteArrayType *ArrayT
9894 = Context.getAsIncompleteArrayType(Type)) {
9895 if (RequireCompleteType(Var->getLocation(),
9896 ArrayT->getElementType(),
9897 diag::err_illegal_decl_array_incomplete_type))
9898 Var->setInvalidDecl();
9899 } else if (Var->getStorageClass() == SC_Static) {
9900 // C99 6.9.2p3: If the declaration of an identifier for an object is
9901 // a tentative definition and has internal linkage (C99 6.2.2p3), the
9902 // declared type shall not be an incomplete type.
9903 // NOTE: code such as the following
9905 // struct s { int a; };
9906 // is accepted by gcc. Hence here we issue a warning instead of
9907 // an error and we do not invalidate the static declaration.
9908 // NOTE: to avoid multiple warnings, only check the first declaration.
9909 if (Var->isFirstDecl())
9910 RequireCompleteType(Var->getLocation(), Type,
9911 diag::ext_typecheck_decl_incomplete_type);
9915 // Record the tentative definition; we're done.
9916 if (!Var->isInvalidDecl())
9917 TentativeDefinitions.push_back(Var);
9921 // Provide a specific diagnostic for uninitialized variable
9922 // definitions with incomplete array type.
9923 if (Type->isIncompleteArrayType()) {
9924 Diag(Var->getLocation(),
9925 diag::err_typecheck_incomplete_array_needs_initializer);
9926 Var->setInvalidDecl();
9930 // Provide a specific diagnostic for uninitialized variable
9931 // definitions with reference type.
9932 if (Type->isReferenceType()) {
9933 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9934 << Var->getDeclName()
9935 << SourceRange(Var->getLocation(), Var->getLocation());
9936 Var->setInvalidDecl();
9940 // Do not attempt to type-check the default initializer for a
9941 // variable with dependent type.
9942 if (Type->isDependentType())
9945 if (Var->isInvalidDecl())
9948 if (!Var->hasAttr<AliasAttr>()) {
9949 if (RequireCompleteType(Var->getLocation(),
9950 Context.getBaseElementType(Type),
9951 diag::err_typecheck_decl_incomplete_type)) {
9952 Var->setInvalidDecl();
9959 // The variable can not have an abstract class type.
9960 if (RequireNonAbstractType(Var->getLocation(), Type,
9961 diag::err_abstract_type_in_decl,
9962 AbstractVariableType)) {
9963 Var->setInvalidDecl();
9967 // Check for jumps past the implicit initializer. C++0x
9968 // clarifies that this applies to a "variable with automatic
9969 // storage duration", not a "local variable".
9970 // C++11 [stmt.dcl]p3
9971 // A program that jumps from a point where a variable with automatic
9972 // storage duration is not in scope to a point where it is in scope is
9973 // ill-formed unless the variable has scalar type, class type with a
9974 // trivial default constructor and a trivial destructor, a cv-qualified
9975 // version of one of these types, or an array of one of the preceding
9976 // types and is declared without an initializer.
9977 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9978 if (const RecordType *Record
9979 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9980 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9981 // Mark the function for further checking even if the looser rules of
9982 // C++11 do not require such checks, so that we can diagnose
9983 // incompatibilities with C++98.
9984 if (!CXXRecord->isPOD())
9985 getCurFunction()->setHasBranchProtectedScope();
9989 // C++03 [dcl.init]p9:
9990 // If no initializer is specified for an object, and the
9991 // object is of (possibly cv-qualified) non-POD class type (or
9992 // array thereof), the object shall be default-initialized; if
9993 // the object is of const-qualified type, the underlying class
9994 // type shall have a user-declared default
9995 // constructor. Otherwise, if no initializer is specified for
9996 // a non- static object, the object and its subobjects, if
9997 // any, have an indeterminate initial value); if the object
9998 // or any of its subobjects are of const-qualified type, the
9999 // program is ill-formed.
10000 // C++0x [dcl.init]p11:
10001 // If no initializer is specified for an object, the object is
10002 // default-initialized; [...].
10003 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10004 InitializationKind Kind
10005 = InitializationKind::CreateDefault(Var->getLocation());
10007 InitializationSequence InitSeq(*this, Entity, Kind, None);
10008 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10009 if (Init.isInvalid())
10010 Var->setInvalidDecl();
10011 else if (Init.get()) {
10012 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10013 // This is important for template substitution.
10014 Var->setInitStyle(VarDecl::CallInit);
10017 CheckCompleteVariableDeclaration(Var);
10021 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10022 // If there is no declaration, there was an error parsing it. Ignore it.
10026 VarDecl *VD = dyn_cast<VarDecl>(D);
10028 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10029 D->setInvalidDecl();
10033 VD->setCXXForRangeDecl(true);
10035 // for-range-declaration cannot be given a storage class specifier.
10037 switch (VD->getStorageClass()) {
10046 case SC_PrivateExtern:
10057 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10058 << VD->getDeclName() << Error;
10059 D->setInvalidDecl();
10064 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10065 IdentifierInfo *Ident,
10066 ParsedAttributes &Attrs,
10067 SourceLocation AttrEnd) {
10068 // C++1y [stmt.iter]p1:
10069 // A range-based for statement of the form
10070 // for ( for-range-identifier : for-range-initializer ) statement
10071 // is equivalent to
10072 // for ( auto&& for-range-identifier : for-range-initializer ) statement
10073 DeclSpec DS(Attrs.getPool().getFactory());
10075 const char *PrevSpec;
10077 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10078 getPrintingPolicy());
10080 Declarator D(DS, Declarator::ForContext);
10081 D.SetIdentifier(Ident, IdentLoc);
10082 D.takeAttributes(Attrs, AttrEnd);
10084 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10085 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10086 EmptyAttrs, IdentLoc);
10087 Decl *Var = ActOnDeclarator(S, D);
10088 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10089 FinalizeDeclaration(Var);
10090 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10091 AttrEnd.isValid() ? AttrEnd : IdentLoc);
10094 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10095 if (var->isInvalidDecl()) return;
10097 if (getLangOpts().OpenCL) {
10098 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10100 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10102 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10104 var->setInvalidDecl();
10109 // In Objective-C, don't allow jumps past the implicit initialization of a
10110 // local retaining variable.
10111 if (getLangOpts().ObjC1 &&
10112 var->hasLocalStorage()) {
10113 switch (var->getType().getObjCLifetime()) {
10114 case Qualifiers::OCL_None:
10115 case Qualifiers::OCL_ExplicitNone:
10116 case Qualifiers::OCL_Autoreleasing:
10119 case Qualifiers::OCL_Weak:
10120 case Qualifiers::OCL_Strong:
10121 getCurFunction()->setHasBranchProtectedScope();
10126 // Warn about externally-visible variables being defined without a
10127 // prior declaration. We only want to do this for global
10128 // declarations, but we also specifically need to avoid doing it for
10129 // class members because the linkage of an anonymous class can
10130 // change if it's later given a typedef name.
10131 if (var->isThisDeclarationADefinition() &&
10132 var->getDeclContext()->getRedeclContext()->isFileContext() &&
10133 var->isExternallyVisible() && var->hasLinkage() &&
10134 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10135 var->getLocation())) {
10136 // Find a previous declaration that's not a definition.
10137 VarDecl *prev = var->getPreviousDecl();
10138 while (prev && prev->isThisDeclarationADefinition())
10139 prev = prev->getPreviousDecl();
10142 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10145 if (var->getTLSKind() == VarDecl::TLS_Static) {
10146 const Expr *Culprit;
10147 if (var->getType().isDestructedType()) {
10148 // GNU C++98 edits for __thread, [basic.start.term]p3:
10149 // The type of an object with thread storage duration shall not
10150 // have a non-trivial destructor.
10151 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10152 if (getLangOpts().CPlusPlus11)
10153 Diag(var->getLocation(), diag::note_use_thread_local);
10154 } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10155 !var->getInit()->isConstantInitializer(
10156 Context, var->getType()->isReferenceType(), &Culprit)) {
10157 // GNU C++98 edits for __thread, [basic.start.init]p4:
10158 // An object of thread storage duration shall not require dynamic
10160 // FIXME: Need strict checking here.
10161 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10162 << Culprit->getSourceRange();
10163 if (getLangOpts().CPlusPlus11)
10164 Diag(var->getLocation(), diag::note_use_thread_local);
10168 // Apply section attributes and pragmas to global variables.
10169 bool GlobalStorage = var->hasGlobalStorage();
10170 if (GlobalStorage && var->isThisDeclarationADefinition() &&
10171 ActiveTemplateInstantiations.empty()) {
10172 PragmaStack<StringLiteral *> *Stack = nullptr;
10173 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10174 if (var->getType().isConstQualified())
10175 Stack = &ConstSegStack;
10176 else if (!var->getInit()) {
10177 Stack = &BSSSegStack;
10178 SectionFlags |= ASTContext::PSF_Write;
10180 Stack = &DataSegStack;
10181 SectionFlags |= ASTContext::PSF_Write;
10183 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10184 var->addAttr(SectionAttr::CreateImplicit(
10185 Context, SectionAttr::Declspec_allocate,
10186 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10188 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10189 if (UnifySection(SA->getName(), SectionFlags, var))
10190 var->dropAttr<SectionAttr>();
10192 // Apply the init_seg attribute if this has an initializer. If the
10193 // initializer turns out to not be dynamic, we'll end up ignoring this
10195 if (CurInitSeg && var->getInit())
10196 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10200 // All the following checks are C++ only.
10201 if (!getLangOpts().CPlusPlus) return;
10203 QualType type = var->getType();
10204 if (type->isDependentType()) return;
10206 // __block variables might require us to capture a copy-initializer.
10207 if (var->hasAttr<BlocksAttr>()) {
10208 // It's currently invalid to ever have a __block variable with an
10209 // array type; should we diagnose that here?
10211 // Regardless, we don't want to ignore array nesting when
10212 // constructing this copy.
10213 if (type->isStructureOrClassType()) {
10214 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10215 SourceLocation poi = var->getLocation();
10216 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10218 = PerformMoveOrCopyInitialization(
10219 InitializedEntity::InitializeBlock(poi, type, false),
10220 var, var->getType(), varRef, /*AllowNRVO=*/true);
10221 if (!result.isInvalid()) {
10222 result = MaybeCreateExprWithCleanups(result);
10223 Expr *init = result.getAs<Expr>();
10224 Context.setBlockVarCopyInits(var, init);
10229 Expr *Init = var->getInit();
10230 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10231 QualType baseType = Context.getBaseElementType(type);
10233 if (!var->getDeclContext()->isDependentContext() &&
10234 Init && !Init->isValueDependent()) {
10235 if (IsGlobal && !var->isConstexpr() &&
10236 !getDiagnostics().isIgnored(diag::warn_global_constructor,
10237 var->getLocation())) {
10238 // Warn about globals which don't have a constant initializer. Don't
10239 // warn about globals with a non-trivial destructor because we already
10240 // warned about them.
10241 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10242 if (!(RD && !RD->hasTrivialDestructor()) &&
10243 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10244 Diag(var->getLocation(), diag::warn_global_constructor)
10245 << Init->getSourceRange();
10248 if (var->isConstexpr()) {
10249 SmallVector<PartialDiagnosticAt, 8> Notes;
10250 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10251 SourceLocation DiagLoc = var->getLocation();
10252 // If the note doesn't add any useful information other than a source
10253 // location, fold it into the primary diagnostic.
10254 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10255 diag::note_invalid_subexpr_in_const_expr) {
10256 DiagLoc = Notes[0].first;
10259 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10260 << var << Init->getSourceRange();
10261 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10262 Diag(Notes[I].first, Notes[I].second);
10264 } else if (var->isUsableInConstantExpressions(Context)) {
10265 // Check whether the initializer of a const variable of integral or
10266 // enumeration type is an ICE now, since we can't tell whether it was
10267 // initialized by a constant expression if we check later.
10268 var->checkInitIsICE();
10272 // Require the destructor.
10273 if (const RecordType *recordType = baseType->getAs<RecordType>())
10274 FinalizeVarWithDestructor(var, recordType);
10277 /// \brief Determines if a variable's alignment is dependent.
10278 static bool hasDependentAlignment(VarDecl *VD) {
10279 if (VD->getType()->isDependentType())
10281 for (auto *I : VD->specific_attrs<AlignedAttr>())
10282 if (I->isAlignmentDependent())
10287 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10288 /// any semantic actions necessary after any initializer has been attached.
10290 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10291 // Note that we are no longer parsing the initializer for this declaration.
10292 ParsingInitForAutoVars.erase(ThisDecl);
10294 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10298 checkAttributesAfterMerging(*this, *VD);
10300 // Perform TLS alignment check here after attributes attached to the variable
10301 // which may affect the alignment have been processed. Only perform the check
10302 // if the target has a maximum TLS alignment (zero means no constraints).
10303 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10304 // Protect the check so that it's not performed on dependent types and
10305 // dependent alignments (we can't determine the alignment in that case).
10306 if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10307 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10308 if (Context.getDeclAlign(VD) > MaxAlignChars) {
10309 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10310 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10311 << (unsigned)MaxAlignChars.getQuantity();
10316 // Static locals inherit dll attributes from their function.
10317 if (VD->isStaticLocal()) {
10318 if (FunctionDecl *FD =
10319 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10320 if (Attr *A = getDLLAttr(FD)) {
10321 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10322 NewAttr->setInherited(true);
10323 VD->addAttr(NewAttr);
10328 // Perform check for initializers of device-side global variables.
10329 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10330 // 7.5). CUDA also allows constant initializers for __constant__ and
10331 // __device__ variables.
10332 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10333 const Expr *Init = VD->getInit();
10334 const bool IsGlobal = VD->hasGlobalStorage() && !VD->isStaticLocal();
10335 if (Init && IsGlobal &&
10336 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10337 VD->hasAttr<CUDASharedAttr>())) {
10338 bool AllowedInit = false;
10339 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10341 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10342 // We'll allow constant initializers even if it's a non-empty
10343 // constructor according to CUDA rules. This deviates from NVCC,
10344 // but allows us to handle things like constexpr constructors.
10345 if (!AllowedInit &&
10346 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10347 AllowedInit = VD->getInit()->isConstantInitializer(
10348 Context, VD->getType()->isReferenceType());
10350 if (!AllowedInit) {
10351 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10352 ? diag::err_shared_var_init
10353 : diag::err_dynamic_var_init)
10354 << Init->getSourceRange();
10355 VD->setInvalidDecl();
10360 // Grab the dllimport or dllexport attribute off of the VarDecl.
10361 const InheritableAttr *DLLAttr = getDLLAttr(VD);
10363 // Imported static data members cannot be defined out-of-line.
10364 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10365 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10366 VD->isThisDeclarationADefinition()) {
10367 // We allow definitions of dllimport class template static data members
10369 CXXRecordDecl *Context =
10370 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10371 bool IsClassTemplateMember =
10372 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10373 Context->getDescribedClassTemplate();
10375 Diag(VD->getLocation(),
10376 IsClassTemplateMember
10377 ? diag::warn_attribute_dllimport_static_field_definition
10378 : diag::err_attribute_dllimport_static_field_definition);
10379 Diag(IA->getLocation(), diag::note_attribute);
10380 if (!IsClassTemplateMember)
10381 VD->setInvalidDecl();
10385 // dllimport/dllexport variables cannot be thread local, their TLS index
10386 // isn't exported with the variable.
10387 if (DLLAttr && VD->getTLSKind()) {
10388 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10389 if (F && getDLLAttr(F)) {
10390 assert(VD->isStaticLocal());
10391 // But if this is a static local in a dlimport/dllexport function, the
10392 // function will never be inlined, which means the var would never be
10393 // imported, so having it marked import/export is safe.
10395 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10397 VD->setInvalidDecl();
10401 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10402 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10403 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10404 VD->dropAttr<UsedAttr>();
10408 const DeclContext *DC = VD->getDeclContext();
10409 // If there's a #pragma GCC visibility in scope, and this isn't a class
10410 // member, set the visibility of this variable.
10411 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10412 AddPushedVisibilityAttribute(VD);
10414 // FIXME: Warn on unused templates.
10415 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10416 !isa<VarTemplatePartialSpecializationDecl>(VD))
10417 MarkUnusedFileScopedDecl(VD);
10419 // Now we have parsed the initializer and can update the table of magic
10421 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10422 !VD->getType()->isIntegralOrEnumerationType())
10425 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10426 const Expr *MagicValueExpr = VD->getInit();
10427 if (!MagicValueExpr) {
10430 llvm::APSInt MagicValueInt;
10431 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10432 Diag(I->getRange().getBegin(),
10433 diag::err_type_tag_for_datatype_not_ice)
10434 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10437 if (MagicValueInt.getActiveBits() > 64) {
10438 Diag(I->getRange().getBegin(),
10439 diag::err_type_tag_for_datatype_too_large)
10440 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10443 uint64_t MagicValue = MagicValueInt.getZExtValue();
10444 RegisterTypeTagForDatatype(I->getArgumentKind(),
10446 I->getMatchingCType(),
10447 I->getLayoutCompatible(),
10448 I->getMustBeNull());
10452 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10453 ArrayRef<Decl *> Group) {
10454 SmallVector<Decl*, 8> Decls;
10456 if (DS.isTypeSpecOwned())
10457 Decls.push_back(DS.getRepAsDecl());
10459 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10460 for (unsigned i = 0, e = Group.size(); i != e; ++i)
10461 if (Decl *D = Group[i]) {
10462 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10463 if (!FirstDeclaratorInGroup)
10464 FirstDeclaratorInGroup = DD;
10465 Decls.push_back(D);
10468 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10469 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10470 handleTagNumbering(Tag, S);
10471 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10472 getLangOpts().CPlusPlus)
10473 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10477 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10480 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10481 /// group, performing any necessary semantic checking.
10482 Sema::DeclGroupPtrTy
10483 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10484 bool TypeMayContainAuto) {
10485 // C++0x [dcl.spec.auto]p7:
10486 // If the type deduced for the template parameter U is not the same in each
10487 // deduction, the program is ill-formed.
10488 // FIXME: When initializer-list support is added, a distinction is needed
10489 // between the deduced type U and the deduced type which 'auto' stands for.
10490 // auto a = 0, b = { 1, 2, 3 };
10491 // is legal because the deduced type U is 'int' in both cases.
10492 if (TypeMayContainAuto && Group.size() > 1) {
10494 CanQualType DeducedCanon;
10495 VarDecl *DeducedDecl = nullptr;
10496 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10497 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10498 AutoType *AT = D->getType()->getContainedAutoType();
10499 // Don't reissue diagnostics when instantiating a template.
10500 if (AT && D->isInvalidDecl())
10502 QualType U = AT ? AT->getDeducedType() : QualType();
10504 CanQualType UCanon = Context.getCanonicalType(U);
10505 if (Deduced.isNull()) {
10507 DeducedCanon = UCanon;
10509 } else if (DeducedCanon != UCanon) {
10510 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10511 diag::err_auto_different_deductions)
10512 << (unsigned)AT->getKeyword()
10513 << Deduced << DeducedDecl->getDeclName()
10514 << U << D->getDeclName()
10515 << DeducedDecl->getInit()->getSourceRange()
10516 << D->getInit()->getSourceRange();
10517 D->setInvalidDecl();
10525 ActOnDocumentableDecls(Group);
10527 return DeclGroupPtrTy::make(
10528 DeclGroupRef::Create(Context, Group.data(), Group.size()));
10531 void Sema::ActOnDocumentableDecl(Decl *D) {
10532 ActOnDocumentableDecls(D);
10535 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10536 // Don't parse the comment if Doxygen diagnostics are ignored.
10537 if (Group.empty() || !Group[0])
10540 if (Diags.isIgnored(diag::warn_doc_param_not_found,
10541 Group[0]->getLocation()) &&
10542 Diags.isIgnored(diag::warn_unknown_comment_command_name,
10543 Group[0]->getLocation()))
10546 if (Group.size() >= 2) {
10547 // This is a decl group. Normally it will contain only declarations
10548 // produced from declarator list. But in case we have any definitions or
10549 // additional declaration references:
10550 // 'typedef struct S {} S;'
10551 // 'typedef struct S *S;'
10553 // FinalizeDeclaratorGroup adds these as separate declarations.
10554 Decl *MaybeTagDecl = Group[0];
10555 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10556 Group = Group.slice(1);
10560 // See if there are any new comments that are not attached to a decl.
10561 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10562 if (!Comments.empty() &&
10563 !Comments.back()->isAttached()) {
10564 // There is at least one comment that not attached to a decl.
10565 // Maybe it should be attached to one of these decls?
10567 // Note that this way we pick up not only comments that precede the
10568 // declaration, but also comments that *follow* the declaration -- thanks to
10569 // the lookahead in the lexer: we've consumed the semicolon and looked
10570 // ahead through comments.
10571 for (unsigned i = 0, e = Group.size(); i != e; ++i)
10572 Context.getCommentForDecl(Group[i], &PP);
10576 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10577 /// to introduce parameters into function prototype scope.
10578 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10579 const DeclSpec &DS = D.getDeclSpec();
10581 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10583 // C++03 [dcl.stc]p2 also permits 'auto'.
10584 StorageClass SC = SC_None;
10585 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10587 } else if (getLangOpts().CPlusPlus &&
10588 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10590 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10591 Diag(DS.getStorageClassSpecLoc(),
10592 diag::err_invalid_storage_class_in_func_decl);
10593 D.getMutableDeclSpec().ClearStorageClassSpecs();
10596 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10597 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10598 << DeclSpec::getSpecifierName(TSCS);
10599 if (DS.isConstexprSpecified())
10600 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10602 if (DS.isConceptSpecified())
10603 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10605 DiagnoseFunctionSpecifiers(DS);
10607 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10608 QualType parmDeclType = TInfo->getType();
10610 if (getLangOpts().CPlusPlus) {
10611 // Check that there are no default arguments inside the type of this
10613 CheckExtraCXXDefaultArguments(D);
10615 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10616 if (D.getCXXScopeSpec().isSet()) {
10617 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10618 << D.getCXXScopeSpec().getRange();
10619 D.getCXXScopeSpec().clear();
10623 // Ensure we have a valid name
10624 IdentifierInfo *II = nullptr;
10626 II = D.getIdentifier();
10628 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10629 << GetNameForDeclarator(D).getName();
10630 D.setInvalidType(true);
10634 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10636 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10639 if (R.isSingleResult()) {
10640 NamedDecl *PrevDecl = R.getFoundDecl();
10641 if (PrevDecl->isTemplateParameter()) {
10642 // Maybe we will complain about the shadowed template parameter.
10643 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10644 // Just pretend that we didn't see the previous declaration.
10645 PrevDecl = nullptr;
10646 } else if (S->isDeclScope(PrevDecl)) {
10647 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10648 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10650 // Recover by removing the name
10652 D.SetIdentifier(nullptr, D.getIdentifierLoc());
10653 D.setInvalidType(true);
10658 // Temporarily put parameter variables in the translation unit, not
10659 // the enclosing context. This prevents them from accidentally
10660 // looking like class members in C++.
10661 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10663 D.getIdentifierLoc(), II,
10664 parmDeclType, TInfo,
10667 if (D.isInvalidType())
10668 New->setInvalidDecl();
10670 assert(S->isFunctionPrototypeScope());
10671 assert(S->getFunctionPrototypeDepth() >= 1);
10672 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10673 S->getNextFunctionPrototypeIndex());
10675 // Add the parameter declaration into this scope.
10678 IdResolver.AddDecl(New);
10680 ProcessDeclAttributes(S, New, D);
10682 if (D.getDeclSpec().isModulePrivateSpecified())
10683 Diag(New->getLocation(), diag::err_module_private_local)
10684 << 1 << New->getDeclName()
10685 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10686 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10688 if (New->hasAttr<BlocksAttr>()) {
10689 Diag(New->getLocation(), diag::err_block_on_nonlocal);
10694 /// \brief Synthesizes a variable for a parameter arising from a
10696 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10697 SourceLocation Loc,
10699 /* FIXME: setting StartLoc == Loc.
10700 Would it be worth to modify callers so as to provide proper source
10701 location for the unnamed parameters, embedding the parameter's type? */
10702 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10703 T, Context.getTrivialTypeSourceInfo(T, Loc),
10705 Param->setImplicit();
10709 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10710 ParmVarDecl * const *ParamEnd) {
10711 // Don't diagnose unused-parameter errors in template instantiations; we
10712 // will already have done so in the template itself.
10713 if (!ActiveTemplateInstantiations.empty())
10716 for (; Param != ParamEnd; ++Param) {
10717 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10718 !(*Param)->hasAttr<UnusedAttr>()) {
10719 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10720 << (*Param)->getDeclName();
10725 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10726 ParmVarDecl * const *ParamEnd,
10729 if (LangOpts.NumLargeByValueCopy == 0) // No check.
10732 // Warn if the return value is pass-by-value and larger than the specified
10734 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10735 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10736 if (Size > LangOpts.NumLargeByValueCopy)
10737 Diag(D->getLocation(), diag::warn_return_value_size)
10738 << D->getDeclName() << Size;
10741 // Warn if any parameter is pass-by-value and larger than the specified
10743 for (; Param != ParamEnd; ++Param) {
10744 QualType T = (*Param)->getType();
10745 if (T->isDependentType() || !T.isPODType(Context))
10747 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10748 if (Size > LangOpts.NumLargeByValueCopy)
10749 Diag((*Param)->getLocation(), diag::warn_parameter_size)
10750 << (*Param)->getDeclName() << Size;
10754 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10755 SourceLocation NameLoc, IdentifierInfo *Name,
10756 QualType T, TypeSourceInfo *TSInfo,
10758 // In ARC, infer a lifetime qualifier for appropriate parameter types.
10759 if (getLangOpts().ObjCAutoRefCount &&
10760 T.getObjCLifetime() == Qualifiers::OCL_None &&
10761 T->isObjCLifetimeType()) {
10763 Qualifiers::ObjCLifetime lifetime;
10765 // Special cases for arrays:
10766 // - if it's const, use __unsafe_unretained
10767 // - otherwise, it's an error
10768 if (T->isArrayType()) {
10769 if (!T.isConstQualified()) {
10770 DelayedDiagnostics.add(
10771 sema::DelayedDiagnostic::makeForbiddenType(
10772 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10774 lifetime = Qualifiers::OCL_ExplicitNone;
10776 lifetime = T->getObjCARCImplicitLifetime();
10778 T = Context.getLifetimeQualifiedType(T, lifetime);
10781 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10782 Context.getAdjustedParameterType(T),
10783 TSInfo, SC, nullptr);
10785 // Parameters can not be abstract class types.
10786 // For record types, this is done by the AbstractClassUsageDiagnoser once
10787 // the class has been completely parsed.
10788 if (!CurContext->isRecord() &&
10789 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10790 AbstractParamType))
10791 New->setInvalidDecl();
10793 // Parameter declarators cannot be interface types. All ObjC objects are
10794 // passed by reference.
10795 if (T->isObjCObjectType()) {
10796 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10798 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10799 << FixItHint::CreateInsertion(TypeEndLoc, "*");
10800 T = Context.getObjCObjectPointerType(T);
10804 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10805 // duration shall not be qualified by an address-space qualifier."
10806 // Since all parameters have automatic store duration, they can not have
10807 // an address space.
10808 if (T.getAddressSpace() != 0) {
10809 // OpenCL allows function arguments declared to be an array of a type
10810 // to be qualified with an address space.
10811 if (!(getLangOpts().OpenCL && T->isArrayType())) {
10812 Diag(NameLoc, diag::err_arg_with_address_space);
10813 New->setInvalidDecl();
10817 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
10818 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
10819 if (getLangOpts().OpenCL && T->isPointerType()) {
10820 const QualType PTy = T->getPointeeType();
10821 if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) {
10822 Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy;
10823 New->setInvalidDecl();
10830 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10831 SourceLocation LocAfterDecls) {
10832 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10834 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10835 // for a K&R function.
10836 if (!FTI.hasPrototype) {
10837 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10839 if (FTI.Params[i].Param == nullptr) {
10840 SmallString<256> Code;
10841 llvm::raw_svector_ostream(Code)
10842 << " int " << FTI.Params[i].Ident->getName() << ";\n";
10843 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10844 << FTI.Params[i].Ident
10845 << FixItHint::CreateInsertion(LocAfterDecls, Code);
10847 // Implicitly declare the argument as type 'int' for lack of a better
10849 AttributeFactory attrs;
10850 DeclSpec DS(attrs);
10851 const char* PrevSpec; // unused
10852 unsigned DiagID; // unused
10853 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10854 DiagID, Context.getPrintingPolicy());
10855 // Use the identifier location for the type source range.
10856 DS.SetRangeStart(FTI.Params[i].IdentLoc);
10857 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10858 Declarator ParamD(DS, Declarator::KNRTypeListContext);
10859 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10860 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10867 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10868 MultiTemplateParamsArg TemplateParameterLists,
10869 SkipBodyInfo *SkipBody) {
10870 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10871 assert(D.isFunctionDeclarator() && "Not a function declarator!");
10872 Scope *ParentScope = FnBodyScope->getParent();
10874 D.setFunctionDefinitionKind(FDK_Definition);
10875 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10876 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10879 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10880 Consumer.HandleInlineMethodDefinition(D);
10883 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10884 const FunctionDecl*& PossibleZeroParamPrototype) {
10885 // Don't warn about invalid declarations.
10886 if (FD->isInvalidDecl())
10889 // Or declarations that aren't global.
10890 if (!FD->isGlobal())
10893 // Don't warn about C++ member functions.
10894 if (isa<CXXMethodDecl>(FD))
10897 // Don't warn about 'main'.
10901 // Don't warn about inline functions.
10902 if (FD->isInlined())
10905 // Don't warn about function templates.
10906 if (FD->getDescribedFunctionTemplate())
10909 // Don't warn about function template specializations.
10910 if (FD->isFunctionTemplateSpecialization())
10913 // Don't warn for OpenCL kernels.
10914 if (FD->hasAttr<OpenCLKernelAttr>())
10917 // Don't warn on explicitly deleted functions.
10918 if (FD->isDeleted())
10921 bool MissingPrototype = true;
10922 for (const FunctionDecl *Prev = FD->getPreviousDecl();
10923 Prev; Prev = Prev->getPreviousDecl()) {
10924 // Ignore any declarations that occur in function or method
10925 // scope, because they aren't visible from the header.
10926 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10929 MissingPrototype = !Prev->getType()->isFunctionProtoType();
10930 if (FD->getNumParams() == 0)
10931 PossibleZeroParamPrototype = Prev;
10935 return MissingPrototype;
10939 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10940 const FunctionDecl *EffectiveDefinition,
10941 SkipBodyInfo *SkipBody) {
10942 // Don't complain if we're in GNU89 mode and the previous definition
10943 // was an extern inline function.
10944 const FunctionDecl *Definition = EffectiveDefinition;
10946 if (!FD->isDefined(Definition))
10949 if (canRedefineFunction(Definition, getLangOpts()))
10952 // If we don't have a visible definition of the function, and it's inline or
10953 // a template, skip the new definition.
10954 if (SkipBody && !hasVisibleDefinition(Definition) &&
10955 (Definition->getFormalLinkage() == InternalLinkage ||
10956 Definition->isInlined() ||
10957 Definition->getDescribedFunctionTemplate() ||
10958 Definition->getNumTemplateParameterLists())) {
10959 SkipBody->ShouldSkip = true;
10960 if (auto *TD = Definition->getDescribedFunctionTemplate())
10961 makeMergedDefinitionVisible(TD, FD->getLocation());
10963 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
10964 FD->getLocation());
10968 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10969 Definition->getStorageClass() == SC_Extern)
10970 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10971 << FD->getDeclName() << getLangOpts().CPlusPlus;
10973 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10975 Diag(Definition->getLocation(), diag::note_previous_definition);
10976 FD->setInvalidDecl();
10979 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10981 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10983 LambdaScopeInfo *LSI = S.PushLambdaScope();
10984 LSI->CallOperator = CallOperator;
10985 LSI->Lambda = LambdaClass;
10986 LSI->ReturnType = CallOperator->getReturnType();
10987 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10989 if (LCD == LCD_None)
10990 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10991 else if (LCD == LCD_ByCopy)
10992 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10993 else if (LCD == LCD_ByRef)
10994 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10995 DeclarationNameInfo DNI = CallOperator->getNameInfo();
10997 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10998 LSI->Mutable = !CallOperator->isConst();
11000 // Add the captures to the LSI so they can be noted as already
11001 // captured within tryCaptureVar.
11002 auto I = LambdaClass->field_begin();
11003 for (const auto &C : LambdaClass->captures()) {
11004 if (C.capturesVariable()) {
11005 VarDecl *VD = C.getCapturedVar();
11006 if (VD->isInitCapture())
11007 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11008 QualType CaptureType = VD->getType();
11009 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11010 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11011 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11012 /*EllipsisLoc*/C.isPackExpansion()
11013 ? C.getEllipsisLoc() : SourceLocation(),
11014 CaptureType, /*Expr*/ nullptr);
11016 } else if (C.capturesThis()) {
11017 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11018 S.getCurrentThisType(), /*Expr*/ nullptr,
11019 C.getCaptureKind() == LCK_StarThis);
11021 LSI->addVLATypeCapture(C.getLocation(), I->getType());
11027 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11028 SkipBodyInfo *SkipBody) {
11029 // Clear the last template instantiation error context.
11030 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11034 FunctionDecl *FD = nullptr;
11036 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11037 FD = FunTmpl->getTemplatedDecl();
11039 FD = cast<FunctionDecl>(D);
11041 // See if this is a redefinition.
11042 if (!FD->isLateTemplateParsed()) {
11043 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11045 // If we're skipping the body, we're done. Don't enter the scope.
11046 if (SkipBody && SkipBody->ShouldSkip)
11050 // If we are instantiating a generic lambda call operator, push
11051 // a LambdaScopeInfo onto the function stack. But use the information
11052 // that's already been calculated (ActOnLambdaExpr) to prime the current
11053 // LambdaScopeInfo.
11054 // When the template operator is being specialized, the LambdaScopeInfo,
11055 // has to be properly restored so that tryCaptureVariable doesn't try
11056 // and capture any new variables. In addition when calculating potential
11057 // captures during transformation of nested lambdas, it is necessary to
11058 // have the LSI properly restored.
11059 if (isGenericLambdaCallOperatorSpecialization(FD)) {
11060 assert(ActiveTemplateInstantiations.size() &&
11061 "There should be an active template instantiation on the stack "
11062 "when instantiating a generic lambda!");
11063 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11066 // Enter a new function scope
11067 PushFunctionScope();
11069 // Builtin functions cannot be defined.
11070 if (unsigned BuiltinID = FD->getBuiltinID()) {
11071 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11072 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11073 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11074 FD->setInvalidDecl();
11078 // The return type of a function definition must be complete
11079 // (C99 6.9.1p3, C++ [dcl.fct]p6).
11080 QualType ResultType = FD->getReturnType();
11081 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11082 !FD->isInvalidDecl() &&
11083 RequireCompleteType(FD->getLocation(), ResultType,
11084 diag::err_func_def_incomplete_result))
11085 FD->setInvalidDecl();
11088 PushDeclContext(FnBodyScope, FD);
11090 // Check the validity of our function parameters
11091 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
11092 /*CheckParameterNames=*/true);
11094 // Introduce our parameters into the function scope
11095 for (auto Param : FD->params()) {
11096 Param->setOwningFunction(FD);
11098 // If this has an identifier, add it to the scope stack.
11099 if (Param->getIdentifier() && FnBodyScope) {
11100 CheckShadow(FnBodyScope, Param);
11102 PushOnScopeChains(Param, FnBodyScope);
11106 // If we had any tags defined in the function prototype,
11107 // introduce them into the function scope.
11109 for (ArrayRef<NamedDecl *>::iterator
11110 I = FD->getDeclsInPrototypeScope().begin(),
11111 E = FD->getDeclsInPrototypeScope().end();
11115 // Some of these decls (like enums) may have been pinned to the
11116 // translation unit for lack of a real context earlier. If so, remove
11117 // from the translation unit and reattach to the current context.
11118 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11119 // Is the decl actually in the context?
11120 if (Context.getTranslationUnitDecl()->containsDecl(D))
11121 Context.getTranslationUnitDecl()->removeDecl(D);
11122 // Either way, reassign the lexical decl context to our FunctionDecl.
11123 D->setLexicalDeclContext(CurContext);
11126 // If the decl has a non-null name, make accessible in the current scope.
11127 if (!D->getName().empty())
11128 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11130 // Similarly, dive into enums and fish their constants out, making them
11131 // accessible in this scope.
11132 if (auto *ED = dyn_cast<EnumDecl>(D)) {
11133 for (auto *EI : ED->enumerators())
11134 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11139 // Ensure that the function's exception specification is instantiated.
11140 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11141 ResolveExceptionSpec(D->getLocation(), FPT);
11143 // dllimport cannot be applied to non-inline function definitions.
11144 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11145 !FD->isTemplateInstantiation()) {
11146 assert(!FD->hasAttr<DLLExportAttr>());
11147 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11148 FD->setInvalidDecl();
11151 // We want to attach documentation to original Decl (which might be
11152 // a function template).
11153 ActOnDocumentableDecl(D);
11154 if (getCurLexicalContext()->isObjCContainer() &&
11155 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11156 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11157 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11162 /// \brief Given the set of return statements within a function body,
11163 /// compute the variables that are subject to the named return value
11166 /// Each of the variables that is subject to the named return value
11167 /// optimization will be marked as NRVO variables in the AST, and any
11168 /// return statement that has a marked NRVO variable as its NRVO candidate can
11169 /// use the named return value optimization.
11171 /// This function applies a very simplistic algorithm for NRVO: if every return
11172 /// statement in the scope of a variable has the same NRVO candidate, that
11173 /// candidate is an NRVO variable.
11174 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11175 ReturnStmt **Returns = Scope->Returns.data();
11177 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11178 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11179 if (!NRVOCandidate->isNRVOVariable())
11180 Returns[I]->setNRVOCandidate(nullptr);
11185 bool Sema::canDelayFunctionBody(const Declarator &D) {
11186 // We can't delay parsing the body of a constexpr function template (yet).
11187 if (D.getDeclSpec().isConstexprSpecified())
11190 // We can't delay parsing the body of a function template with a deduced
11191 // return type (yet).
11192 if (D.getDeclSpec().containsPlaceholderType()) {
11193 // If the placeholder introduces a non-deduced trailing return type,
11194 // we can still delay parsing it.
11195 if (D.getNumTypeObjects()) {
11196 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11197 if (Outer.Kind == DeclaratorChunk::Function &&
11198 Outer.Fun.hasTrailingReturnType()) {
11199 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11200 return Ty.isNull() || !Ty->isUndeducedType();
11209 bool Sema::canSkipFunctionBody(Decl *D) {
11210 // We cannot skip the body of a function (or function template) which is
11211 // constexpr, since we may need to evaluate its body in order to parse the
11212 // rest of the file.
11213 // We cannot skip the body of a function with an undeduced return type,
11214 // because any callers of that function need to know the type.
11215 if (const FunctionDecl *FD = D->getAsFunction())
11216 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11218 return Consumer.shouldSkipFunctionBody(D);
11221 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11222 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11223 FD->setHasSkippedBody();
11224 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11225 MD->setHasSkippedBody();
11226 return ActOnFinishFunctionBody(Decl, nullptr);
11229 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11230 return ActOnFinishFunctionBody(D, BodyArg, false);
11233 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11234 bool IsInstantiation) {
11235 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11237 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11238 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11240 if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11241 CheckCompletedCoroutineBody(FD, Body);
11246 if (getLangOpts().CPlusPlus14) {
11247 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11248 FD->getReturnType()->isUndeducedType()) {
11249 // If the function has a deduced result type but contains no 'return'
11250 // statements, the result type as written must be exactly 'auto', and
11251 // the deduced result type is 'void'.
11252 if (!FD->getReturnType()->getAs<AutoType>()) {
11253 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11254 << FD->getReturnType();
11255 FD->setInvalidDecl();
11257 // Substitute 'void' for the 'auto' in the type.
11258 TypeLoc ResultType = getReturnTypeLoc(FD);
11259 Context.adjustDeducedFunctionResultType(
11260 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11263 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11264 // In C++11, we don't use 'auto' deduction rules for lambda call
11265 // operators because we don't support return type deduction.
11266 auto *LSI = getCurLambda();
11267 if (LSI->HasImplicitReturnType) {
11268 deduceClosureReturnType(*LSI);
11270 // C++11 [expr.prim.lambda]p4:
11271 // [...] if there are no return statements in the compound-statement
11272 // [the deduced type is] the type void
11274 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11276 // Update the return type to the deduced type.
11277 const FunctionProtoType *Proto =
11278 FD->getType()->getAs<FunctionProtoType>();
11279 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11280 Proto->getExtProtoInfo()));
11284 // The only way to be included in UndefinedButUsed is if there is an
11285 // ODR use before the definition. Avoid the expensive map lookup if this
11286 // is the first declaration.
11287 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11288 if (!FD->isExternallyVisible())
11289 UndefinedButUsed.erase(FD);
11290 else if (FD->isInlined() &&
11291 !LangOpts.GNUInline &&
11292 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11293 UndefinedButUsed.erase(FD);
11296 // If the function implicitly returns zero (like 'main') or is naked,
11297 // don't complain about missing return statements.
11298 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11299 WP.disableCheckFallThrough();
11301 // MSVC permits the use of pure specifier (=0) on function definition,
11302 // defined at class scope, warn about this non-standard construct.
11303 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11304 Diag(FD->getLocation(), diag::ext_pure_function_definition);
11306 if (!FD->isInvalidDecl()) {
11307 // Don't diagnose unused parameters of defaulted or deleted functions.
11308 if (!FD->isDeleted() && !FD->isDefaulted())
11309 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11310 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11311 FD->getReturnType(), FD);
11313 // If this is a structor, we need a vtable.
11314 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11315 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11316 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11317 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11319 // Try to apply the named return value optimization. We have to check
11320 // if we can do this here because lambdas keep return statements around
11321 // to deduce an implicit return type.
11322 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11323 !FD->isDependentContext())
11324 computeNRVO(Body, getCurFunction());
11327 // GNU warning -Wmissing-prototypes:
11328 // Warn if a global function is defined without a previous
11329 // prototype declaration. This warning is issued even if the
11330 // definition itself provides a prototype. The aim is to detect
11331 // global functions that fail to be declared in header files.
11332 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11333 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11334 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11336 if (PossibleZeroParamPrototype) {
11337 // We found a declaration that is not a prototype,
11338 // but that could be a zero-parameter prototype
11339 if (TypeSourceInfo *TI =
11340 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11341 TypeLoc TL = TI->getTypeLoc();
11342 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11343 Diag(PossibleZeroParamPrototype->getLocation(),
11344 diag::note_declaration_not_a_prototype)
11345 << PossibleZeroParamPrototype
11346 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11351 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11352 const CXXMethodDecl *KeyFunction;
11353 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11355 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11356 MD == KeyFunction->getCanonicalDecl()) {
11357 // Update the key-function state if necessary for this ABI.
11358 if (FD->isInlined() &&
11359 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11360 Context.setNonKeyFunction(MD);
11362 // If the newly-chosen key function is already defined, then we
11363 // need to mark the vtable as used retroactively.
11364 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11365 const FunctionDecl *Definition;
11366 if (KeyFunction && KeyFunction->isDefined(Definition))
11367 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11369 // We just defined they key function; mark the vtable as used.
11370 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11375 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11376 "Function parsing confused");
11377 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11378 assert(MD == getCurMethodDecl() && "Method parsing confused");
11380 if (!MD->isInvalidDecl()) {
11381 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11382 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11383 MD->getReturnType(), MD);
11386 computeNRVO(Body, getCurFunction());
11388 if (getCurFunction()->ObjCShouldCallSuper) {
11389 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11390 << MD->getSelector().getAsString();
11391 getCurFunction()->ObjCShouldCallSuper = false;
11393 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11394 const ObjCMethodDecl *InitMethod = nullptr;
11395 bool isDesignated =
11396 MD->isDesignatedInitializerForTheInterface(&InitMethod);
11397 assert(isDesignated && InitMethod);
11398 (void)isDesignated;
11400 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11401 auto IFace = MD->getClassInterface();
11404 auto SuperD = IFace->getSuperClass();
11407 return SuperD->getIdentifier() ==
11408 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11410 // Don't issue this warning for unavailable inits or direct subclasses
11412 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11413 Diag(MD->getLocation(),
11414 diag::warn_objc_designated_init_missing_super_call);
11415 Diag(InitMethod->getLocation(),
11416 diag::note_objc_designated_init_marked_here);
11418 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11420 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11421 // Don't issue this warning for unavaialable inits.
11422 if (!MD->isUnavailable())
11423 Diag(MD->getLocation(),
11424 diag::warn_objc_secondary_init_missing_init_call);
11425 getCurFunction()->ObjCWarnForNoInitDelegation = false;
11431 assert(!getCurFunction()->ObjCShouldCallSuper &&
11432 "This should only be set for ObjC methods, which should have been "
11433 "handled in the block above.");
11435 // Verify and clean out per-function state.
11436 if (Body && (!FD || !FD->isDefaulted())) {
11437 // C++ constructors that have function-try-blocks can't have return
11438 // statements in the handlers of that block. (C++ [except.handle]p14)
11440 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11441 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11443 // Verify that gotos and switch cases don't jump into scopes illegally.
11444 if (getCurFunction()->NeedsScopeChecking() &&
11445 !PP.isCodeCompletionEnabled())
11446 DiagnoseInvalidJumps(Body);
11448 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11449 if (!Destructor->getParent()->isDependentType())
11450 CheckDestructor(Destructor);
11452 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11453 Destructor->getParent());
11456 // If any errors have occurred, clear out any temporaries that may have
11457 // been leftover. This ensures that these temporaries won't be picked up for
11458 // deletion in some later function.
11459 if (getDiagnostics().hasErrorOccurred() ||
11460 getDiagnostics().getSuppressAllDiagnostics()) {
11461 DiscardCleanupsInEvaluationContext();
11463 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11464 !isa<FunctionTemplateDecl>(dcl)) {
11465 // Since the body is valid, issue any analysis-based warnings that are
11467 ActivePolicy = &WP;
11470 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11471 (!CheckConstexprFunctionDecl(FD) ||
11472 !CheckConstexprFunctionBody(FD, Body)))
11473 FD->setInvalidDecl();
11475 if (FD && FD->hasAttr<NakedAttr>()) {
11476 for (const Stmt *S : Body->children()) {
11477 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11478 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11479 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11480 FD->setInvalidDecl();
11486 assert(ExprCleanupObjects.size() ==
11487 ExprEvalContexts.back().NumCleanupObjects &&
11488 "Leftover temporaries in function");
11489 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11490 assert(MaybeODRUseExprs.empty() &&
11491 "Leftover expressions for odr-use checking");
11494 if (!IsInstantiation)
11497 PopFunctionScopeInfo(ActivePolicy, dcl);
11498 // If any errors have occurred, clear out any temporaries that may have
11499 // been leftover. This ensures that these temporaries won't be picked up for
11500 // deletion in some later function.
11501 if (getDiagnostics().hasErrorOccurred()) {
11502 DiscardCleanupsInEvaluationContext();
11508 /// When we finish delayed parsing of an attribute, we must attach it to the
11510 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11511 ParsedAttributes &Attrs) {
11512 // Always attach attributes to the underlying decl.
11513 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11514 D = TD->getTemplatedDecl();
11515 ProcessDeclAttributeList(S, D, Attrs.getList());
11517 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11518 if (Method->isStatic())
11519 checkThisInStaticMemberFunctionAttributes(Method);
11522 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11523 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11524 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11525 IdentifierInfo &II, Scope *S) {
11526 // Before we produce a declaration for an implicitly defined
11527 // function, see whether there was a locally-scoped declaration of
11528 // this name as a function or variable. If so, use that
11529 // (non-visible) declaration, and complain about it.
11530 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11531 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11532 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11533 return ExternCPrev;
11536 // Extension in C99. Legal in C90, but warn about it.
11538 if (II.getName().startswith("__builtin_"))
11539 diag_id = diag::warn_builtin_unknown;
11540 else if (getLangOpts().C99)
11541 diag_id = diag::ext_implicit_function_decl;
11543 diag_id = diag::warn_implicit_function_decl;
11544 Diag(Loc, diag_id) << &II;
11546 // Because typo correction is expensive, only do it if the implicit
11547 // function declaration is going to be treated as an error.
11548 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11549 TypoCorrection Corrected;
11551 (Corrected = CorrectTypo(
11552 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11553 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11554 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11555 /*ErrorRecovery*/false);
11558 // Set a Declarator for the implicit definition: int foo();
11560 AttributeFactory attrFactory;
11561 DeclSpec DS(attrFactory);
11563 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11564 Context.getPrintingPolicy());
11565 (void)Error; // Silence warning.
11566 assert(!Error && "Error setting up implicit decl!");
11567 SourceLocation NoLoc;
11568 Declarator D(DS, Declarator::BlockContext);
11569 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11570 /*IsAmbiguous=*/false,
11571 /*LParenLoc=*/NoLoc,
11572 /*Params=*/nullptr,
11574 /*EllipsisLoc=*/NoLoc,
11575 /*RParenLoc=*/NoLoc,
11577 /*RefQualifierIsLvalueRef=*/true,
11578 /*RefQualifierLoc=*/NoLoc,
11579 /*ConstQualifierLoc=*/NoLoc,
11580 /*VolatileQualifierLoc=*/NoLoc,
11581 /*RestrictQualifierLoc=*/NoLoc,
11582 /*MutableLoc=*/NoLoc,
11584 /*ESpecRange=*/SourceRange(),
11585 /*Exceptions=*/nullptr,
11586 /*ExceptionRanges=*/nullptr,
11587 /*NumExceptions=*/0,
11588 /*NoexceptExpr=*/nullptr,
11589 /*ExceptionSpecTokens=*/nullptr,
11591 DS.getAttributes(),
11593 D.SetIdentifier(&II, Loc);
11595 // Insert this function into translation-unit scope.
11597 DeclContext *PrevDC = CurContext;
11598 CurContext = Context.getTranslationUnitDecl();
11600 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11603 CurContext = PrevDC;
11605 AddKnownFunctionAttributes(FD);
11610 /// \brief Adds any function attributes that we know a priori based on
11611 /// the declaration of this function.
11613 /// These attributes can apply both to implicitly-declared builtins
11614 /// (like __builtin___printf_chk) or to library-declared functions
11615 /// like NSLog or printf.
11617 /// We need to check for duplicate attributes both here and where user-written
11618 /// attributes are applied to declarations.
11619 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11620 if (FD->isInvalidDecl())
11623 // If this is a built-in function, map its builtin attributes to
11624 // actual attributes.
11625 if (unsigned BuiltinID = FD->getBuiltinID()) {
11626 // Handle printf-formatting attributes.
11627 unsigned FormatIdx;
11629 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11630 if (!FD->hasAttr<FormatAttr>()) {
11631 const char *fmt = "printf";
11632 unsigned int NumParams = FD->getNumParams();
11633 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11634 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11636 FD->addAttr(FormatAttr::CreateImplicit(Context,
11637 &Context.Idents.get(fmt),
11639 HasVAListArg ? 0 : FormatIdx+2,
11640 FD->getLocation()));
11643 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11645 if (!FD->hasAttr<FormatAttr>())
11646 FD->addAttr(FormatAttr::CreateImplicit(Context,
11647 &Context.Idents.get("scanf"),
11649 HasVAListArg ? 0 : FormatIdx+2,
11650 FD->getLocation()));
11653 // Mark const if we don't care about errno and that is the only
11654 // thing preventing the function from being const. This allows
11655 // IRgen to use LLVM intrinsics for such functions.
11656 if (!getLangOpts().MathErrno &&
11657 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11658 if (!FD->hasAttr<ConstAttr>())
11659 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11662 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11663 !FD->hasAttr<ReturnsTwiceAttr>())
11664 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11665 FD->getLocation()));
11666 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11667 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11668 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11669 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11670 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads &&
11671 Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11672 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11673 // Assign appropriate attribute depending on CUDA compilation
11674 // mode and the target builtin belongs to. E.g. during host
11675 // compilation, aux builtins are __device__, the rest are __host__.
11676 if (getLangOpts().CUDAIsDevice !=
11677 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11678 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11680 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11684 // If C++ exceptions are enabled but we are told extern "C" functions cannot
11685 // throw, add an implicit nothrow attribute to any extern "C" function we come
11687 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11688 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
11689 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
11690 if (!FPT || FPT->getExceptionSpecType() == EST_None)
11691 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11694 IdentifierInfo *Name = FD->getIdentifier();
11697 if ((!getLangOpts().CPlusPlus &&
11698 FD->getDeclContext()->isTranslationUnit()) ||
11699 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11700 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11701 LinkageSpecDecl::lang_c)) {
11702 // Okay: this could be a libc/libm/Objective-C function we know
11707 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11708 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11709 // target-specific builtins, perhaps?
11710 if (!FD->hasAttr<FormatAttr>())
11711 FD->addAttr(FormatAttr::CreateImplicit(Context,
11712 &Context.Idents.get("printf"), 2,
11713 Name->isStr("vasprintf") ? 0 : 3,
11714 FD->getLocation()));
11717 if (Name->isStr("__CFStringMakeConstantString")) {
11718 // We already have a __builtin___CFStringMakeConstantString,
11719 // but builds that use -fno-constant-cfstrings don't go through that.
11720 if (!FD->hasAttr<FormatArgAttr>())
11721 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11722 FD->getLocation()));
11726 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11727 TypeSourceInfo *TInfo) {
11728 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11729 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11732 assert(D.isInvalidType() && "no declarator info for valid type");
11733 TInfo = Context.getTrivialTypeSourceInfo(T);
11736 // Scope manipulation handled by caller.
11737 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11739 D.getIdentifierLoc(),
11743 // Bail out immediately if we have an invalid declaration.
11744 if (D.isInvalidType()) {
11745 NewTD->setInvalidDecl();
11749 if (D.getDeclSpec().isModulePrivateSpecified()) {
11750 if (CurContext->isFunctionOrMethod())
11751 Diag(NewTD->getLocation(), diag::err_module_private_local)
11752 << 2 << NewTD->getDeclName()
11753 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11754 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11756 NewTD->setModulePrivate();
11759 // C++ [dcl.typedef]p8:
11760 // If the typedef declaration defines an unnamed class (or
11761 // enum), the first typedef-name declared by the declaration
11762 // to be that class type (or enum type) is used to denote the
11763 // class type (or enum type) for linkage purposes only.
11764 // We need to check whether the type was declared in the declaration.
11765 switch (D.getDeclSpec().getTypeSpecType()) {
11768 case TST_interface:
11771 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11772 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11783 /// \brief Check that this is a valid underlying type for an enum declaration.
11784 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11785 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11786 QualType T = TI->getType();
11788 if (T->isDependentType())
11791 if (const BuiltinType *BT = T->getAs<BuiltinType>())
11792 if (BT->isInteger())
11795 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11799 /// Check whether this is a valid redeclaration of a previous enumeration.
11800 /// \return true if the redeclaration was invalid.
11801 bool Sema::CheckEnumRedeclaration(
11802 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11803 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11804 bool IsFixed = !EnumUnderlyingTy.isNull();
11806 if (IsScoped != Prev->isScoped()) {
11807 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11808 << Prev->isScoped();
11809 Diag(Prev->getLocation(), diag::note_previous_declaration);
11813 if (IsFixed && Prev->isFixed()) {
11814 if (!EnumUnderlyingTy->isDependentType() &&
11815 !Prev->getIntegerType()->isDependentType() &&
11816 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11817 Prev->getIntegerType())) {
11818 // TODO: Highlight the underlying type of the redeclaration.
11819 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11820 << EnumUnderlyingTy << Prev->getIntegerType();
11821 Diag(Prev->getLocation(), diag::note_previous_declaration)
11822 << Prev->getIntegerTypeRange();
11825 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11827 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11829 } else if (IsFixed != Prev->isFixed()) {
11830 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11831 << Prev->isFixed();
11832 Diag(Prev->getLocation(), diag::note_previous_declaration);
11839 /// \brief Get diagnostic %select index for tag kind for
11840 /// redeclaration diagnostic message.
11841 /// WARNING: Indexes apply to particular diagnostics only!
11843 /// \returns diagnostic %select index.
11844 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11846 case TTK_Struct: return 0;
11847 case TTK_Interface: return 1;
11848 case TTK_Class: return 2;
11849 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11853 /// \brief Determine if tag kind is a class-key compatible with
11854 /// class for redeclaration (class, struct, or __interface).
11856 /// \returns true iff the tag kind is compatible.
11857 static bool isClassCompatTagKind(TagTypeKind Tag)
11859 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11862 /// \brief Determine whether a tag with a given kind is acceptable
11863 /// as a redeclaration of the given tag declaration.
11865 /// \returns true if the new tag kind is acceptable, false otherwise.
11866 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11867 TagTypeKind NewTag, bool isDefinition,
11868 SourceLocation NewTagLoc,
11869 const IdentifierInfo *Name) {
11870 // C++ [dcl.type.elab]p3:
11871 // The class-key or enum keyword present in the
11872 // elaborated-type-specifier shall agree in kind with the
11873 // declaration to which the name in the elaborated-type-specifier
11874 // refers. This rule also applies to the form of
11875 // elaborated-type-specifier that declares a class-name or
11876 // friend class since it can be construed as referring to the
11877 // definition of the class. Thus, in any
11878 // elaborated-type-specifier, the enum keyword shall be used to
11879 // refer to an enumeration (7.2), the union class-key shall be
11880 // used to refer to a union (clause 9), and either the class or
11881 // struct class-key shall be used to refer to a class (clause 9)
11882 // declared using the class or struct class-key.
11883 TagTypeKind OldTag = Previous->getTagKind();
11884 if (!isDefinition || !isClassCompatTagKind(NewTag))
11885 if (OldTag == NewTag)
11888 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11889 // Warn about the struct/class tag mismatch.
11890 bool isTemplate = false;
11891 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11892 isTemplate = Record->getDescribedClassTemplate();
11894 if (!ActiveTemplateInstantiations.empty()) {
11895 // In a template instantiation, do not offer fix-its for tag mismatches
11896 // since they usually mess up the template instead of fixing the problem.
11897 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11898 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11899 << getRedeclDiagFromTagKind(OldTag);
11903 if (isDefinition) {
11904 // On definitions, check previous tags and issue a fix-it for each
11905 // one that doesn't match the current tag.
11906 if (Previous->getDefinition()) {
11907 // Don't suggest fix-its for redefinitions.
11911 bool previousMismatch = false;
11912 for (auto I : Previous->redecls()) {
11913 if (I->getTagKind() != NewTag) {
11914 if (!previousMismatch) {
11915 previousMismatch = true;
11916 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11917 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11918 << getRedeclDiagFromTagKind(I->getTagKind());
11920 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11921 << getRedeclDiagFromTagKind(NewTag)
11922 << FixItHint::CreateReplacement(I->getInnerLocStart(),
11923 TypeWithKeyword::getTagTypeKindName(NewTag));
11929 // Check for a previous definition. If current tag and definition
11930 // are same type, do nothing. If no definition, but disagree with
11931 // with previous tag type, give a warning, but no fix-it.
11932 const TagDecl *Redecl = Previous->getDefinition() ?
11933 Previous->getDefinition() : Previous;
11934 if (Redecl->getTagKind() == NewTag) {
11938 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11939 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11940 << getRedeclDiagFromTagKind(OldTag);
11941 Diag(Redecl->getLocation(), diag::note_previous_use);
11943 // If there is a previous definition, suggest a fix-it.
11944 if (Previous->getDefinition()) {
11945 Diag(NewTagLoc, diag::note_struct_class_suggestion)
11946 << getRedeclDiagFromTagKind(Redecl->getTagKind())
11947 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11948 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11956 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11957 /// from an outer enclosing namespace or file scope inside a friend declaration.
11958 /// This should provide the commented out code in the following snippet:
11962 /// struct Y { friend struct /*N::*/ X; };
11965 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11966 SourceLocation NameLoc) {
11967 // While the decl is in a namespace, do repeated lookup of that name and see
11968 // if we get the same namespace back. If we do not, continue until
11969 // translation unit scope, at which point we have a fully qualified NNS.
11970 SmallVector<IdentifierInfo *, 4> Namespaces;
11971 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11972 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11973 // This tag should be declared in a namespace, which can only be enclosed by
11974 // other namespaces. Bail if there's an anonymous namespace in the chain.
11975 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11976 if (!Namespace || Namespace->isAnonymousNamespace())
11977 return FixItHint();
11978 IdentifierInfo *II = Namespace->getIdentifier();
11979 Namespaces.push_back(II);
11980 NamedDecl *Lookup = SemaRef.LookupSingleName(
11981 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11982 if (Lookup == Namespace)
11986 // Once we have all the namespaces, reverse them to go outermost first, and
11988 SmallString<64> Insertion;
11989 llvm::raw_svector_ostream OS(Insertion);
11990 if (DC->isTranslationUnit())
11992 std::reverse(Namespaces.begin(), Namespaces.end());
11993 for (auto *II : Namespaces)
11994 OS << II->getName() << "::";
11995 return FixItHint::CreateInsertion(NameLoc, Insertion);
11998 /// \brief Determine whether a tag originally declared in context \p OldDC can
11999 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12000 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12001 /// using-declaration).
12002 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12003 DeclContext *NewDC) {
12004 OldDC = OldDC->getRedeclContext();
12005 NewDC = NewDC->getRedeclContext();
12007 if (OldDC->Equals(NewDC))
12010 // In MSVC mode, we allow a redeclaration if the contexts are related (either
12011 // encloses the other).
12012 if (S.getLangOpts().MSVCCompat &&
12013 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12019 /// Find the DeclContext in which a tag is implicitly declared if we see an
12020 /// elaborated type specifier in the specified context, and lookup finds
12022 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12023 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12024 DC = DC->getParent();
12028 /// Find the Scope in which a tag is implicitly declared if we see an
12029 /// elaborated type specifier in the specified context, and lookup finds
12031 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12032 while (S->isClassScope() ||
12033 (LangOpts.CPlusPlus &&
12034 S->isFunctionPrototypeScope()) ||
12035 ((S->getFlags() & Scope::DeclScope) == 0) ||
12036 (S->getEntity() && S->getEntity()->isTransparentContext()))
12037 S = S->getParent();
12041 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
12042 /// former case, Name will be non-null. In the later case, Name will be null.
12043 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12044 /// reference/declaration/definition of a tag.
12046 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12047 /// trailing-type-specifier) other than one in an alias-declaration.
12049 /// \param SkipBody If non-null, will be set to indicate if the caller should
12050 /// skip the definition of this tag and treat it as if it were a declaration.
12051 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12052 SourceLocation KWLoc, CXXScopeSpec &SS,
12053 IdentifierInfo *Name, SourceLocation NameLoc,
12054 AttributeList *Attr, AccessSpecifier AS,
12055 SourceLocation ModulePrivateLoc,
12056 MultiTemplateParamsArg TemplateParameterLists,
12057 bool &OwnedDecl, bool &IsDependent,
12058 SourceLocation ScopedEnumKWLoc,
12059 bool ScopedEnumUsesClassTag,
12060 TypeResult UnderlyingType,
12061 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12062 // If this is not a definition, it must have a name.
12063 IdentifierInfo *OrigName = Name;
12064 assert((Name != nullptr || TUK == TUK_Definition) &&
12065 "Nameless record must be a definition!");
12066 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12069 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12070 bool ScopedEnum = ScopedEnumKWLoc.isValid();
12072 // FIXME: Check explicit specializations more carefully.
12073 bool isExplicitSpecialization = false;
12074 bool Invalid = false;
12076 // We only need to do this matching if we have template parameters
12077 // or a scope specifier, which also conveniently avoids this work
12078 // for non-C++ cases.
12079 if (TemplateParameterLists.size() > 0 ||
12080 (SS.isNotEmpty() && TUK != TUK_Reference)) {
12081 if (TemplateParameterList *TemplateParams =
12082 MatchTemplateParametersToScopeSpecifier(
12083 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12084 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12085 if (Kind == TTK_Enum) {
12086 Diag(KWLoc, diag::err_enum_template);
12090 if (TemplateParams->size() > 0) {
12091 // This is a declaration or definition of a class template (which may
12092 // be a member of another template).
12098 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12099 SS, Name, NameLoc, Attr,
12100 TemplateParams, AS,
12102 /*FriendLoc*/SourceLocation(),
12103 TemplateParameterLists.size()-1,
12104 TemplateParameterLists.data(),
12106 return Result.get();
12108 // The "template<>" header is extraneous.
12109 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12110 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12111 isExplicitSpecialization = true;
12116 // Figure out the underlying type if this a enum declaration. We need to do
12117 // this early, because it's needed to detect if this is an incompatible
12119 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12120 bool EnumUnderlyingIsImplicit = false;
12122 if (Kind == TTK_Enum) {
12123 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12124 // No underlying type explicitly specified, or we failed to parse the
12125 // type, default to int.
12126 EnumUnderlying = Context.IntTy.getTypePtr();
12127 else if (UnderlyingType.get()) {
12128 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12129 // integral type; any cv-qualification is ignored.
12130 TypeSourceInfo *TI = nullptr;
12131 GetTypeFromParser(UnderlyingType.get(), &TI);
12132 EnumUnderlying = TI;
12134 if (CheckEnumUnderlyingType(TI))
12135 // Recover by falling back to int.
12136 EnumUnderlying = Context.IntTy.getTypePtr();
12138 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12139 UPPC_FixedUnderlyingType))
12140 EnumUnderlying = Context.IntTy.getTypePtr();
12142 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12143 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12144 // Microsoft enums are always of int type.
12145 EnumUnderlying = Context.IntTy.getTypePtr();
12146 EnumUnderlyingIsImplicit = true;
12151 DeclContext *SearchDC = CurContext;
12152 DeclContext *DC = CurContext;
12153 bool isStdBadAlloc = false;
12155 RedeclarationKind Redecl = ForRedeclaration;
12156 if (TUK == TUK_Friend || TUK == TUK_Reference)
12157 Redecl = NotForRedeclaration;
12159 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12160 if (Name && SS.isNotEmpty()) {
12161 // We have a nested-name tag ('struct foo::bar').
12163 // Check for invalid 'foo::'.
12164 if (SS.isInvalid()) {
12166 goto CreateNewDecl;
12169 // If this is a friend or a reference to a class in a dependent
12170 // context, don't try to make a decl for it.
12171 if (TUK == TUK_Friend || TUK == TUK_Reference) {
12172 DC = computeDeclContext(SS, false);
12174 IsDependent = true;
12178 DC = computeDeclContext(SS, true);
12180 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12186 if (RequireCompleteDeclContext(SS, DC))
12190 // Look-up name inside 'foo::'.
12191 LookupQualifiedName(Previous, DC);
12193 if (Previous.isAmbiguous())
12196 if (Previous.empty()) {
12197 // Name lookup did not find anything. However, if the
12198 // nested-name-specifier refers to the current instantiation,
12199 // and that current instantiation has any dependent base
12200 // classes, we might find something at instantiation time: treat
12201 // this as a dependent elaborated-type-specifier.
12202 // But this only makes any sense for reference-like lookups.
12203 if (Previous.wasNotFoundInCurrentInstantiation() &&
12204 (TUK == TUK_Reference || TUK == TUK_Friend)) {
12205 IsDependent = true;
12209 // A tag 'foo::bar' must already exist.
12210 Diag(NameLoc, diag::err_not_tag_in_scope)
12211 << Kind << Name << DC << SS.getRange();
12214 goto CreateNewDecl;
12217 // C++14 [class.mem]p14:
12218 // If T is the name of a class, then each of the following shall have a
12219 // name different from T:
12220 // -- every member of class T that is itself a type
12221 if (TUK != TUK_Reference && TUK != TUK_Friend &&
12222 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12225 // If this is a named struct, check to see if there was a previous forward
12226 // declaration or definition.
12227 // FIXME: We're looking into outer scopes here, even when we
12228 // shouldn't be. Doing so can result in ambiguities that we
12229 // shouldn't be diagnosing.
12230 LookupName(Previous, S);
12232 // When declaring or defining a tag, ignore ambiguities introduced
12233 // by types using'ed into this scope.
12234 if (Previous.isAmbiguous() &&
12235 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12236 LookupResult::Filter F = Previous.makeFilter();
12237 while (F.hasNext()) {
12238 NamedDecl *ND = F.next();
12239 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
12245 // C++11 [namespace.memdef]p3:
12246 // If the name in a friend declaration is neither qualified nor
12247 // a template-id and the declaration is a function or an
12248 // elaborated-type-specifier, the lookup to determine whether
12249 // the entity has been previously declared shall not consider
12250 // any scopes outside the innermost enclosing namespace.
12252 // MSVC doesn't implement the above rule for types, so a friend tag
12253 // declaration may be a redeclaration of a type declared in an enclosing
12254 // scope. They do implement this rule for friend functions.
12256 // Does it matter that this should be by scope instead of by
12257 // semantic context?
12258 if (!Previous.empty() && TUK == TUK_Friend) {
12259 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12260 LookupResult::Filter F = Previous.makeFilter();
12261 bool FriendSawTagOutsideEnclosingNamespace = false;
12262 while (F.hasNext()) {
12263 NamedDecl *ND = F.next();
12264 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12265 if (DC->isFileContext() &&
12266 !EnclosingNS->Encloses(ND->getDeclContext())) {
12267 if (getLangOpts().MSVCCompat)
12268 FriendSawTagOutsideEnclosingNamespace = true;
12275 // Diagnose this MSVC extension in the easy case where lookup would have
12276 // unambiguously found something outside the enclosing namespace.
12277 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12278 NamedDecl *ND = Previous.getFoundDecl();
12279 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12280 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12284 // Note: there used to be some attempt at recovery here.
12285 if (Previous.isAmbiguous())
12288 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12289 // FIXME: This makes sure that we ignore the contexts associated
12290 // with C structs, unions, and enums when looking for a matching
12291 // tag declaration or definition. See the similar lookup tweak
12292 // in Sema::LookupName; is there a better way to deal with this?
12293 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12294 SearchDC = SearchDC->getParent();
12298 if (Previous.isSingleResult() &&
12299 Previous.getFoundDecl()->isTemplateParameter()) {
12300 // Maybe we will complain about the shadowed template parameter.
12301 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12302 // Just pretend that we didn't see the previous declaration.
12306 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12307 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12308 // This is a declaration of or a reference to "std::bad_alloc".
12309 isStdBadAlloc = true;
12311 if (Previous.empty() && StdBadAlloc) {
12312 // std::bad_alloc has been implicitly declared (but made invisible to
12313 // name lookup). Fill in this implicit declaration as the previous
12314 // declaration, so that the declarations get chained appropriately.
12315 Previous.addDecl(getStdBadAlloc());
12319 // If we didn't find a previous declaration, and this is a reference
12320 // (or friend reference), move to the correct scope. In C++, we
12321 // also need to do a redeclaration lookup there, just in case
12322 // there's a shadow friend decl.
12323 if (Name && Previous.empty() &&
12324 (TUK == TUK_Reference || TUK == TUK_Friend)) {
12325 if (Invalid) goto CreateNewDecl;
12326 assert(SS.isEmpty());
12328 if (TUK == TUK_Reference) {
12329 // C++ [basic.scope.pdecl]p5:
12330 // -- for an elaborated-type-specifier of the form
12332 // class-key identifier
12334 // if the elaborated-type-specifier is used in the
12335 // decl-specifier-seq or parameter-declaration-clause of a
12336 // function defined in namespace scope, the identifier is
12337 // declared as a class-name in the namespace that contains
12338 // the declaration; otherwise, except as a friend
12339 // declaration, the identifier is declared in the smallest
12340 // non-class, non-function-prototype scope that contains the
12343 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12344 // C structs and unions.
12346 // It is an error in C++ to declare (rather than define) an enum
12347 // type, including via an elaborated type specifier. We'll
12348 // diagnose that later; for now, declare the enum in the same
12349 // scope as we would have picked for any other tag type.
12351 // GNU C also supports this behavior as part of its incomplete
12352 // enum types extension, while GNU C++ does not.
12354 // Find the context where we'll be declaring the tag.
12355 // FIXME: We would like to maintain the current DeclContext as the
12356 // lexical context,
12357 SearchDC = getTagInjectionContext(SearchDC);
12359 // Find the scope where we'll be declaring the tag.
12360 S = getTagInjectionScope(S, getLangOpts());
12362 assert(TUK == TUK_Friend);
12363 // C++ [namespace.memdef]p3:
12364 // If a friend declaration in a non-local class first declares a
12365 // class or function, the friend class or function is a member of
12366 // the innermost enclosing namespace.
12367 SearchDC = SearchDC->getEnclosingNamespaceContext();
12370 // In C++, we need to do a redeclaration lookup to properly
12371 // diagnose some problems.
12372 // FIXME: redeclaration lookup is also used (with and without C++) to find a
12373 // hidden declaration so that we don't get ambiguity errors when using a
12374 // type declared by an elaborated-type-specifier. In C that is not correct
12375 // and we should instead merge compatible types found by lookup.
12376 if (getLangOpts().CPlusPlus) {
12377 Previous.setRedeclarationKind(ForRedeclaration);
12378 LookupQualifiedName(Previous, SearchDC);
12380 Previous.setRedeclarationKind(ForRedeclaration);
12381 LookupName(Previous, S);
12385 // If we have a known previous declaration to use, then use it.
12386 if (Previous.empty() && SkipBody && SkipBody->Previous)
12387 Previous.addDecl(SkipBody->Previous);
12389 if (!Previous.empty()) {
12390 NamedDecl *PrevDecl = Previous.getFoundDecl();
12391 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12393 // It's okay to have a tag decl in the same scope as a typedef
12394 // which hides a tag decl in the same scope. Finding this
12395 // insanity with a redeclaration lookup can only actually happen
12398 // This is also okay for elaborated-type-specifiers, which is
12399 // technically forbidden by the current standard but which is
12400 // okay according to the likely resolution of an open issue;
12401 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12402 if (getLangOpts().CPlusPlus) {
12403 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12404 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12405 TagDecl *Tag = TT->getDecl();
12406 if (Tag->getDeclName() == Name &&
12407 Tag->getDeclContext()->getRedeclContext()
12408 ->Equals(TD->getDeclContext()->getRedeclContext())) {
12411 Previous.addDecl(Tag);
12412 Previous.resolveKind();
12418 // If this is a redeclaration of a using shadow declaration, it must
12419 // declare a tag in the same context. In MSVC mode, we allow a
12420 // redefinition if either context is within the other.
12421 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12422 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12423 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12424 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12425 !(OldTag && isAcceptableTagRedeclContext(
12426 *this, OldTag->getDeclContext(), SearchDC))) {
12427 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12428 Diag(Shadow->getTargetDecl()->getLocation(),
12429 diag::note_using_decl_target);
12430 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12432 // Recover by ignoring the old declaration.
12434 goto CreateNewDecl;
12438 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12439 // If this is a use of a previous tag, or if the tag is already declared
12440 // in the same scope (so that the definition/declaration completes or
12441 // rementions the tag), reuse the decl.
12442 if (TUK == TUK_Reference || TUK == TUK_Friend ||
12443 isDeclInScope(DirectPrevDecl, SearchDC, S,
12444 SS.isNotEmpty() || isExplicitSpecialization)) {
12445 // Make sure that this wasn't declared as an enum and now used as a
12446 // struct or something similar.
12447 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12448 TUK == TUK_Definition, KWLoc,
12450 bool SafeToContinue
12451 = (PrevTagDecl->getTagKind() != TTK_Enum &&
12453 if (SafeToContinue)
12454 Diag(KWLoc, diag::err_use_with_wrong_tag)
12456 << FixItHint::CreateReplacement(SourceRange(KWLoc),
12457 PrevTagDecl->getKindName());
12459 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12460 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12462 if (SafeToContinue)
12463 Kind = PrevTagDecl->getTagKind();
12465 // Recover by making this an anonymous redefinition.
12472 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12473 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12475 // If this is an elaborated-type-specifier for a scoped enumeration,
12476 // the 'class' keyword is not necessary and not permitted.
12477 if (TUK == TUK_Reference || TUK == TUK_Friend) {
12479 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12480 << PrevEnum->isScoped()
12481 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12482 return PrevTagDecl;
12485 QualType EnumUnderlyingTy;
12486 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12487 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12488 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12489 EnumUnderlyingTy = QualType(T, 0);
12491 // All conflicts with previous declarations are recovered by
12492 // returning the previous declaration, unless this is a definition,
12493 // in which case we want the caller to bail out.
12494 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12495 ScopedEnum, EnumUnderlyingTy,
12496 EnumUnderlyingIsImplicit, PrevEnum))
12497 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12500 // C++11 [class.mem]p1:
12501 // A member shall not be declared twice in the member-specification,
12502 // except that a nested class or member class template can be declared
12503 // and then later defined.
12504 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12505 S->isDeclScope(PrevDecl)) {
12506 Diag(NameLoc, diag::ext_member_redeclared);
12507 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12511 // If this is a use, just return the declaration we found, unless
12512 // we have attributes.
12513 if (TUK == TUK_Reference || TUK == TUK_Friend) {
12515 // FIXME: Diagnose these attributes. For now, we create a new
12516 // declaration to hold them.
12517 } else if (TUK == TUK_Reference &&
12518 (PrevTagDecl->getFriendObjectKind() ==
12519 Decl::FOK_Undeclared ||
12520 PP.getModuleContainingLocation(
12521 PrevDecl->getLocation()) !=
12522 PP.getModuleContainingLocation(KWLoc)) &&
12524 // This declaration is a reference to an existing entity, but
12525 // has different visibility from that entity: it either makes
12526 // a friend visible or it makes a type visible in a new module.
12527 // In either case, create a new declaration. We only do this if
12528 // the declaration would have meant the same thing if no prior
12529 // declaration were found, that is, if it was found in the same
12530 // scope where we would have injected a declaration.
12531 if (!getTagInjectionContext(CurContext)->getRedeclContext()
12532 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12533 return PrevTagDecl;
12534 // This is in the injected scope, create a new declaration in
12536 S = getTagInjectionScope(S, getLangOpts());
12538 return PrevTagDecl;
12542 // Diagnose attempts to redefine a tag.
12543 if (TUK == TUK_Definition) {
12544 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12545 // If we're defining a specialization and the previous definition
12546 // is from an implicit instantiation, don't emit an error
12547 // here; we'll catch this in the general case below.
12548 bool IsExplicitSpecializationAfterInstantiation = false;
12549 if (isExplicitSpecialization) {
12550 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12551 IsExplicitSpecializationAfterInstantiation =
12552 RD->getTemplateSpecializationKind() !=
12553 TSK_ExplicitSpecialization;
12554 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12555 IsExplicitSpecializationAfterInstantiation =
12556 ED->getTemplateSpecializationKind() !=
12557 TSK_ExplicitSpecialization;
12560 NamedDecl *Hidden = nullptr;
12561 if (SkipBody && getLangOpts().CPlusPlus &&
12562 !hasVisibleDefinition(Def, &Hidden)) {
12563 // There is a definition of this tag, but it is not visible. We
12564 // explicitly make use of C++'s one definition rule here, and
12565 // assume that this definition is identical to the hidden one
12566 // we already have. Make the existing definition visible and
12567 // use it in place of this one.
12568 SkipBody->ShouldSkip = true;
12569 makeMergedDefinitionVisible(Hidden, KWLoc);
12571 } else if (!IsExplicitSpecializationAfterInstantiation) {
12572 // A redeclaration in function prototype scope in C isn't
12573 // visible elsewhere, so merely issue a warning.
12574 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12575 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12577 Diag(NameLoc, diag::err_redefinition) << Name;
12578 Diag(Def->getLocation(), diag::note_previous_definition);
12579 // If this is a redefinition, recover by making this
12580 // struct be anonymous, which will make any later
12581 // references get the previous definition.
12587 // If the type is currently being defined, complain
12588 // about a nested redefinition.
12589 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12590 if (TD->isBeingDefined()) {
12591 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12592 Diag(PrevTagDecl->getLocation(),
12593 diag::note_previous_definition);
12600 // Okay, this is definition of a previously declared or referenced
12601 // tag. We're going to create a new Decl for it.
12604 // Okay, we're going to make a redeclaration. If this is some kind
12605 // of reference, make sure we build the redeclaration in the same DC
12606 // as the original, and ignore the current access specifier.
12607 if (TUK == TUK_Friend || TUK == TUK_Reference) {
12608 SearchDC = PrevTagDecl->getDeclContext();
12612 // If we get here we have (another) forward declaration or we
12613 // have a definition. Just create a new decl.
12616 // If we get here, this is a definition of a new tag type in a nested
12617 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12618 // new decl/type. We set PrevDecl to NULL so that the entities
12619 // have distinct types.
12622 // If we get here, we're going to create a new Decl. If PrevDecl
12623 // is non-NULL, it's a definition of the tag declared by
12624 // PrevDecl. If it's NULL, we have a new definition.
12626 // Otherwise, PrevDecl is not a tag, but was found with tag
12627 // lookup. This is only actually possible in C++, where a few
12628 // things like templates still live in the tag namespace.
12630 // Use a better diagnostic if an elaborated-type-specifier
12631 // found the wrong kind of type on the first
12632 // (non-redeclaration) lookup.
12633 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12634 !Previous.isForRedeclaration()) {
12636 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12637 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12638 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12639 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12640 Diag(PrevDecl->getLocation(), diag::note_declared_at);
12643 // Otherwise, only diagnose if the declaration is in scope.
12644 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12645 SS.isNotEmpty() || isExplicitSpecialization)) {
12648 // Diagnose implicit declarations introduced by elaborated types.
12649 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12651 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12652 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12653 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12654 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12655 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12658 // Otherwise it's a declaration. Call out a particularly common
12660 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12662 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12663 Diag(NameLoc, diag::err_tag_definition_of_typedef)
12664 << Name << Kind << TND->getUnderlyingType();
12665 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12668 // Otherwise, diagnose.
12670 // The tag name clashes with something else in the target scope,
12671 // issue an error and recover by making this tag be anonymous.
12672 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12673 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12678 // The existing declaration isn't relevant to us; we're in a
12679 // new scope, so clear out the previous declaration.
12686 TagDecl *PrevDecl = nullptr;
12687 if (Previous.isSingleResult())
12688 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12690 // If there is an identifier, use the location of the identifier as the
12691 // location of the decl, otherwise use the location of the struct/union
12693 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12695 // Otherwise, create a new declaration. If there is a previous
12696 // declaration of the same entity, the two will be linked via
12700 bool IsForwardReference = false;
12701 if (Kind == TTK_Enum) {
12702 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12703 // enum X { A, B, C } D; D should chain to X.
12704 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12705 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12706 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12707 // If this is an undefined enum, warn.
12708 if (TUK != TUK_Definition && !Invalid) {
12710 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12711 cast<EnumDecl>(New)->isFixed()) {
12712 // C++0x: 7.2p2: opaque-enum-declaration.
12713 // Conflicts are diagnosed above. Do nothing.
12715 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12716 Diag(Loc, diag::ext_forward_ref_enum_def)
12718 Diag(Def->getLocation(), diag::note_previous_definition);
12720 unsigned DiagID = diag::ext_forward_ref_enum;
12721 if (getLangOpts().MSVCCompat)
12722 DiagID = diag::ext_ms_forward_ref_enum;
12723 else if (getLangOpts().CPlusPlus)
12724 DiagID = diag::err_forward_ref_enum;
12727 // If this is a forward-declared reference to an enumeration, make a
12728 // note of it; we won't actually be introducing the declaration into
12729 // the declaration context.
12730 if (TUK == TUK_Reference)
12731 IsForwardReference = true;
12735 if (EnumUnderlying) {
12736 EnumDecl *ED = cast<EnumDecl>(New);
12737 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12738 ED->setIntegerTypeSourceInfo(TI);
12740 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12741 ED->setPromotionType(ED->getIntegerType());
12744 // struct/union/class
12746 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12747 // struct X { int A; } D; D should chain to X.
12748 if (getLangOpts().CPlusPlus) {
12749 // FIXME: Look for a way to use RecordDecl for simple structs.
12750 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12751 cast_or_null<CXXRecordDecl>(PrevDecl));
12753 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12754 StdBadAlloc = cast<CXXRecordDecl>(New);
12756 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12757 cast_or_null<RecordDecl>(PrevDecl));
12760 // C++11 [dcl.type]p3:
12761 // A type-specifier-seq shall not define a class or enumeration [...].
12762 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12763 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12764 << Context.getTagDeclType(New);
12768 // Maybe add qualifier info.
12769 if (SS.isNotEmpty()) {
12771 // If this is either a declaration or a definition, check the
12772 // nested-name-specifier against the current context. We don't do this
12773 // for explicit specializations, because they have similar checking
12774 // (with more specific diagnostics) in the call to
12775 // CheckMemberSpecialization, below.
12776 if (!isExplicitSpecialization &&
12777 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12778 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12781 New->setQualifierInfo(SS.getWithLocInContext(Context));
12782 if (TemplateParameterLists.size() > 0) {
12783 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12790 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12791 // Add alignment attributes if necessary; these attributes are checked when
12792 // the ASTContext lays out the structure.
12794 // It is important for implementing the correct semantics that this
12795 // happen here (in act on tag decl). The #pragma pack stack is
12796 // maintained as a result of parser callbacks which can occur at
12797 // many points during the parsing of a struct declaration (because
12798 // the #pragma tokens are effectively skipped over during the
12799 // parsing of the struct).
12800 if (TUK == TUK_Definition) {
12801 AddAlignmentAttributesForRecord(RD);
12802 AddMsStructLayoutForRecord(RD);
12806 if (ModulePrivateLoc.isValid()) {
12807 if (isExplicitSpecialization)
12808 Diag(New->getLocation(), diag::err_module_private_specialization)
12810 << FixItHint::CreateRemoval(ModulePrivateLoc);
12811 // __module_private__ does not apply to local classes. However, we only
12812 // diagnose this as an error when the declaration specifiers are
12813 // freestanding. Here, we just ignore the __module_private__.
12814 else if (!SearchDC->isFunctionOrMethod())
12815 New->setModulePrivate();
12818 // If this is a specialization of a member class (of a class template),
12819 // check the specialization.
12820 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12823 // If we're declaring or defining a tag in function prototype scope in C,
12824 // note that this type can only be used within the function and add it to
12825 // the list of decls to inject into the function definition scope.
12826 if ((Name || Kind == TTK_Enum) &&
12827 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12828 if (getLangOpts().CPlusPlus) {
12829 // C++ [dcl.fct]p6:
12830 // Types shall not be defined in return or parameter types.
12831 if (TUK == TUK_Definition && !IsTypeSpecifier) {
12832 Diag(Loc, diag::err_type_defined_in_param_type)
12836 } else if (!PrevDecl) {
12837 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12839 DeclsInPrototypeScope.push_back(New);
12843 New->setInvalidDecl();
12846 ProcessDeclAttributeList(S, New, Attr);
12848 // Set the lexical context. If the tag has a C++ scope specifier, the
12849 // lexical context will be different from the semantic context.
12850 New->setLexicalDeclContext(CurContext);
12852 // Mark this as a friend decl if applicable.
12853 // In Microsoft mode, a friend declaration also acts as a forward
12854 // declaration so we always pass true to setObjectOfFriendDecl to make
12855 // the tag name visible.
12856 if (TUK == TUK_Friend)
12857 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12859 // Set the access specifier.
12860 if (!Invalid && SearchDC->isRecord())
12861 SetMemberAccessSpecifier(New, PrevDecl, AS);
12863 if (TUK == TUK_Definition)
12864 New->startDefinition();
12866 // If this has an identifier, add it to the scope stack.
12867 if (TUK == TUK_Friend) {
12868 // We might be replacing an existing declaration in the lookup tables;
12869 // if so, borrow its access specifier.
12871 New->setAccess(PrevDecl->getAccess());
12873 DeclContext *DC = New->getDeclContext()->getRedeclContext();
12874 DC->makeDeclVisibleInContext(New);
12875 if (Name) // can be null along some error paths
12876 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12877 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12879 S = getNonFieldDeclScope(S);
12880 PushOnScopeChains(New, S, !IsForwardReference);
12881 if (IsForwardReference)
12882 SearchDC->makeDeclVisibleInContext(New);
12884 CurContext->addDecl(New);
12887 // If this is the C FILE type, notify the AST context.
12888 if (IdentifierInfo *II = New->getIdentifier())
12889 if (!New->isInvalidDecl() &&
12890 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12892 Context.setFILEDecl(New);
12895 mergeDeclAttributes(New, PrevDecl);
12897 // If there's a #pragma GCC visibility in scope, set the visibility of this
12899 AddPushedVisibilityAttribute(New);
12902 // In C++, don't return an invalid declaration. We can't recover well from
12903 // the cases where we make the type anonymous.
12904 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12907 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12908 AdjustDeclIfTemplate(TagD);
12909 TagDecl *Tag = cast<TagDecl>(TagD);
12911 // Enter the tag context.
12912 PushDeclContext(S, Tag);
12914 ActOnDocumentableDecl(TagD);
12916 // If there's a #pragma GCC visibility in scope, set the visibility of this
12918 AddPushedVisibilityAttribute(Tag);
12921 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12922 assert(isa<ObjCContainerDecl>(IDecl) &&
12923 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12924 DeclContext *OCD = cast<DeclContext>(IDecl);
12925 assert(getContainingDC(OCD) == CurContext &&
12926 "The next DeclContext should be lexically contained in the current one.");
12931 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12932 SourceLocation FinalLoc,
12933 bool IsFinalSpelledSealed,
12934 SourceLocation LBraceLoc) {
12935 AdjustDeclIfTemplate(TagD);
12936 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12938 FieldCollector->StartClass();
12940 if (!Record->getIdentifier())
12943 if (FinalLoc.isValid())
12944 Record->addAttr(new (Context)
12945 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12948 // [...] The class-name is also inserted into the scope of the
12949 // class itself; this is known as the injected-class-name. For
12950 // purposes of access checking, the injected-class-name is treated
12951 // as if it were a public member name.
12952 CXXRecordDecl *InjectedClassName
12953 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12954 Record->getLocStart(), Record->getLocation(),
12955 Record->getIdentifier(),
12956 /*PrevDecl=*/nullptr,
12957 /*DelayTypeCreation=*/true);
12958 Context.getTypeDeclType(InjectedClassName, Record);
12959 InjectedClassName->setImplicit();
12960 InjectedClassName->setAccess(AS_public);
12961 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12962 InjectedClassName->setDescribedClassTemplate(Template);
12963 PushOnScopeChains(InjectedClassName, S);
12964 assert(InjectedClassName->isInjectedClassName() &&
12965 "Broken injected-class-name");
12968 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12969 SourceLocation RBraceLoc) {
12970 AdjustDeclIfTemplate(TagD);
12971 TagDecl *Tag = cast<TagDecl>(TagD);
12972 Tag->setRBraceLoc(RBraceLoc);
12974 // Make sure we "complete" the definition even it is invalid.
12975 if (Tag->isBeingDefined()) {
12976 assert(Tag->isInvalidDecl() && "We should already have completed it");
12977 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12978 RD->completeDefinition();
12981 if (isa<CXXRecordDecl>(Tag))
12982 FieldCollector->FinishClass();
12984 // Exit this scope of this tag's definition.
12987 if (getCurLexicalContext()->isObjCContainer() &&
12988 Tag->getDeclContext()->isFileContext())
12989 Tag->setTopLevelDeclInObjCContainer();
12991 // Notify the consumer that we've defined a tag.
12992 if (!Tag->isInvalidDecl())
12993 Consumer.HandleTagDeclDefinition(Tag);
12996 void Sema::ActOnObjCContainerFinishDefinition() {
12997 // Exit this scope of this interface definition.
13001 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13002 assert(DC == CurContext && "Mismatch of container contexts");
13003 OriginalLexicalContext = DC;
13004 ActOnObjCContainerFinishDefinition();
13007 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13008 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13009 OriginalLexicalContext = nullptr;
13012 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13013 AdjustDeclIfTemplate(TagD);
13014 TagDecl *Tag = cast<TagDecl>(TagD);
13015 Tag->setInvalidDecl();
13017 // Make sure we "complete" the definition even it is invalid.
13018 if (Tag->isBeingDefined()) {
13019 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13020 RD->completeDefinition();
13023 // We're undoing ActOnTagStartDefinition here, not
13024 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13025 // the FieldCollector.
13030 // Note that FieldName may be null for anonymous bitfields.
13031 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13032 IdentifierInfo *FieldName,
13033 QualType FieldTy, bool IsMsStruct,
13034 Expr *BitWidth, bool *ZeroWidth) {
13035 // Default to true; that shouldn't confuse checks for emptiness
13039 // C99 6.7.2.1p4 - verify the field type.
13040 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13041 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13042 // Handle incomplete types with specific error.
13043 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13044 return ExprError();
13046 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13047 << FieldName << FieldTy << BitWidth->getSourceRange();
13048 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13049 << FieldTy << BitWidth->getSourceRange();
13050 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13051 UPPC_BitFieldWidth))
13052 return ExprError();
13054 // If the bit-width is type- or value-dependent, don't try to check
13056 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13059 llvm::APSInt Value;
13060 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13061 if (ICE.isInvalid())
13063 BitWidth = ICE.get();
13065 if (Value != 0 && ZeroWidth)
13066 *ZeroWidth = false;
13068 // Zero-width bitfield is ok for anonymous field.
13069 if (Value == 0 && FieldName)
13070 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13072 if (Value.isSigned() && Value.isNegative()) {
13074 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13075 << FieldName << Value.toString(10);
13076 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13077 << Value.toString(10);
13080 if (!FieldTy->isDependentType()) {
13081 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13082 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13083 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13085 // Over-wide bitfields are an error in C or when using the MSVC bitfield
13087 bool CStdConstraintViolation =
13088 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13089 bool MSBitfieldViolation =
13090 Value.ugt(TypeStorageSize) &&
13091 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13092 if (CStdConstraintViolation || MSBitfieldViolation) {
13093 unsigned DiagWidth =
13094 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13096 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13097 << FieldName << (unsigned)Value.getZExtValue()
13098 << !CStdConstraintViolation << DiagWidth;
13100 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13101 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13105 // Warn on types where the user might conceivably expect to get all
13106 // specified bits as value bits: that's all integral types other than
13108 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13110 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13111 << FieldName << (unsigned)Value.getZExtValue()
13112 << (unsigned)TypeWidth;
13114 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13115 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13122 /// ActOnField - Each field of a C struct/union is passed into this in order
13123 /// to create a FieldDecl object for it.
13124 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13125 Declarator &D, Expr *BitfieldWidth) {
13126 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13127 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13128 /*InitStyle=*/ICIS_NoInit, AS_public);
13132 /// HandleField - Analyze a field of a C struct or a C++ data member.
13134 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13135 SourceLocation DeclStart,
13136 Declarator &D, Expr *BitWidth,
13137 InClassInitStyle InitStyle,
13138 AccessSpecifier AS) {
13139 IdentifierInfo *II = D.getIdentifier();
13140 SourceLocation Loc = DeclStart;
13141 if (II) Loc = D.getIdentifierLoc();
13143 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13144 QualType T = TInfo->getType();
13145 if (getLangOpts().CPlusPlus) {
13146 CheckExtraCXXDefaultArguments(D);
13148 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13149 UPPC_DataMemberType)) {
13150 D.setInvalidType();
13152 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13156 // TR 18037 does not allow fields to be declared with address spaces.
13157 if (T.getQualifiers().hasAddressSpace()) {
13158 Diag(Loc, diag::err_field_with_address_space);
13159 D.setInvalidType();
13162 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13163 // used as structure or union field: image, sampler, event or block types.
13164 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13165 T->isSamplerT() || T->isBlockPointerType())) {
13166 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13167 D.setInvalidType();
13170 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13172 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13173 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13174 diag::err_invalid_thread)
13175 << DeclSpec::getSpecifierName(TSCS);
13177 // Check to see if this name was declared as a member previously
13178 NamedDecl *PrevDecl = nullptr;
13179 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13180 LookupName(Previous, S);
13181 switch (Previous.getResultKind()) {
13182 case LookupResult::Found:
13183 case LookupResult::FoundUnresolvedValue:
13184 PrevDecl = Previous.getAsSingle<NamedDecl>();
13187 case LookupResult::FoundOverloaded:
13188 PrevDecl = Previous.getRepresentativeDecl();
13191 case LookupResult::NotFound:
13192 case LookupResult::NotFoundInCurrentInstantiation:
13193 case LookupResult::Ambiguous:
13196 Previous.suppressDiagnostics();
13198 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13199 // Maybe we will complain about the shadowed template parameter.
13200 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13201 // Just pretend that we didn't see the previous declaration.
13202 PrevDecl = nullptr;
13205 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13206 PrevDecl = nullptr;
13209 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13210 SourceLocation TSSL = D.getLocStart();
13212 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13213 TSSL, AS, PrevDecl, &D);
13215 if (NewFD->isInvalidDecl())
13216 Record->setInvalidDecl();
13218 if (D.getDeclSpec().isModulePrivateSpecified())
13219 NewFD->setModulePrivate();
13221 if (NewFD->isInvalidDecl() && PrevDecl) {
13222 // Don't introduce NewFD into scope; there's already something
13223 // with the same name in the same scope.
13225 PushOnScopeChains(NewFD, S);
13227 Record->addDecl(NewFD);
13232 /// \brief Build a new FieldDecl and check its well-formedness.
13234 /// This routine builds a new FieldDecl given the fields name, type,
13235 /// record, etc. \p PrevDecl should refer to any previous declaration
13236 /// with the same name and in the same scope as the field to be
13239 /// \returns a new FieldDecl.
13241 /// \todo The Declarator argument is a hack. It will be removed once
13242 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13243 TypeSourceInfo *TInfo,
13244 RecordDecl *Record, SourceLocation Loc,
13245 bool Mutable, Expr *BitWidth,
13246 InClassInitStyle InitStyle,
13247 SourceLocation TSSL,
13248 AccessSpecifier AS, NamedDecl *PrevDecl,
13250 IdentifierInfo *II = Name.getAsIdentifierInfo();
13251 bool InvalidDecl = false;
13252 if (D) InvalidDecl = D->isInvalidType();
13254 // If we receive a broken type, recover by assuming 'int' and
13255 // marking this declaration as invalid.
13257 InvalidDecl = true;
13261 QualType EltTy = Context.getBaseElementType(T);
13262 if (!EltTy->isDependentType()) {
13263 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13264 // Fields of incomplete type force their record to be invalid.
13265 Record->setInvalidDecl();
13266 InvalidDecl = true;
13269 EltTy->isIncompleteType(&Def);
13270 if (Def && Def->isInvalidDecl()) {
13271 Record->setInvalidDecl();
13272 InvalidDecl = true;
13277 // OpenCL v1.2 s6.9.c: bitfields are not supported.
13278 if (BitWidth && getLangOpts().OpenCL) {
13279 Diag(Loc, diag::err_opencl_bitfields);
13280 InvalidDecl = true;
13283 // C99 6.7.2.1p8: A member of a structure or union may have any type other
13284 // than a variably modified type.
13285 if (!InvalidDecl && T->isVariablyModifiedType()) {
13286 bool SizeIsNegative;
13287 llvm::APSInt Oversized;
13289 TypeSourceInfo *FixedTInfo =
13290 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13294 Diag(Loc, diag::warn_illegal_constant_array_size);
13295 TInfo = FixedTInfo;
13296 T = FixedTInfo->getType();
13298 if (SizeIsNegative)
13299 Diag(Loc, diag::err_typecheck_negative_array_size);
13300 else if (Oversized.getBoolValue())
13301 Diag(Loc, diag::err_array_too_large)
13302 << Oversized.toString(10);
13304 Diag(Loc, diag::err_typecheck_field_variable_size);
13305 InvalidDecl = true;
13309 // Fields can not have abstract class types
13310 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13311 diag::err_abstract_type_in_decl,
13312 AbstractFieldType))
13313 InvalidDecl = true;
13315 bool ZeroWidth = false;
13317 BitWidth = nullptr;
13318 // If this is declared as a bit-field, check the bit-field.
13320 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13323 InvalidDecl = true;
13324 BitWidth = nullptr;
13329 // Check that 'mutable' is consistent with the type of the declaration.
13330 if (!InvalidDecl && Mutable) {
13331 unsigned DiagID = 0;
13332 if (T->isReferenceType())
13333 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13334 : diag::err_mutable_reference;
13335 else if (T.isConstQualified())
13336 DiagID = diag::err_mutable_const;
13339 SourceLocation ErrLoc = Loc;
13340 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13341 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13342 Diag(ErrLoc, DiagID);
13343 if (DiagID != diag::ext_mutable_reference) {
13345 InvalidDecl = true;
13350 // C++11 [class.union]p8 (DR1460):
13351 // At most one variant member of a union may have a
13352 // brace-or-equal-initializer.
13353 if (InitStyle != ICIS_NoInit)
13354 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13356 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13357 BitWidth, Mutable, InitStyle);
13359 NewFD->setInvalidDecl();
13361 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13362 Diag(Loc, diag::err_duplicate_member) << II;
13363 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13364 NewFD->setInvalidDecl();
13367 if (!InvalidDecl && getLangOpts().CPlusPlus) {
13368 if (Record->isUnion()) {
13369 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13370 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13371 if (RDecl->getDefinition()) {
13372 // C++ [class.union]p1: An object of a class with a non-trivial
13373 // constructor, a non-trivial copy constructor, a non-trivial
13374 // destructor, or a non-trivial copy assignment operator
13375 // cannot be a member of a union, nor can an array of such
13377 if (CheckNontrivialField(NewFD))
13378 NewFD->setInvalidDecl();
13382 // C++ [class.union]p1: If a union contains a member of reference type,
13383 // the program is ill-formed, except when compiling with MSVC extensions
13385 if (EltTy->isReferenceType()) {
13386 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13387 diag::ext_union_member_of_reference_type :
13388 diag::err_union_member_of_reference_type)
13389 << NewFD->getDeclName() << EltTy;
13390 if (!getLangOpts().MicrosoftExt)
13391 NewFD->setInvalidDecl();
13396 // FIXME: We need to pass in the attributes given an AST
13397 // representation, not a parser representation.
13399 // FIXME: The current scope is almost... but not entirely... correct here.
13400 ProcessDeclAttributes(getCurScope(), NewFD, *D);
13402 if (NewFD->hasAttrs())
13403 CheckAlignasUnderalignment(NewFD);
13406 // In auto-retain/release, infer strong retension for fields of
13407 // retainable type.
13408 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13409 NewFD->setInvalidDecl();
13411 if (T.isObjCGCWeak())
13412 Diag(Loc, diag::warn_attribute_weak_on_field);
13414 NewFD->setAccess(AS);
13418 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13420 assert(getLangOpts().CPlusPlus && "valid check only for C++");
13422 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13425 QualType EltTy = Context.getBaseElementType(FD->getType());
13426 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13427 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13428 if (RDecl->getDefinition()) {
13429 // We check for copy constructors before constructors
13430 // because otherwise we'll never get complaints about
13431 // copy constructors.
13433 CXXSpecialMember member = CXXInvalid;
13434 // We're required to check for any non-trivial constructors. Since the
13435 // implicit default constructor is suppressed if there are any
13436 // user-declared constructors, we just need to check that there is a
13437 // trivial default constructor and a trivial copy constructor. (We don't
13438 // worry about move constructors here, since this is a C++98 check.)
13439 if (RDecl->hasNonTrivialCopyConstructor())
13440 member = CXXCopyConstructor;
13441 else if (!RDecl->hasTrivialDefaultConstructor())
13442 member = CXXDefaultConstructor;
13443 else if (RDecl->hasNonTrivialCopyAssignment())
13444 member = CXXCopyAssignment;
13445 else if (RDecl->hasNonTrivialDestructor())
13446 member = CXXDestructor;
13448 if (member != CXXInvalid) {
13449 if (!getLangOpts().CPlusPlus11 &&
13450 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13451 // Objective-C++ ARC: it is an error to have a non-trivial field of
13452 // a union. However, system headers in Objective-C programs
13453 // occasionally have Objective-C lifetime objects within unions,
13454 // and rather than cause the program to fail, we make those
13455 // members unavailable.
13456 SourceLocation Loc = FD->getLocation();
13457 if (getSourceManager().isInSystemHeader(Loc)) {
13458 if (!FD->hasAttr<UnavailableAttr>())
13459 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13460 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13465 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13466 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13467 diag::err_illegal_union_or_anon_struct_member)
13468 << FD->getParent()->isUnion() << FD->getDeclName() << member;
13469 DiagnoseNontrivial(RDecl, member);
13470 return !getLangOpts().CPlusPlus11;
13478 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13479 /// AST enum value.
13480 static ObjCIvarDecl::AccessControl
13481 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13482 switch (ivarVisibility) {
13483 default: llvm_unreachable("Unknown visitibility kind");
13484 case tok::objc_private: return ObjCIvarDecl::Private;
13485 case tok::objc_public: return ObjCIvarDecl::Public;
13486 case tok::objc_protected: return ObjCIvarDecl::Protected;
13487 case tok::objc_package: return ObjCIvarDecl::Package;
13491 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13492 /// in order to create an IvarDecl object for it.
13493 Decl *Sema::ActOnIvar(Scope *S,
13494 SourceLocation DeclStart,
13495 Declarator &D, Expr *BitfieldWidth,
13496 tok::ObjCKeywordKind Visibility) {
13498 IdentifierInfo *II = D.getIdentifier();
13499 Expr *BitWidth = (Expr*)BitfieldWidth;
13500 SourceLocation Loc = DeclStart;
13501 if (II) Loc = D.getIdentifierLoc();
13503 // FIXME: Unnamed fields can be handled in various different ways, for
13504 // example, unnamed unions inject all members into the struct namespace!
13506 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13507 QualType T = TInfo->getType();
13510 // 6.7.2.1p3, 6.7.2.1p4
13511 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13513 D.setInvalidType();
13520 if (T->isReferenceType()) {
13521 Diag(Loc, diag::err_ivar_reference_type);
13522 D.setInvalidType();
13524 // C99 6.7.2.1p8: A member of a structure or union may have any type other
13525 // than a variably modified type.
13526 else if (T->isVariablyModifiedType()) {
13527 Diag(Loc, diag::err_typecheck_ivar_variable_size);
13528 D.setInvalidType();
13531 // Get the visibility (access control) for this ivar.
13532 ObjCIvarDecl::AccessControl ac =
13533 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13534 : ObjCIvarDecl::None;
13535 // Must set ivar's DeclContext to its enclosing interface.
13536 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13537 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13539 ObjCContainerDecl *EnclosingContext;
13540 if (ObjCImplementationDecl *IMPDecl =
13541 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13542 if (LangOpts.ObjCRuntime.isFragile()) {
13543 // Case of ivar declared in an implementation. Context is that of its class.
13544 EnclosingContext = IMPDecl->getClassInterface();
13545 assert(EnclosingContext && "Implementation has no class interface!");
13548 EnclosingContext = EnclosingDecl;
13550 if (ObjCCategoryDecl *CDecl =
13551 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13552 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13553 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13557 EnclosingContext = EnclosingDecl;
13560 // Construct the decl.
13561 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13562 DeclStart, Loc, II, T,
13563 TInfo, ac, (Expr *)BitfieldWidth);
13566 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13568 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13569 && !isa<TagDecl>(PrevDecl)) {
13570 Diag(Loc, diag::err_duplicate_member) << II;
13571 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13572 NewID->setInvalidDecl();
13576 // Process attributes attached to the ivar.
13577 ProcessDeclAttributes(S, NewID, D);
13579 if (D.isInvalidType())
13580 NewID->setInvalidDecl();
13582 // In ARC, infer 'retaining' for ivars of retainable type.
13583 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13584 NewID->setInvalidDecl();
13586 if (D.getDeclSpec().isModulePrivateSpecified())
13587 NewID->setModulePrivate();
13590 // FIXME: When interfaces are DeclContexts, we'll need to add
13591 // these to the interface.
13593 IdResolver.AddDecl(NewID);
13596 if (LangOpts.ObjCRuntime.isNonFragile() &&
13597 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13598 Diag(Loc, diag::warn_ivars_in_interface);
13603 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13604 /// class and class extensions. For every class \@interface and class
13605 /// extension \@interface, if the last ivar is a bitfield of any type,
13606 /// then add an implicit `char :0` ivar to the end of that interface.
13607 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13608 SmallVectorImpl<Decl *> &AllIvarDecls) {
13609 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13612 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13613 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13615 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13617 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13619 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13620 if (!CD->IsClassExtension())
13623 // No need to add this to end of @implementation.
13627 // All conditions are met. Add a new bitfield to the tail end of ivars.
13628 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13629 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13631 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13632 DeclLoc, DeclLoc, nullptr,
13634 Context.getTrivialTypeSourceInfo(Context.CharTy,
13636 ObjCIvarDecl::Private, BW,
13638 AllIvarDecls.push_back(Ivar);
13641 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13642 ArrayRef<Decl *> Fields, SourceLocation LBrac,
13643 SourceLocation RBrac, AttributeList *Attr) {
13644 assert(EnclosingDecl && "missing record or interface decl");
13646 // If this is an Objective-C @implementation or category and we have
13647 // new fields here we should reset the layout of the interface since
13648 // it will now change.
13649 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13650 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13651 switch (DC->getKind()) {
13653 case Decl::ObjCCategory:
13654 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13656 case Decl::ObjCImplementation:
13658 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13663 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13665 // Start counting up the number of named members; make sure to include
13666 // members of anonymous structs and unions in the total.
13667 unsigned NumNamedMembers = 0;
13669 for (const auto *I : Record->decls()) {
13670 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13671 if (IFD->getDeclName())
13676 // Verify that all the fields are okay.
13677 SmallVector<FieldDecl*, 32> RecFields;
13679 bool ARCErrReported = false;
13680 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13682 FieldDecl *FD = cast<FieldDecl>(*i);
13684 // Get the type for the field.
13685 const Type *FDTy = FD->getType().getTypePtr();
13687 if (!FD->isAnonymousStructOrUnion()) {
13688 // Remember all fields written by the user.
13689 RecFields.push_back(FD);
13692 // If the field is already invalid for some reason, don't emit more
13693 // diagnostics about it.
13694 if (FD->isInvalidDecl()) {
13695 EnclosingDecl->setInvalidDecl();
13700 // A structure or union shall not contain a member with
13701 // incomplete or function type (hence, a structure shall not
13702 // contain an instance of itself, but may contain a pointer to
13703 // an instance of itself), except that the last member of a
13704 // structure with more than one named member may have incomplete
13705 // array type; such a structure (and any union containing,
13706 // possibly recursively, a member that is such a structure)
13707 // shall not be a member of a structure or an element of an
13709 if (FDTy->isFunctionType()) {
13710 // Field declared as a function.
13711 Diag(FD->getLocation(), diag::err_field_declared_as_function)
13712 << FD->getDeclName();
13713 FD->setInvalidDecl();
13714 EnclosingDecl->setInvalidDecl();
13716 } else if (FDTy->isIncompleteArrayType() && Record &&
13717 ((i + 1 == Fields.end() && !Record->isUnion()) ||
13718 ((getLangOpts().MicrosoftExt ||
13719 getLangOpts().CPlusPlus) &&
13720 (i + 1 == Fields.end() || Record->isUnion())))) {
13721 // Flexible array member.
13722 // Microsoft and g++ is more permissive regarding flexible array.
13723 // It will accept flexible array in union and also
13724 // as the sole element of a struct/class.
13725 unsigned DiagID = 0;
13726 if (Record->isUnion())
13727 DiagID = getLangOpts().MicrosoftExt
13728 ? diag::ext_flexible_array_union_ms
13729 : getLangOpts().CPlusPlus
13730 ? diag::ext_flexible_array_union_gnu
13731 : diag::err_flexible_array_union;
13732 else if (Fields.size() == 1)
13733 DiagID = getLangOpts().MicrosoftExt
13734 ? diag::ext_flexible_array_empty_aggregate_ms
13735 : getLangOpts().CPlusPlus
13736 ? diag::ext_flexible_array_empty_aggregate_gnu
13737 : NumNamedMembers < 1
13738 ? diag::err_flexible_array_empty_aggregate
13742 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13743 << Record->getTagKind();
13744 // While the layout of types that contain virtual bases is not specified
13745 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13746 // virtual bases after the derived members. This would make a flexible
13747 // array member declared at the end of an object not adjacent to the end
13749 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13750 if (RD->getNumVBases() != 0)
13751 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13752 << FD->getDeclName() << Record->getTagKind();
13753 if (!getLangOpts().C99)
13754 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13755 << FD->getDeclName() << Record->getTagKind();
13757 // If the element type has a non-trivial destructor, we would not
13758 // implicitly destroy the elements, so disallow it for now.
13760 // FIXME: GCC allows this. We should probably either implicitly delete
13761 // the destructor of the containing class, or just allow this.
13762 QualType BaseElem = Context.getBaseElementType(FD->getType());
13763 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13764 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13765 << FD->getDeclName() << FD->getType();
13766 FD->setInvalidDecl();
13767 EnclosingDecl->setInvalidDecl();
13770 // Okay, we have a legal flexible array member at the end of the struct.
13771 Record->setHasFlexibleArrayMember(true);
13772 } else if (!FDTy->isDependentType() &&
13773 RequireCompleteType(FD->getLocation(), FD->getType(),
13774 diag::err_field_incomplete)) {
13776 FD->setInvalidDecl();
13777 EnclosingDecl->setInvalidDecl();
13779 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13780 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13781 // A type which contains a flexible array member is considered to be a
13782 // flexible array member.
13783 Record->setHasFlexibleArrayMember(true);
13784 if (!Record->isUnion()) {
13785 // If this is a struct/class and this is not the last element, reject
13786 // it. Note that GCC supports variable sized arrays in the middle of
13788 if (i + 1 != Fields.end())
13789 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13790 << FD->getDeclName() << FD->getType();
13792 // We support flexible arrays at the end of structs in
13793 // other structs as an extension.
13794 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13795 << FD->getDeclName();
13799 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13800 RequireNonAbstractType(FD->getLocation(), FD->getType(),
13801 diag::err_abstract_type_in_decl,
13802 AbstractIvarType)) {
13803 // Ivars can not have abstract class types
13804 FD->setInvalidDecl();
13806 if (Record && FDTTy->getDecl()->hasObjectMember())
13807 Record->setHasObjectMember(true);
13808 if (Record && FDTTy->getDecl()->hasVolatileMember())
13809 Record->setHasVolatileMember(true);
13810 } else if (FDTy->isObjCObjectType()) {
13811 /// A field cannot be an Objective-c object
13812 Diag(FD->getLocation(), diag::err_statically_allocated_object)
13813 << FixItHint::CreateInsertion(FD->getLocation(), "*");
13814 QualType T = Context.getObjCObjectPointerType(FD->getType());
13816 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13817 (!getLangOpts().CPlusPlus || Record->isUnion())) {
13818 // It's an error in ARC if a field has lifetime.
13819 // We don't want to report this in a system header, though,
13820 // so we just make the field unavailable.
13821 // FIXME: that's really not sufficient; we need to make the type
13822 // itself invalid to, say, initialize or copy.
13823 QualType T = FD->getType();
13824 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13825 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13826 SourceLocation loc = FD->getLocation();
13827 if (getSourceManager().isInSystemHeader(loc)) {
13828 if (!FD->hasAttr<UnavailableAttr>()) {
13829 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13830 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13833 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13834 << T->isBlockPointerType() << Record->getTagKind();
13836 ARCErrReported = true;
13838 } else if (getLangOpts().ObjC1 &&
13839 getLangOpts().getGC() != LangOptions::NonGC &&
13840 Record && !Record->hasObjectMember()) {
13841 if (FD->getType()->isObjCObjectPointerType() ||
13842 FD->getType().isObjCGCStrong())
13843 Record->setHasObjectMember(true);
13844 else if (Context.getAsArrayType(FD->getType())) {
13845 QualType BaseType = Context.getBaseElementType(FD->getType());
13846 if (BaseType->isRecordType() &&
13847 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13848 Record->setHasObjectMember(true);
13849 else if (BaseType->isObjCObjectPointerType() ||
13850 BaseType.isObjCGCStrong())
13851 Record->setHasObjectMember(true);
13854 if (Record && FD->getType().isVolatileQualified())
13855 Record->setHasVolatileMember(true);
13856 // Keep track of the number of named members.
13857 if (FD->getIdentifier())
13861 // Okay, we successfully defined 'Record'.
13863 bool Completed = false;
13864 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13865 if (!CXXRecord->isInvalidDecl()) {
13866 // Set access bits correctly on the directly-declared conversions.
13867 for (CXXRecordDecl::conversion_iterator
13868 I = CXXRecord->conversion_begin(),
13869 E = CXXRecord->conversion_end(); I != E; ++I)
13870 I.setAccess((*I)->getAccess());
13873 if (!CXXRecord->isDependentType()) {
13874 if (CXXRecord->hasUserDeclaredDestructor()) {
13875 // Adjust user-defined destructor exception spec.
13876 if (getLangOpts().CPlusPlus11)
13877 AdjustDestructorExceptionSpec(CXXRecord,
13878 CXXRecord->getDestructor());
13881 if (!CXXRecord->isInvalidDecl()) {
13882 // Add any implicitly-declared members to this class.
13883 AddImplicitlyDeclaredMembersToClass(CXXRecord);
13885 // If we have virtual base classes, we may end up finding multiple
13886 // final overriders for a given virtual function. Check for this
13888 if (CXXRecord->getNumVBases()) {
13889 CXXFinalOverriderMap FinalOverriders;
13890 CXXRecord->getFinalOverriders(FinalOverriders);
13892 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13893 MEnd = FinalOverriders.end();
13895 for (OverridingMethods::iterator SO = M->second.begin(),
13896 SOEnd = M->second.end();
13897 SO != SOEnd; ++SO) {
13898 assert(SO->second.size() > 0 &&
13899 "Virtual function without overridding functions?");
13900 if (SO->second.size() == 1)
13903 // C++ [class.virtual]p2:
13904 // In a derived class, if a virtual member function of a base
13905 // class subobject has more than one final overrider the
13906 // program is ill-formed.
13907 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13908 << (const NamedDecl *)M->first << Record;
13909 Diag(M->first->getLocation(),
13910 diag::note_overridden_virtual_function);
13911 for (OverridingMethods::overriding_iterator
13912 OM = SO->second.begin(),
13913 OMEnd = SO->second.end();
13915 Diag(OM->Method->getLocation(), diag::note_final_overrider)
13916 << (const NamedDecl *)M->first << OM->Method->getParent();
13918 Record->setInvalidDecl();
13921 CXXRecord->completeDefinition(&FinalOverriders);
13929 Record->completeDefinition();
13931 if (Record->hasAttrs()) {
13932 CheckAlignasUnderalignment(Record);
13934 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13935 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13936 IA->getRange(), IA->getBestCase(),
13937 IA->getSemanticSpelling());
13940 // Check if the structure/union declaration is a type that can have zero
13941 // size in C. For C this is a language extension, for C++ it may cause
13942 // compatibility problems.
13943 bool CheckForZeroSize;
13944 if (!getLangOpts().CPlusPlus) {
13945 CheckForZeroSize = true;
13947 // For C++ filter out types that cannot be referenced in C code.
13948 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13950 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13951 !CXXRecord->isDependentType() &&
13952 CXXRecord->isCLike();
13954 if (CheckForZeroSize) {
13955 bool ZeroSize = true;
13956 bool IsEmpty = true;
13957 unsigned NonBitFields = 0;
13958 for (RecordDecl::field_iterator I = Record->field_begin(),
13959 E = Record->field_end();
13960 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13962 if (I->isUnnamedBitfield()) {
13963 if (I->getBitWidthValue(Context) > 0)
13967 QualType FieldType = I->getType();
13968 if (FieldType->isIncompleteType() ||
13969 !Context.getTypeSizeInChars(FieldType).isZero())
13974 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13975 // allowed in C++, but warn if its declaration is inside
13976 // extern "C" block.
13978 Diag(RecLoc, getLangOpts().CPlusPlus ?
13979 diag::warn_zero_size_struct_union_in_extern_c :
13980 diag::warn_zero_size_struct_union_compat)
13981 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13984 // Structs without named members are extension in C (C99 6.7.2.1p7),
13985 // but are accepted by GCC.
13986 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13987 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13988 diag::ext_no_named_members_in_struct_union)
13989 << Record->isUnion();
13993 ObjCIvarDecl **ClsFields =
13994 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13995 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13996 ID->setEndOfDefinitionLoc(RBrac);
13997 // Add ivar's to class's DeclContext.
13998 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13999 ClsFields[i]->setLexicalDeclContext(ID);
14000 ID->addDecl(ClsFields[i]);
14002 // Must enforce the rule that ivars in the base classes may not be
14004 if (ID->getSuperClass())
14005 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14006 } else if (ObjCImplementationDecl *IMPDecl =
14007 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14008 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14009 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14010 // Ivar declared in @implementation never belongs to the implementation.
14011 // Only it is in implementation's lexical context.
14012 ClsFields[I]->setLexicalDeclContext(IMPDecl);
14013 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14014 IMPDecl->setIvarLBraceLoc(LBrac);
14015 IMPDecl->setIvarRBraceLoc(RBrac);
14016 } else if (ObjCCategoryDecl *CDecl =
14017 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14018 // case of ivars in class extension; all other cases have been
14019 // reported as errors elsewhere.
14020 // FIXME. Class extension does not have a LocEnd field.
14021 // CDecl->setLocEnd(RBrac);
14022 // Add ivar's to class extension's DeclContext.
14023 // Diagnose redeclaration of private ivars.
14024 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14025 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14027 if (const ObjCIvarDecl *ClsIvar =
14028 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14029 Diag(ClsFields[i]->getLocation(),
14030 diag::err_duplicate_ivar_declaration);
14031 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14034 for (const auto *Ext : IDecl->known_extensions()) {
14035 if (const ObjCIvarDecl *ClsExtIvar
14036 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14037 Diag(ClsFields[i]->getLocation(),
14038 diag::err_duplicate_ivar_declaration);
14039 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14044 ClsFields[i]->setLexicalDeclContext(CDecl);
14045 CDecl->addDecl(ClsFields[i]);
14047 CDecl->setIvarLBraceLoc(LBrac);
14048 CDecl->setIvarRBraceLoc(RBrac);
14053 ProcessDeclAttributeList(S, Record, Attr);
14056 /// \brief Determine whether the given integral value is representable within
14057 /// the given type T.
14058 static bool isRepresentableIntegerValue(ASTContext &Context,
14059 llvm::APSInt &Value,
14061 assert(T->isIntegralType(Context) && "Integral type required!");
14062 unsigned BitWidth = Context.getIntWidth(T);
14064 if (Value.isUnsigned() || Value.isNonNegative()) {
14065 if (T->isSignedIntegerOrEnumerationType())
14067 return Value.getActiveBits() <= BitWidth;
14069 return Value.getMinSignedBits() <= BitWidth;
14072 // \brief Given an integral type, return the next larger integral type
14073 // (or a NULL type of no such type exists).
14074 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14075 // FIXME: Int128/UInt128 support, which also needs to be introduced into
14076 // enum checking below.
14077 assert(T->isIntegralType(Context) && "Integral type required!");
14078 const unsigned NumTypes = 4;
14079 QualType SignedIntegralTypes[NumTypes] = {
14080 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14082 QualType UnsignedIntegralTypes[NumTypes] = {
14083 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14084 Context.UnsignedLongLongTy
14087 unsigned BitWidth = Context.getTypeSize(T);
14088 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14089 : UnsignedIntegralTypes;
14090 for (unsigned I = 0; I != NumTypes; ++I)
14091 if (Context.getTypeSize(Types[I]) > BitWidth)
14097 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14098 EnumConstantDecl *LastEnumConst,
14099 SourceLocation IdLoc,
14100 IdentifierInfo *Id,
14102 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14103 llvm::APSInt EnumVal(IntWidth);
14106 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14110 Val = DefaultLvalueConversion(Val).get();
14113 if (Enum->isDependentType() || Val->isTypeDependent())
14114 EltTy = Context.DependentTy;
14116 SourceLocation ExpLoc;
14117 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14118 !getLangOpts().MSVCCompat) {
14119 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14120 // constant-expression in the enumerator-definition shall be a converted
14121 // constant expression of the underlying type.
14122 EltTy = Enum->getIntegerType();
14123 ExprResult Converted =
14124 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14126 if (Converted.isInvalid())
14129 Val = Converted.get();
14130 } else if (!Val->isValueDependent() &&
14131 !(Val = VerifyIntegerConstantExpression(Val,
14132 &EnumVal).get())) {
14133 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14135 if (Enum->isFixed()) {
14136 EltTy = Enum->getIntegerType();
14138 // In Obj-C and Microsoft mode, require the enumeration value to be
14139 // representable in the underlying type of the enumeration. In C++11,
14140 // we perform a non-narrowing conversion as part of converted constant
14141 // expression checking.
14142 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14143 if (getLangOpts().MSVCCompat) {
14144 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14145 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14147 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14149 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14150 } else if (getLangOpts().CPlusPlus) {
14151 // C++11 [dcl.enum]p5:
14152 // If the underlying type is not fixed, the type of each enumerator
14153 // is the type of its initializing value:
14154 // - If an initializer is specified for an enumerator, the
14155 // initializing value has the same type as the expression.
14156 EltTy = Val->getType();
14159 // The expression that defines the value of an enumeration constant
14160 // shall be an integer constant expression that has a value
14161 // representable as an int.
14163 // Complain if the value is not representable in an int.
14164 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14165 Diag(IdLoc, diag::ext_enum_value_not_int)
14166 << EnumVal.toString(10) << Val->getSourceRange()
14167 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14168 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14169 // Force the type of the expression to 'int'.
14170 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14172 EltTy = Val->getType();
14179 if (Enum->isDependentType())
14180 EltTy = Context.DependentTy;
14181 else if (!LastEnumConst) {
14182 // C++0x [dcl.enum]p5:
14183 // If the underlying type is not fixed, the type of each enumerator
14184 // is the type of its initializing value:
14185 // - If no initializer is specified for the first enumerator, the
14186 // initializing value has an unspecified integral type.
14188 // GCC uses 'int' for its unspecified integral type, as does
14190 if (Enum->isFixed()) {
14191 EltTy = Enum->getIntegerType();
14194 EltTy = Context.IntTy;
14197 // Assign the last value + 1.
14198 EnumVal = LastEnumConst->getInitVal();
14200 EltTy = LastEnumConst->getType();
14202 // Check for overflow on increment.
14203 if (EnumVal < LastEnumConst->getInitVal()) {
14204 // C++0x [dcl.enum]p5:
14205 // If the underlying type is not fixed, the type of each enumerator
14206 // is the type of its initializing value:
14208 // - Otherwise the type of the initializing value is the same as
14209 // the type of the initializing value of the preceding enumerator
14210 // unless the incremented value is not representable in that type,
14211 // in which case the type is an unspecified integral type
14212 // sufficient to contain the incremented value. If no such type
14213 // exists, the program is ill-formed.
14214 QualType T = getNextLargerIntegralType(Context, EltTy);
14215 if (T.isNull() || Enum->isFixed()) {
14216 // There is no integral type larger enough to represent this
14217 // value. Complain, then allow the value to wrap around.
14218 EnumVal = LastEnumConst->getInitVal();
14219 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14221 if (Enum->isFixed())
14222 // When the underlying type is fixed, this is ill-formed.
14223 Diag(IdLoc, diag::err_enumerator_wrapped)
14224 << EnumVal.toString(10)
14227 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14228 << EnumVal.toString(10);
14233 // Retrieve the last enumerator's value, extent that type to the
14234 // type that is supposed to be large enough to represent the incremented
14235 // value, then increment.
14236 EnumVal = LastEnumConst->getInitVal();
14237 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14238 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14241 // If we're not in C++, diagnose the overflow of enumerator values,
14242 // which in C99 means that the enumerator value is not representable in
14243 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14244 // permits enumerator values that are representable in some larger
14246 if (!getLangOpts().CPlusPlus && !T.isNull())
14247 Diag(IdLoc, diag::warn_enum_value_overflow);
14248 } else if (!getLangOpts().CPlusPlus &&
14249 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14250 // Enforce C99 6.7.2.2p2 even when we compute the next value.
14251 Diag(IdLoc, diag::ext_enum_value_not_int)
14252 << EnumVal.toString(10) << 1;
14257 if (!EltTy->isDependentType()) {
14258 // Make the enumerator value match the signedness and size of the
14259 // enumerator's type.
14260 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14261 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14264 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14268 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14269 SourceLocation IILoc) {
14270 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14271 !getLangOpts().CPlusPlus)
14272 return SkipBodyInfo();
14274 // We have an anonymous enum definition. Look up the first enumerator to
14275 // determine if we should merge the definition with an existing one and
14277 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14279 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14281 return SkipBodyInfo();
14283 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14285 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14287 Skip.Previous = Hidden;
14291 return SkipBodyInfo();
14294 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14295 SourceLocation IdLoc, IdentifierInfo *Id,
14296 AttributeList *Attr,
14297 SourceLocation EqualLoc, Expr *Val) {
14298 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14299 EnumConstantDecl *LastEnumConst =
14300 cast_or_null<EnumConstantDecl>(lastEnumConst);
14302 // The scope passed in may not be a decl scope. Zip up the scope tree until
14303 // we find one that is.
14304 S = getNonFieldDeclScope(S);
14306 // Verify that there isn't already something declared with this name in this
14308 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14310 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14311 // Maybe we will complain about the shadowed template parameter.
14312 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14313 // Just pretend that we didn't see the previous declaration.
14314 PrevDecl = nullptr;
14317 // C++ [class.mem]p15:
14318 // If T is the name of a class, then each of the following shall have a name
14319 // different from T:
14320 // - every enumerator of every member of class T that is an unscoped
14322 if (!TheEnumDecl->isScoped())
14323 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14324 DeclarationNameInfo(Id, IdLoc));
14326 EnumConstantDecl *New =
14327 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14332 // When in C++, we may get a TagDecl with the same name; in this case the
14333 // enum constant will 'hide' the tag.
14334 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14335 "Received TagDecl when not in C++!");
14336 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14337 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14338 if (isa<EnumConstantDecl>(PrevDecl))
14339 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14341 Diag(IdLoc, diag::err_redefinition) << Id;
14342 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14347 // Process attributes.
14348 if (Attr) ProcessDeclAttributeList(S, New, Attr);
14350 // Register this decl in the current scope stack.
14351 New->setAccess(TheEnumDecl->getAccess());
14352 PushOnScopeChains(New, S);
14354 ActOnDocumentableDecl(New);
14359 // Returns true when the enum initial expression does not trigger the
14360 // duplicate enum warning. A few common cases are exempted as follows:
14361 // Element2 = Element1
14362 // Element2 = Element1 + 1
14363 // Element2 = Element1 - 1
14364 // Where Element2 and Element1 are from the same enum.
14365 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14366 Expr *InitExpr = ECD->getInitExpr();
14369 InitExpr = InitExpr->IgnoreImpCasts();
14371 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14372 if (!BO->isAdditiveOp())
14374 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14377 if (IL->getValue() != 1)
14380 InitExpr = BO->getLHS();
14383 // This checks if the elements are from the same enum.
14384 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14388 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14392 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14402 bool isTombstoneOrEmptyKey;
14403 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14404 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14407 static DupKey GetDupKey(const llvm::APSInt& Val) {
14408 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14412 struct DenseMapInfoDupKey {
14413 static DupKey getEmptyKey() { return DupKey(0, true); }
14414 static DupKey getTombstoneKey() { return DupKey(1, true); }
14415 static unsigned getHashValue(const DupKey Key) {
14416 return (unsigned)(Key.val * 37);
14418 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14419 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14420 LHS.val == RHS.val;
14423 } // end anonymous namespace
14425 // Emits a warning when an element is implicitly set a value that
14426 // a previous element has already been set to.
14427 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14429 QualType EnumType) {
14430 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14432 // Avoid anonymous enums
14433 if (!Enum->getIdentifier())
14436 // Only check for small enums.
14437 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14440 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14441 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14443 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14444 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14447 DuplicatesVector DupVector;
14448 ValueToVectorMap EnumMap;
14450 // Populate the EnumMap with all values represented by enum constants without
14452 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14453 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14455 // Null EnumConstantDecl means a previous diagnostic has been emitted for
14456 // this constant. Skip this enum since it may be ill-formed.
14461 if (ECD->getInitExpr())
14464 DupKey Key = GetDupKey(ECD->getInitVal());
14465 DeclOrVector &Entry = EnumMap[Key];
14467 // First time encountering this value.
14468 if (Entry.isNull())
14472 // Create vectors for any values that has duplicates.
14473 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14474 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14475 if (!ValidDuplicateEnum(ECD, Enum))
14478 DupKey Key = GetDupKey(ECD->getInitVal());
14480 DeclOrVector& Entry = EnumMap[Key];
14481 if (Entry.isNull())
14484 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14485 // Ensure constants are different.
14489 // Create new vector and push values onto it.
14490 ECDVector *Vec = new ECDVector();
14492 Vec->push_back(ECD);
14494 // Update entry to point to the duplicates vector.
14497 // Store the vector somewhere we can consult later for quick emission of
14499 DupVector.push_back(Vec);
14503 ECDVector *Vec = Entry.get<ECDVector*>();
14504 // Make sure constants are not added more than once.
14505 if (*Vec->begin() == ECD)
14508 Vec->push_back(ECD);
14511 // Emit diagnostics.
14512 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14513 DupVectorEnd = DupVector.end();
14514 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14515 ECDVector *Vec = *DupVectorIter;
14516 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14518 // Emit warning for one enum constant.
14519 ECDVector::iterator I = Vec->begin();
14520 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14521 << (*I)->getName() << (*I)->getInitVal().toString(10)
14522 << (*I)->getSourceRange();
14525 // Emit one note for each of the remaining enum constants with
14527 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14528 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14529 << (*I)->getName() << (*I)->getInitVal().toString(10)
14530 << (*I)->getSourceRange();
14535 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14536 bool AllowMask) const {
14537 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14538 assert(ED->isCompleteDefinition() && "expected enum definition");
14540 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14541 llvm::APInt &FlagBits = R.first->second;
14544 for (auto *E : ED->enumerators()) {
14545 const auto &EVal = E->getInitVal();
14546 // Only single-bit enumerators introduce new flag values.
14547 if (EVal.isPowerOf2())
14548 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14552 // A value is in a flag enum if either its bits are a subset of the enum's
14553 // flag bits (the first condition) or we are allowing masks and the same is
14554 // true of its complement (the second condition). When masks are allowed, we
14555 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14557 // While it's true that any value could be used as a mask, the assumption is
14558 // that a mask will have all of the insignificant bits set. Anything else is
14559 // likely a logic error.
14560 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14561 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14564 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14565 SourceLocation RBraceLoc, Decl *EnumDeclX,
14566 ArrayRef<Decl *> Elements,
14567 Scope *S, AttributeList *Attr) {
14568 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14569 QualType EnumType = Context.getTypeDeclType(Enum);
14572 ProcessDeclAttributeList(S, Enum, Attr);
14574 if (Enum->isDependentType()) {
14575 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14576 EnumConstantDecl *ECD =
14577 cast_or_null<EnumConstantDecl>(Elements[i]);
14578 if (!ECD) continue;
14580 ECD->setType(EnumType);
14583 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14587 // TODO: If the result value doesn't fit in an int, it must be a long or long
14588 // long value. ISO C does not support this, but GCC does as an extension,
14590 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14591 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14592 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14594 // Verify that all the values are okay, compute the size of the values, and
14595 // reverse the list.
14596 unsigned NumNegativeBits = 0;
14597 unsigned NumPositiveBits = 0;
14599 // Keep track of whether all elements have type int.
14600 bool AllElementsInt = true;
14602 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14603 EnumConstantDecl *ECD =
14604 cast_or_null<EnumConstantDecl>(Elements[i]);
14605 if (!ECD) continue; // Already issued a diagnostic.
14607 const llvm::APSInt &InitVal = ECD->getInitVal();
14609 // Keep track of the size of positive and negative values.
14610 if (InitVal.isUnsigned() || InitVal.isNonNegative())
14611 NumPositiveBits = std::max(NumPositiveBits,
14612 (unsigned)InitVal.getActiveBits());
14614 NumNegativeBits = std::max(NumNegativeBits,
14615 (unsigned)InitVal.getMinSignedBits());
14617 // Keep track of whether every enum element has type int (very commmon).
14618 if (AllElementsInt)
14619 AllElementsInt = ECD->getType() == Context.IntTy;
14622 // Figure out the type that should be used for this enum.
14624 unsigned BestWidth;
14626 // C++0x N3000 [conv.prom]p3:
14627 // An rvalue of an unscoped enumeration type whose underlying
14628 // type is not fixed can be converted to an rvalue of the first
14629 // of the following types that can represent all the values of
14630 // the enumeration: int, unsigned int, long int, unsigned long
14631 // int, long long int, or unsigned long long int.
14633 // An identifier declared as an enumeration constant has type int.
14634 // The C99 rule is modified by a gcc extension
14635 QualType BestPromotionType;
14637 bool Packed = Enum->hasAttr<PackedAttr>();
14638 // -fshort-enums is the equivalent to specifying the packed attribute on all
14639 // enum definitions.
14640 if (LangOpts.ShortEnums)
14643 if (Enum->isFixed()) {
14644 BestType = Enum->getIntegerType();
14645 if (BestType->isPromotableIntegerType())
14646 BestPromotionType = Context.getPromotedIntegerType(BestType);
14648 BestPromotionType = BestType;
14650 BestWidth = Context.getIntWidth(BestType);
14652 else if (NumNegativeBits) {
14653 // If there is a negative value, figure out the smallest integer type (of
14654 // int/long/longlong) that fits.
14655 // If it's packed, check also if it fits a char or a short.
14656 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14657 BestType = Context.SignedCharTy;
14658 BestWidth = CharWidth;
14659 } else if (Packed && NumNegativeBits <= ShortWidth &&
14660 NumPositiveBits < ShortWidth) {
14661 BestType = Context.ShortTy;
14662 BestWidth = ShortWidth;
14663 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14664 BestType = Context.IntTy;
14665 BestWidth = IntWidth;
14667 BestWidth = Context.getTargetInfo().getLongWidth();
14669 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14670 BestType = Context.LongTy;
14672 BestWidth = Context.getTargetInfo().getLongLongWidth();
14674 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14675 Diag(Enum->getLocation(), diag::ext_enum_too_large);
14676 BestType = Context.LongLongTy;
14679 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14681 // If there is no negative value, figure out the smallest type that fits
14682 // all of the enumerator values.
14683 // If it's packed, check also if it fits a char or a short.
14684 if (Packed && NumPositiveBits <= CharWidth) {
14685 BestType = Context.UnsignedCharTy;
14686 BestPromotionType = Context.IntTy;
14687 BestWidth = CharWidth;
14688 } else if (Packed && NumPositiveBits <= ShortWidth) {
14689 BestType = Context.UnsignedShortTy;
14690 BestPromotionType = Context.IntTy;
14691 BestWidth = ShortWidth;
14692 } else if (NumPositiveBits <= IntWidth) {
14693 BestType = Context.UnsignedIntTy;
14694 BestWidth = IntWidth;
14696 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14697 ? Context.UnsignedIntTy : Context.IntTy;
14698 } else if (NumPositiveBits <=
14699 (BestWidth = Context.getTargetInfo().getLongWidth())) {
14700 BestType = Context.UnsignedLongTy;
14702 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14703 ? Context.UnsignedLongTy : Context.LongTy;
14705 BestWidth = Context.getTargetInfo().getLongLongWidth();
14706 assert(NumPositiveBits <= BestWidth &&
14707 "How could an initializer get larger than ULL?");
14708 BestType = Context.UnsignedLongLongTy;
14710 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14711 ? Context.UnsignedLongLongTy : Context.LongLongTy;
14715 // Loop over all of the enumerator constants, changing their types to match
14716 // the type of the enum if needed.
14717 for (auto *D : Elements) {
14718 auto *ECD = cast_or_null<EnumConstantDecl>(D);
14719 if (!ECD) continue; // Already issued a diagnostic.
14721 // Standard C says the enumerators have int type, but we allow, as an
14722 // extension, the enumerators to be larger than int size. If each
14723 // enumerator value fits in an int, type it as an int, otherwise type it the
14724 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
14725 // that X has type 'int', not 'unsigned'.
14727 // Determine whether the value fits into an int.
14728 llvm::APSInt InitVal = ECD->getInitVal();
14730 // If it fits into an integer type, force it. Otherwise force it to match
14731 // the enum decl type.
14735 if (!getLangOpts().CPlusPlus &&
14736 !Enum->isFixed() &&
14737 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14738 NewTy = Context.IntTy;
14739 NewWidth = IntWidth;
14741 } else if (ECD->getType() == BestType) {
14742 // Already the right type!
14743 if (getLangOpts().CPlusPlus)
14744 // C++ [dcl.enum]p4: Following the closing brace of an
14745 // enum-specifier, each enumerator has the type of its
14747 ECD->setType(EnumType);
14751 NewWidth = BestWidth;
14752 NewSign = BestType->isSignedIntegerOrEnumerationType();
14755 // Adjust the APSInt value.
14756 InitVal = InitVal.extOrTrunc(NewWidth);
14757 InitVal.setIsSigned(NewSign);
14758 ECD->setInitVal(InitVal);
14760 // Adjust the Expr initializer and type.
14761 if (ECD->getInitExpr() &&
14762 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14763 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14765 ECD->getInitExpr(),
14766 /*base paths*/ nullptr,
14768 if (getLangOpts().CPlusPlus)
14769 // C++ [dcl.enum]p4: Following the closing brace of an
14770 // enum-specifier, each enumerator has the type of its
14772 ECD->setType(EnumType);
14774 ECD->setType(NewTy);
14777 Enum->completeDefinition(BestType, BestPromotionType,
14778 NumPositiveBits, NumNegativeBits);
14780 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14782 if (Enum->hasAttr<FlagEnumAttr>()) {
14783 for (Decl *D : Elements) {
14784 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14785 if (!ECD) continue; // Already issued a diagnostic.
14787 llvm::APSInt InitVal = ECD->getInitVal();
14788 if (InitVal != 0 && !InitVal.isPowerOf2() &&
14789 !IsValueInFlagEnum(Enum, InitVal, true))
14790 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14795 // Now that the enum type is defined, ensure it's not been underaligned.
14796 if (Enum->hasAttrs())
14797 CheckAlignasUnderalignment(Enum);
14800 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14801 SourceLocation StartLoc,
14802 SourceLocation EndLoc) {
14803 StringLiteral *AsmString = cast<StringLiteral>(expr);
14805 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14806 AsmString, StartLoc,
14808 CurContext->addDecl(New);
14812 static void checkModuleImportContext(Sema &S, Module *M,
14813 SourceLocation ImportLoc, DeclContext *DC,
14814 bool FromInclude = false) {
14815 SourceLocation ExternCLoc;
14817 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14818 switch (LSD->getLanguage()) {
14819 case LinkageSpecDecl::lang_c:
14820 if (ExternCLoc.isInvalid())
14821 ExternCLoc = LSD->getLocStart();
14823 case LinkageSpecDecl::lang_cxx:
14826 DC = LSD->getParent();
14829 while (isa<LinkageSpecDecl>(DC))
14830 DC = DC->getParent();
14832 if (!isa<TranslationUnitDecl>(DC)) {
14833 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14834 ? diag::ext_module_import_not_at_top_level_noop
14835 : diag::err_module_import_not_at_top_level_fatal)
14836 << M->getFullModuleName() << DC;
14837 S.Diag(cast<Decl>(DC)->getLocStart(),
14838 diag::note_module_import_not_at_top_level) << DC;
14839 } else if (!M->IsExternC && ExternCLoc.isValid()) {
14840 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14841 << M->getFullModuleName();
14842 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14846 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14847 return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14850 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14851 SourceLocation ImportLoc,
14852 ModuleIdPath Path) {
14854 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14855 /*IsIncludeDirective=*/false);
14859 VisibleModules.setVisible(Mod, ImportLoc);
14861 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14863 // FIXME: we should support importing a submodule within a different submodule
14864 // of the same top-level module. Until we do, make it an error rather than
14865 // silently ignoring the import.
14866 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14867 Diag(ImportLoc, getLangOpts().CompilingModule
14868 ? diag::err_module_self_import
14869 : diag::err_module_import_in_implementation)
14870 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14872 SmallVector<SourceLocation, 2> IdentifierLocs;
14873 Module *ModCheck = Mod;
14874 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14875 // If we've run out of module parents, just drop the remaining identifiers.
14876 // We need the length to be consistent.
14879 ModCheck = ModCheck->Parent;
14881 IdentifierLocs.push_back(Path[I].second);
14884 ImportDecl *Import = ImportDecl::Create(Context,
14885 Context.getTranslationUnitDecl(),
14886 AtLoc.isValid()? AtLoc : ImportLoc,
14887 Mod, IdentifierLocs);
14888 Context.getTranslationUnitDecl()->addDecl(Import);
14892 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14893 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14895 // Determine whether we're in the #include buffer for a module. The #includes
14896 // in that buffer do not qualify as module imports; they're just an
14897 // implementation detail of us building the module.
14899 // FIXME: Should we even get ActOnModuleInclude calls for those?
14900 bool IsInModuleIncludes =
14901 TUKind == TU_Module &&
14902 getSourceManager().isWrittenInMainFile(DirectiveLoc);
14904 // Similarly, if we're in the implementation of a module, don't
14905 // synthesize an illegal module import. FIXME: Why not?
14906 bool ShouldAddImport =
14907 !IsInModuleIncludes &&
14908 (getLangOpts().CompilingModule ||
14909 getLangOpts().CurrentModule.empty() ||
14910 getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
14912 // If this module import was due to an inclusion directive, create an
14913 // implicit import declaration to capture it in the AST.
14914 if (ShouldAddImport) {
14915 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14916 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14919 TU->addDecl(ImportD);
14920 Consumer.HandleImplicitImportDecl(ImportD);
14923 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14924 VisibleModules.setVisible(Mod, DirectiveLoc);
14927 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14928 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14930 if (getLangOpts().ModulesLocalVisibility)
14931 VisibleModulesStack.push_back(std::move(VisibleModules));
14932 VisibleModules.setVisible(Mod, DirectiveLoc);
14935 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14936 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14938 if (getLangOpts().ModulesLocalVisibility) {
14939 VisibleModules = std::move(VisibleModulesStack.back());
14940 VisibleModulesStack.pop_back();
14941 VisibleModules.setVisible(Mod, DirectiveLoc);
14942 // Leaving a module hides namespace names, so our visible namespace cache
14943 // is now out of date.
14944 VisibleNamespaceCache.clear();
14948 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14950 // Bail if we're not allowed to implicitly import a module here.
14951 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14954 // Create the implicit import declaration.
14955 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14956 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14958 TU->addDecl(ImportD);
14959 Consumer.HandleImplicitImportDecl(ImportD);
14961 // Make the module visible.
14962 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14963 VisibleModules.setVisible(Mod, Loc);
14966 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
14967 IdentifierInfo* AliasName,
14968 SourceLocation PragmaLoc,
14969 SourceLocation NameLoc,
14970 SourceLocation AliasNameLoc) {
14971 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14972 LookupOrdinaryName);
14973 AsmLabelAttr *Attr =
14974 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14976 // If a declaration that:
14977 // 1) declares a function or a variable
14978 // 2) has external linkage
14979 // already exists, add a label attribute to it.
14980 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14981 if (isDeclExternC(PrevDecl))
14982 PrevDecl->addAttr(Attr);
14984 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
14985 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
14986 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14988 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14991 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14992 SourceLocation PragmaLoc,
14993 SourceLocation NameLoc) {
14994 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14997 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14999 (void)WeakUndeclaredIdentifiers.insert(
15000 std::pair<IdentifierInfo*,WeakInfo>
15001 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15005 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15006 IdentifierInfo* AliasName,
15007 SourceLocation PragmaLoc,
15008 SourceLocation NameLoc,
15009 SourceLocation AliasNameLoc) {
15010 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15011 LookupOrdinaryName);
15012 WeakInfo W = WeakInfo(Name, NameLoc);
15014 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15015 if (!PrevDecl->hasAttr<AliasAttr>())
15016 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15017 DeclApplyPragmaWeak(TUScope, ND, W);
15019 (void)WeakUndeclaredIdentifiers.insert(
15020 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15024 Decl *Sema::getObjCDeclContext() const {
15025 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15028 AvailabilityResult Sema::getCurContextAvailability() const {
15029 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15031 return AR_Available;
15033 // If we are within an Objective-C method, we should consult
15034 // both the availability of the method as well as the
15035 // enclosing class. If the class is (say) deprecated,
15036 // the entire method is considered deprecated from the
15037 // purpose of checking if the current context is deprecated.
15038 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15039 AvailabilityResult R = MD->getAvailability();
15040 if (R != AR_Available)
15042 D = MD->getClassInterface();
15044 // If we are within an Objective-c @implementation, it
15045 // gets the same availability context as the @interface.
15046 else if (const ObjCImplementationDecl *ID =
15047 dyn_cast<ObjCImplementationDecl>(D)) {
15048 D = ID->getClassInterface();
15050 // Recover from user error.
15051 return D ? D->getAvailability() : AR_Available;